• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python db.rollback_transaction函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: run_migration

 def run_migration(self, migration):
     migration_function = self.direction(migration)
     db.start_transaction()
     try:
         migration_function()
         db.execute_deferred_sql()
     except:
         db.rollback_transaction()
         if not db.has_ddl_transactions:
             print self.run_migration_error(migration)
         raise
     else:
         db.commit_transaction()
开发者ID:notanumber,项目名称:south,代码行数:13,代码来源:migrators.py


示例17: forwards

    def forwards(self, orm):
        # As opposed to Document1, we can't just delete Document2 documents if
        # there is a duplication because it actually holds data. So instead
        # we'll just find duplications and emit a better error message.
        # Note we reset the `order_by` to make sure to prevent error with mysql:
        # ORDER BY clause is not in GROUP BY clause and contains nonaggregated column.
        duplicated_records = Document2.objects \
         .values('uuid', 'version', 'is_history') \
         .annotate(id_count=models.Count('id')) \
         .filter(id_count__gt=1) \
         .order_by()


        duplicated_records = list(duplicated_records)
        duplicated_ids = []
        duplicated_ids_to_delete = []

        for record in duplicated_records:
             docs = Document2.objects \
                 .values_list('id', flat=True) \
                 .filter(
                     uuid=record['uuid'],
                     version=record['version'],
                     is_history=record['is_history'],
                 ) \
                 .order_by('-last_modified')

             duplicated_ids.extend(docs)
             duplicated_ids_to_delete.extend(docs[1:]) # Keep the most recent duplicate

        if duplicated_ids:
             msg = 'Found duplicated Document2 records! %(duplicated_ids)s.\n' \
                   'This will require manual merging or deletion of the Document2 records with duplicate ids and rerunning the migration.\n' \
                   'For more information on manipulating Hue built in objects, have a look at our blog: http://gethue.com/hue-api-execute-some-builtin-commands/\n' \
                   'For example, to delete Document2 records with the oldest duplicated ids execute the following:\n\n' \
                   'from desktop.models import Document2\n' \
                   'Document2.objects.filter(id__in=%(duplicated_ids_to_delete)s).delete()\n' % {
                       'duplicated_ids': duplicated_ids,
                       'duplicated_ids_to_delete': duplicated_ids_to_delete
                   }
             logging.error(msg)
             raise RuntimeError(msg)

        try:
            db.start_transaction()
            # Adding unique constraint on 'Document2', fields ['uuid', 'version', 'is_history']
            db.create_unique(u'desktop_document2', ['uuid', 'version', 'is_history'])
            db.commit_transaction()
        except Exception, e:
            db.rollback_transaction()
            raise e
开发者ID:cloudera,项目名称:hue,代码行数:51,代码来源:0016_auto__add_unique_document2_uuid_version_is_history.py


示例18: test_add_unique_fk

    def test_add_unique_fk(self):
        """
        Test adding a ForeignKey with unique=True or a OneToOneField
        """
        db.create_table("test_add_unique_fk", [("spam", models.BooleanField(default=False))])
        db.start_transaction()

        db.add_column(
            "test_add_unique_fk", "mock1", models.ForeignKey(db.mock_model("Mock", "mock"), null=True, unique=True)
        )
        db.add_column("test_add_unique_fk", "mock2", models.OneToOneField(db.mock_model("Mock", "mock"), null=True))

        db.rollback_transaction()
        db.delete_table("test_add_unique_fk")
开发者ID:qiwihui,项目名称:johan-doc,代码行数:14,代码来源:db.py


示例19: safe_add_column

def safe_add_column(table, column, column_data, keep_default = False):
    """when user calls syncdb with askbot the first time
    the auth_user table will be created together with the patched columns
    so, we need to add these columns here in separate transactions
    and roll back if they fail, if we want we could also record - which columns clash
    """
    try:
        db.start_transaction()
        db.add_column(table, column, column_data, keep_default = keep_default)
        db.commit_transaction()
        return True
    except:
        db.rollback_transaction()
        return False
开发者ID:OpenMOOC,项目名称:askbot-devel,代码行数:14,代码来源:__init__.py


示例20: backwards

    def backwards(self, orm):
        "Write your backwards methods here."
        try:
            db.start_transaction()
            entities = orm.Profile.objects.values('entity').all()
            print entities
            found = True
            db.commit_transaction()
        except:
            db.rollback_transaction()
            found = False

        if found:
            db.delete_column('profiles_profile', 'entity_id')
开发者ID:BillTheBest,项目名称:tendenci,代码行数:14,代码来源:0003_if_add_entity.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python db.send_create_signal函数代码示例发布时间:2022-05-27
下一篇:
Python db.rename_table函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap