当前位置: 首页>>代码示例>>Python>>正文


Python db.rollback_transaction函数代码示例

本文整理汇总了Python中south.db.db.rollback_transaction函数的典型用法代码示例。如果您正苦于以下问题:Python rollback_transaction函数的具体用法?Python rollback_transaction怎么用?Python rollback_transaction使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了rollback_transaction函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: forwards

    def forwards(self, orm):
        # If there are duplicated documents, we'll have an error when we try to
        # create this index. So to protect against that, we should delete those
        # documents before we create the index.

        # We need to wrap the data migration and alter operation in separate transactions for PostgreSQL
        # See: http://south.readthedocs.org/en/latest/migrationstructure.html#transactions
        try:
            db.start_transaction()
            duplicated_records = Document.objects \
                .values('content_type_id', 'object_id') \
                .annotate(id_count=models.Count('id')) \
                .filter(id_count__gt=1)

            # Delete all but the first document.
            for record in duplicated_records:
                docs = Document.objects \
                    .values_list('id', flat=True) \
                    .filter(
                        content_type_id=record['content_type_id'],
                        object_id=record['object_id'],
                    )[1:]

                docs = list(docs)

                logging.warn('Deleting documents %s' % docs)

                Document.objects.filter(id__in=docs).delete()
            db.commit_transaction()
        except Exception, e:
            db.rollback_transaction()
            raise e
开发者ID:18600597055,项目名称:hue,代码行数:32,代码来源:0014_auto__add_unique_document_content_type_object_id.py

示例2: test_alter_column_postgres_multiword

    def test_alter_column_postgres_multiword(self):
        """
        Tests altering columns with multiple words in Postgres types (issue #125)
        e.g. 'datetime with time zone', look at django/db/backends/postgresql/creation.py
        """
        db.create_table("test_multiword", [
            ('col_datetime', models.DateTimeField(null=True)),
            ('col_integer', models.PositiveIntegerField(null=True)),
            ('col_smallint', models.PositiveSmallIntegerField(null=True)),
            ('col_float', models.FloatField(null=True)),
        ])
        
        # test if 'double precision' is preserved
        db.alter_column('test_multiword', 'col_float', models.FloatField('float', null=True))

        # test if 'CHECK ("%(column)s" >= 0)' is stripped
        db.alter_column('test_multiword', 'col_integer', models.PositiveIntegerField(null=True))
        db.alter_column('test_multiword', 'col_smallint', models.PositiveSmallIntegerField(null=True))

        # test if 'with timezone' is preserved
        if db.backend_name == "postgres":
            db.start_transaction()
            db.execute("INSERT INTO test_multiword (col_datetime) VALUES ('2009-04-24 14:20:55+02')")
            db.alter_column('test_multiword', 'col_datetime', models.DateTimeField(auto_now=True))
            assert db.execute("SELECT col_datetime = '2009-04-24 14:20:55+02' FROM test_multiword")[0][0]
            db.rollback_transaction()

        
        db.delete_table("test_multiword")
开发者ID:NoUsername,项目名称:PrivateNotesExperimental,代码行数:29,代码来源:db.py

示例3: run_backwards

def run_backwards(app, migrations, ignore=[], fake=False, db_dry_run=False, silent=False):
    """
    Runs the specified migrations backwards, in order, skipping those
    migrations in 'ignore'.
    """
    for migration in migrations:
        if migration not in ignore:
            app_name = get_app_name(app)
            if not silent:
                print " < %s: %s" % (app_name, migration)
            klass = get_migration(app, migration)
            if fake:
                if not silent:
                    print "   (faked)"
            else:
                if db_dry_run:
                    db.dry_run = True
                
                db.start_transaction()
                try:
                    klass().backwards()
                    db.execute_deferred_sql()
                except:
                    db.rollback_transaction()
                    raise
                else:
                    db.commit_transaction()

            if not db_dry_run:
                # Record us as having not done this
                record = MigrationHistory.for_migration(app_name, migration)
                record.delete()
