Example #1
0
    def test_reuse_cursor_reference(self):
        """
        Make sure transaction closure is enforced even when the queries are performed
        through a single cursor reference retrieved in the beginning
        (this is to show why it is wrong to set the transaction dirty only when a cursor
        is fetched from the connection).
        """
        @commit_on_success
        def reuse_cursor_ref():
            """
            Fetch a cursor, perform an query, rollback to close the transaction,
            then write a record (in a new transaction) using the same cursor object
            (reference). All this under commit_on_success, so the second insert should
            be committed.
            """
            cursor = connection.cursor()
            cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
            transaction.rollback()
            cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")

        reuse_cursor_ref()
        # Rollback so that if the decorator didn't commit, the record is unwritten
        transaction.rollback()
        try:
            # Check that the record is in the DB
            obj = Mod.objects.get(pk=1)
            self.assertEqual(obj.fld, 2)
        except Mod.DoesNotExist:
            self.fail("After ending a transaction, cursor use no longer sets dirty")
Example #2
0
 def test_bad_sql(self):
     """
     Regression for #11900: If a function wrapped by commit_on_success
     writes a transaction that can't be committed, that transaction should
     be rolled back. The bug is only visible using the psycopg2 backend,
     though the fix is generally a good idea.
     """
     execute_bad_sql = transaction.commit_on_success(self.execute_bad_sql)
     self.assertRaises(IntegrityError, execute_bad_sql)
     transaction.rollback()
Example #3
0
 def reuse_cursor_ref():
     """
     Fetch a cursor, perform an query, rollback to close the transaction,
     then write a record (in a new transaction) using the same cursor object
     (reference). All this under commit_on_success, so the second insert should
     be committed.
     """
     cursor = connection.cursor()
     cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
     transaction.rollback()
     cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
Example #4
0
    def test_syncdb(self):
        with transaction.commit_manually():
            Book.objects.all().delete()

            management.call_command(
                'syncdb',
                verbosity=0,
                load_initial_data=False
            )
            self.assertQuerysetEqual(Book.objects.all(), [])
            transaction.rollback()
Example #5
0
 def ticket_11101(self):
     management.call_command(
         'loaddata',
         'thingy.json',
         verbosity=0,
         commit=False
     )
     self.assertEqual(Thingy.objects.count(), 1)
     transaction.rollback()
     self.assertEqual(Thingy.objects.count(), 0)
     transaction.commit()
Example #6
0
    def test_manyrelated_add_commit(self):
        "Test for https://code.djangoproject.com/ticket/16818"
        a = M2mA.objects.create()
        b = M2mB.objects.create(fld=10)
        a.others.add(b)

        # We're in a TransactionTestCase and have not changed transaction
        # behavior from default of "autocommit", so this rollback should not
        # actually do anything. If it does in fact undo our add, that's a bug
        # that the bulk insert was not auto-committed.
        transaction.rollback()
        self.assertEqual(a.others.count(), 1)
Example #7
0
 def test_bad_sql(self):
     """
     Regression for #11900: If a block wrapped by commit_on_success
     writes a transaction that can't be committed, that transaction should
     be rolled back. The bug is only visible using the psycopg2 backend,
     though the fix is generally a good idea.
     """
     with self.assertRaises(IntegrityError):
         with transaction.commit_on_success():
             cursor = connection.cursor()
             cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');")
             transaction.set_dirty()
     transaction.rollback()
Example #8
0
    def _fixture_teardown(self):
        if not connections_support_transactions():
            return super(TestCase, self)._fixture_teardown()

        # If the test case has a multi_db=True flag, teardown all databases.
        # Otherwise, just teardown default.
        if getattr(self, 'multi_db', False):
            databases = connections
        else:
            databases = [DEFAULT_DB_ALIAS]

        restore_transaction_methods()
        for db in databases:
            transaction.rollback(using=db)
            transaction.leave_transaction_management(using=db)
Example #9
0
    def test_flush(self):
        # Test presence of fixture (flush called by TransactionTestCase)
        self.assertQuerysetEqual(
            Book.objects.all(), [
                'Achieving self-awareness of Python programs'
            ],
            lambda a: a.name
        )

        with transaction.commit_manually():
            management.call_command(
                'flush',
                verbosity=0,
                interactive=False,
                commit=False,
                load_initial_data=False
            )
            self.assertQuerysetEqual(Book.objects.all(), [])
            transaction.rollback()
Example #10
0
 def test_check_constraints(self):
     """
     Constraint checks should raise an IntegrityError when bad data is in the DB.
     """
     with transaction.commit_manually():
         # Create an Article.
         models.Article.objects.create(
             headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r
         )
         # Retrive it from the DB
         a = models.Article.objects.get(headline="Test article")
         a.reporter_id = 30
         try:
             with connection.constraint_checks_disabled():
                 a.save()
                 with self.assertRaises(IntegrityError):
                     connection.check_constraints()
         finally:
             transaction.rollback()
Example #11
0
 def test_disable_constraint_checks_context_manager(self):
     """
     When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.
     """
     with transaction.commit_manually():
         # Create an Article.
         models.Article.objects.create(
             headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r
         )
         # Retrive it from the DB
         a = models.Article.objects.get(headline="Test article")
         a.reporter_id = 30
         try:
             with connection.constraint_checks_disabled():
                 a.save()
         except IntegrityError:
             self.fail("IntegrityError should not have occurred.")
         finally:
             transaction.rollback()
Example #12
0
    def test_raw_committed_on_success(self):
        """
        Make sure a transaction consisting of raw SQL execution gets
        committed by the commit_on_success decorator.
        """
        @commit_on_success
        def raw_sql():
            "Write a record using raw sql under a commit_on_success decorator"
            cursor = connection.cursor()
            cursor.execute("INSERT into transactions_regress_mod (id,fld) values (17,18)")

        raw_sql()
        # Rollback so that if the decorator didn't commit, the record is unwritten
        transaction.rollback()
        try:
            # Check that the record is in the DB
            obj = Mod.objects.get(pk=17)
            self.assertEqual(obj.fld, 18)
        except Mod.DoesNotExist:
            self.fail("transaction with raw sql not committed")
Example #13
0
 def roller_back():
     """
     Perform a database query, then rollback the transaction
     """
     _ = Mod.objects.count()
     transaction.rollback()
Example #14
0
 def process_exception(self, request, exception):
     """Rolls back the database and leaves transaction management"""
     if transaction.is_dirty():
         transaction.rollback()
     transaction.leave_transaction_management()