开发者ID:akaihola,项目名称:django-south,代码行数:32,代码来源:migration.py

示例4: run_forwards

def run_forwards(app, migrations, fake=False, db_dry_run=False, silent=False):
    """
    Runs the specified migrations forwards, in order.
    """
    for migration in migrations:
        app_name = get_app_name(app)
        if not silent:
            print " > %s: %s" % (app_name, migration)
        klass = get_migration(app, migration)

        if fake:
            if not silent:
                print "   (faked)"
        else:
            if db_dry_run:
                db.dry_run = True
                
            db.start_transaction()
            try:
                klass().forwards()
                db.execute_deferred_sql()
            except:
                db.rollback_transaction()
                raise
            else:
                db.commit_transaction()

        if not db_dry_run:
            # Record us as having done this
            record = MigrationHistory.for_migration(app_name, migration)
            record.applied = datetime.datetime.utcnow()
            record.save()
开发者ID:akaihola,项目名称:django-south,代码行数:32,代码来源:migration.py

示例5: test_dry_rename

 def test_dry_rename(self):
     """
     Test column renaming while --dry-run is turned on (should do nothing)
     See ticket #65
     """
     cursor = connection.cursor()
     db.create_table("test_drn", [('spam', models.BooleanField(default=False))])
     # Make sure we can select the column
     cursor.execute("SELECT spam FROM test_drn")
     # Rename it
     db.dry_run = True
     db.rename_column("test_drn", "spam", "eggs")
     db.dry_run = False
     cursor.execute("SELECT spam FROM test_drn")
     db.commit_transaction()
     db.start_transaction()
     try:
         cursor.execute("SELECT eggs FROM test_drn")
     except:
         pass
     else:
         self.fail("Dry-renamed new column could be selected!")
     db.rollback_transaction()
     db.delete_table("test_drn")
     db.start_transaction()
开发者ID:TradeHill2011,项目名称:south,代码行数:25,代码来源:db.py

示例6: drop_field

def drop_field(app_name, model_name, field_name):
    """
    Drop the given field from the app's model
    """
    # Table is typically appname_modelname, but it could be different
    #   always best to be sure.
    from .fields import CategoryM2MField, CategoryFKField
    from .settings import FIELD_REGISTRY
    try:
        from south.db import db
    except ImportError:
        raise ImproperlyConfigured(_('%(dependency) must be installed for this command to work') %
                                   {'dependency' : 'South'})
    mdl = models.get_model(app_name, model_name)

    fld = '%s.%s.%s' % (app_name, model_name, field_name)

    if isinstance(FIELD_REGISTRY[fld], CategoryFKField):
        print (_('Dropping ForeignKey %(field_name) from %(model_name)') %
               {'field_name' : field_name, 'model_name' : model_name})
        try:
            db.start_transaction()
            table_name = mdl._meta.db_table
            db.delete_column(table_name, field_name)
            db.commit_transaction()
        except DatabaseError, e:
            db.rollback_transaction()
            raise e
开发者ID:9gix,项目名称:django-categories,代码行数:28,代码来源:migration.py

示例7: test_alter_constraints

 def test_alter_constraints(self):
     """
     Tests that going from a PostiveIntegerField to an IntegerField drops
     the constraint on the database.
     """
     # Only applies to databases that support CHECK constraints
     if not db.has_check_constraints:
         return
     # Make the test table
     db.create_table("test_alterc", [
         ('num', models.PositiveIntegerField()),
     ])
     # Add in some test values
     db.execute("INSERT INTO test_alterc (num) VALUES (1)")
     db.execute("INSERT INTO test_alterc (num) VALUES (2)")
     # Ensure that adding a negative number is bad
     db.commit_transaction()
     db.start_transaction()
     try:
         db.execute("INSERT INTO test_alterc (num) VALUES (-3)")
     except:
         db.rollback_transaction()
     else:
         self.fail("Could insert a negative integer into a PositiveIntegerField.")
     # Alter it to a normal IntegerField
     db.alter_column("test_alterc", "num", models.IntegerField())
     # It should now work
     db.execute("INSERT INTO test_alterc (num) VALUES (-3)")
     db.delete_table("test_alterc")
     # We need to match up for tearDown
     db.start_transaction()
开发者ID:TradeHill2011,项目名称:south,代码行数:31,代码来源:db.py

示例8: _class_prepared_handler

    def _class_prepared_handler(sender, **kwargs):
        """ Signal handler for class_prepared. 
            This will be run for every model, looking for the moment when all
            dependent models are prepared for the first time. It will then run
            the given function, only once.
        """

        sender_app=sender._meta.app_label.lower()+'.'+sender._meta.object_name
        already_prepared=set([sender_app])
        for app,models in app_cache.app_models.items():
            for model_name,model in models.items():
                already_prepared.add(app.lower()+'.'+model_name)
                
        if all([x in already_prepared for x in dependencies]):
            db.start_transaction()
            try:
                # We need to disconnect, otherwise each new dynamo model generation
                # will trigger it and cause a "maximim recursion error"
                class_prepared.disconnect(_class_prepared_handler,weak=False)                
                fn()
            except DatabaseError, message:
                # If tables are  missing altogether, not much we can do
                # until syncdb/migrate is run. "The code must go on" in this 
                # case, without running our function completely. At least
                # database operations will be rolled back.
                db.rollback_transaction()
                # Better connect again
                if message<>'no such table: dynamo_metamodel':
                    class_prepared.connect(_class_prepared_handler, weak=False)
                else:
                    raise
            else:
                db.commit_transaction()
开发者ID:das-10,项目名称:django-dynamo,代码行数:33,代码来源:handlers.py

示例9: forwards

    def forwards(self, orm):

        # move some models from maps to layers app
        
        # 0. add some missing fields (not for wfp)
        db.start_transaction()
        try:
            # Adding field 'Layer.bbox_top'
            db.add_column('maps_layer', 'bbox_top', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False)
            # Adding field 'Layer.bbox_bottom'
            db.add_column('maps_layer', 'bbox_bottom', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False)
            # Adding field 'Layer.bbox_left'
            db.add_column('maps_layer', 'bbox_left', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False)
            # Adding field 'Layer.bbox_right'
            db.add_column('maps_layer', 'bbox_right', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False)
            db.commit_transaction()
        except:
            print 'No need to create the fields, they are already there'
            db.rollback_transaction()
            
        # 1. layers_layer moved from maps_layer
        db.rename_table('maps_layer', 'layers_layer') 
        if not db.dry_run:
            orm['contenttypes.contenttype'].objects.filter(app_label='maps', model='layer').update(app_label='layers')
            
        # 2. layers_contactrole moved from maps_contactrole
        db.rename_table('maps_contactrole', 'layers_contactrole') 
        if not db.dry_run:
            orm['contenttypes.contenttype'].objects.filter(app_label='maps', model='contactrole').update(app_label='layers')
开发者ID:EricSchles,项目名称:geonode,代码行数:29,代码来源:0003_move_models_to_layers.py