Example #15
0
    def handle(self, *fixture_labels, **options):
        using = options.get('database')

        connection = connections[using]

        if not len(fixture_labels):
            raise CommandError(
                "No database fixture specified. Please provide the path of at "
                "least one fixture in the command line."
            )

        verbosity = int(options.get('verbosity'))
        show_traceback = options.get('traceback')

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: "'%s'" % dirname if dirname else 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   open,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]

        try:
            with connection.constraint_checks_disabled():
                for fixture_label in fixture_labels:
                    parts = fixture_label.split('.')

                    if len(parts) > 1 and parts[-1] in compression_types:
                        compression_formats = [parts[-1]]
                        parts = parts[:-1]
                    else:
                        compression_formats = compression_types.keys()

                    if len(parts) == 1:
                        fixture_name = parts[0]
                        formats = serializers.get_public_serializer_formats()
                    else:
                        fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                        if format in serializers.get_public_serializer_formats():
                            formats = [format]
                        else:
                            formats = []

                    if formats:
                        if verbosity >= 2:
                            self.stdout.write("Loading '%s' fixtures..." % fixture_name)
                    else:
                        raise CommandError(
                            "Problem installing fixture '%s': %s is not a known serialization format." %
                                (fixture_name, format))

                    if os.path.isabs(fixture_name):
                        fixture_dirs = [fixture_name]
                    else:
                        fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

                    for fixture_dir in fixture_dirs:
                        if verbosity >= 2:
                            self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir))

                        label_found = False
                        for combo in product([using, None], formats, compression_formats):
                            database, format, compression_format = combo
                            file_name = '.'.join(
                                p for p in [
                                    fixture_name, database, format, compression_format
                                ]
                                if p
                            )

                            if verbosity >= 3:
                                self.stdout.write("Trying %s for %s fixture '%s'..." % \
                                    (humanize(fixture_dir), file_name, fixture_name))
                            full_path = os.path.join(fixture_dir, file_name)
                            open_method = compression_types[compression_format]
                            try:
                                fixture = open_method(full_path, 'r')
                            except IOError:
                                if verbosity >= 2:
                                    self.stdout.write("No %s fixture '%s' in %s." % \
                                        (format, fixture_name, humanize(fixture_dir)))
                            else:
                                try:
                                    if label_found:
                                        raise CommandError("Multiple fixtures named '%s' in %s. Aborting." %
                                            (fixture_name, humanize(fixture_dir)))

                                    fixture_count += 1
                                    objects_in_fixture = 0
                                    loaded_objects_in_fixture = 0
                                    if verbosity >= 2:
                                        self.stdout.write("Installing %s fixture '%s' from %s." % \
                                            (format, fixture_name, humanize(fixture_dir)))

                                    objects = serializers.deserialize(format, fixture, using=using)

                                    for obj in objects:
                                        objects_in_fixture += 1
                                        if router.allow_syncdb(using, obj.object.__class__):
                                            loaded_objects_in_fixture += 1
                                            models.add(obj.object.__class__)
                                            try:
                                                obj.save(using=using)
                                            except (DatabaseError, IntegrityError) as e:
                                                e.args = ("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                        'app_label': obj.object._meta.app_label,
                                                        'object_name': obj.object._meta.object_name,
                                                        'pk': obj.object.pk,
                                                        'error_msg': force_text(e)
                                                    },)
                                                raise

                                    loaded_object_count += loaded_objects_in_fixture
                                    fixture_object_count += objects_in_fixture
                                    label_found = True
                                except Exception as e:
                                    if not isinstance(e, CommandError):
                                        e.args = ("Problem installing fixture '%s': %s" % (full_path, e),)
                                    raise
                                finally:
                                    fixture.close()

                                # If the fixture we loaded contains 0 objects, assume that an
                                # error was encountered during fixture loading.
                                if objects_in_fixture == 0:
                                    raise CommandError(
                                        "No fixture data found for '%s'. (File format may be invalid.)" %
                                            (fixture_name))

            # Since we disabled constraint checks, we must manually check for
            # any invalid keys that might have been added
            table_names = [model._meta.db_table for model in models]
            try:
                connection.check_constraints(table_names=table_names)
            except Exception as e:
                e.args = ("Problem installing fixtures: %s" % e,)
                raise

        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception as e:
            if commit:
                transaction.rollback(using=using)
                transaction.leave_transaction_management(using=using)
            raise

        # If we found even one object in a fixture, we need to reset the
        # database sequences.
        if loaded_object_count > 0:
            sequence_sql = connection.ops.sequence_reset_sql(no_style(), models)
            if sequence_sql:
                if verbosity >= 2:
                    self.stdout.write("Resetting sequences\n")
                for line in sequence_sql:
                    cursor.execute(line)

        if commit:
            transaction.commit(using=using)
            transaction.leave_transaction_management(using=using)

        if verbosity >= 1:
            if fixture_object_count == loaded_object_count:
                self.stdout.write("Installed %d object(s) from %d fixture(s)" % (
                    loaded_object_count, fixture_count))
            else:
                self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)" % (
                    loaded_object_count, fixture_object_count, fixture_count))

        # Close the DB connection. This is required as a workaround for an
        # edge case in MySQL: if the same connection is used to
        # create tables, load data, and query, the query can return
        # incorrect results. See Django #7572, MySQL #37735.
        if commit:
            connection.close()