示例10: forwards

    def forwards(self, orm):

        # Removing unique constraint on 'BadgeData', fields ['type', 'name']
        db.delete_unique('askbot_badgedata', ['type', 'name'])

        # Deleting field 'BadgeData.multiple'
        db.delete_column('askbot_badgedata', 'multiple')

        # Deleting field 'BadgeData.description'
        db.delete_column('askbot_badgedata', 'description')


        # Deleting field 'BadgeData.type'
        db.delete_column('askbot_badgedata', 'type')

        # Deleting field 'BadgeData.name'
        db.delete_column('askbot_badgedata', 'name')

        # Changing field 'BadgeData.slug'
        db.alter_column('askbot_badgedata', 'slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50))
        # Adding unique constraint on 'BadgeData', fields ['slug']
        return
        try:#work around the South 0.7.3 bug
            db.start_transaction()
            db.create_unique('askbot_badgedata', ['slug'])
            db.commit_transaction()
        except:
            db.rollback_transaction()
开发者ID:AndurilLi,项目名称:askbot-devel,代码行数:28,代码来源:0032_auto__del_field_badgedata_multiple__del_field_badgedata_description__d.py

示例11: test_text_default

 def test_text_default(self):
     """
     MySQL cannot have blank defaults on TEXT columns.
     """
     db.start_transaction()
     try:
         db.create_table("test_textdef", [("textcol", models.TextField(blank=True))])
     finally:
         db.rollback_transaction()
开发者ID:qiwihui,项目名称:johan-doc,代码行数:9,代码来源:db.py

示例12: done_migrate

 def done_migrate(self, migration):
     db.start_transaction()
     try:
         # Record us as having done this
         self.record(migration)
     except:
         db.rollback_transaction()
         raise
     else:
         db.commit_transaction()
开发者ID:notanumber,项目名称:south,代码行数:10,代码来源:migrators.py

示例13: migrate_app

def migrate_app(app, *args, **kwargs):
    """
    Migrate all models of this app registered
    """
    try:
        from south.db import db
    except ImportError:
        raise ImproperlyConfigured("South must be installed for this command to work")

    # pull the information from the registry
    if not isinstance(app, basestring):
        return
    fields = [fld for fld in FIELD_REGISTRY.keys() if fld.startswith(app)]

    # call the south commands to add the fields/tables
    for fld in fields:
        app_name, model_name, field_name = fld.split('.')

        # Table is typically appname_modelname, but it could be different
        #   always best to be sure.
        mdl = models.get_model(app_name, model_name)

        if isinstance(FIELD_REGISTRY[fld], CategoryFKField):
            print "Adding ForeignKey %s to %s" % (field_name, model_name)
            try:
                db.start_transaction()
                table_name = mdl._meta.db_table
                FIELD_REGISTRY[fld].default = -1
                db.add_column(table_name, field_name, FIELD_REGISTRY[fld], keep_default=False)
                db.commit_transaction()
            except DatabaseError, e:
                db.rollback_transaction()
                if "already exists" in str(e):
                    print "Already exists"
                else:
                    raise e
        elif isinstance(FIELD_REGISTRY[fld], CategoryM2MField):
            print "Adding Many2Many table between %s and %s" % (model_name, 'category')
            table_name = "%s_%s" % (mdl._meta.db_table, 'categories')
            try:
                db.start_transaction()
                db.create_table(table_name, (
                    ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
                    (model_name, models.ForeignKey(mdl, null=False)),
                    ('category', models.ForeignKey(Category, null=False))
                ))
                db.create_unique(table_name, ['%s_id' % model_name, 'category_id'])
                db.commit_transaction()
            except DatabaseError, e:
                db.rollback_transaction()
                if "already exists" in str(e):
                    print "Already exists"
                else:
                    raise e
开发者ID:liberation,项目名称:django-categories,代码行数:54,代码来源:migration.py

示例14: ignore_exists

def ignore_exists(fun, *args, **kwargs):
    try:
        fun(*args, **kwargs)
    except Exception, exc:
        if "exists" in str(exc):
            # don't panic, everything is ok: it's just a hack
            if db.has_ddl_transactions:
                db.rollback_transaction()
                db.start_transaction()
            return False
        raise
开发者ID:UQ-CMM-Mirage,项目名称:django-celery,代码行数:11,代码来源:0002_v25_changes.py

示例15: test_capitalised_constraints

 def test_capitalised_constraints(self):
     """
     Under PostgreSQL at least, capitalised constrains must be quoted.
     """
     db.start_transaction()
     try:
         db.create_table("test_capconst", [("SOMECOL", models.PositiveIntegerField(primary_key=True))])
         # Alter it so it's not got the check constraint
         db.alter_column("test_capconst", "SOMECOL", models.IntegerField())
     finally:
         db.rollback_transaction()
开发者ID:qiwihui,项目名称:johan-doc,代码行数:11,代码来源:db.py


注:本文中的south.db.db.rollback_transaction函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。