本文整理汇总了Python中south.db.db.execute_deferred_sql函数的典型用法代码示例。如果您正苦于以下问题:Python execute_deferred_sql函数的具体用法?Python execute_deferred_sql怎么用?Python execute_deferred_sql使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了execute_deferred_sql函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_table_for_dynamic_class
def create_table_for_dynamic_class(model_class):
fields = [(f.name, f) for f in model_class._meta.local_fields]
table_name = model_class._meta.db_table
db.create_table(table_name, fields)
# some fields (eg GeoDjango) require additional SQL to be executed
# Because of the poor Django/GeoDjango support for schemas, we have to manipulate the GeoDjango sql here so that the table is resolved to the correct schema, sigh
if len(table_name.split('.'))==2:
schema, table = parse_schema_and_table(table_name)
for i, sql in enumerate(db.deferred_sql):
# Replace the POSTGIS single argument with two arguments
# TODO this stupidly assumes that all deferred sql is POSTGIS
# Substitution for '"schema"."table"' to 'schema','table'. This is for AddGeometryColumn
db.deferred_sql[i] = re.sub("'{0}'".format(table_name), "'{0}','{1}'".format(schema, table), sql)
# Substitution for "schema"."table" to schema.table. This is for CREATE INDEX
db.deferred_sql[i] = re.sub("{0}".format(table_name), "{0}.{1}".format(schema, table), db.deferred_sql[i])
# Substitution for "schema"."tableHEX". Some indexes add random hex to the table name inside the double quotes. They may also truncate the table name, so just capture everything between "s
# Also truncate to 64 characters the schema name minus the length of the table name, favoring the end of the schema which is most unique
db.deferred_sql[i] = re.sub(r'"(".*)"\."(.*") ON', r'\1.\2 ON'.format(schema, table), db.deferred_sql[i])
if string.find(db.deferred_sql[i], 'CREATE INDEX') == 0:
subs = db.deferred_sql[i]
# Truncate the index name. This could be done more elegantly
db.deferred_sql[i] = subs[0:14] + subs[14:string.index(subs, '" ON')][-64:] + subs[string.index(subs, '" ON'):]
db.execute_deferred_sql()
示例2: 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()
示例3: add_necessary_db_columns
def add_necessary_db_columns(model_class):
""" Cria nova tabela ou colunas pertinentes, se necessário com base no model_class.
Sem colunas ou dados são renomeados ou removidos.
Esta opção está disponível no caso de uma exceção de banco de dados ocorre.
"""
db.start_transaction()
# Create table if missing
create_db_table(model_class)
# Add field columns if missing
table_name = model_class._meta.db_table
fields = _get_fields(model_class)
db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]
for field_name, field in fields:
if field.column not in db_column_names:
logger.debug("Adding field '%s' to table '%s'" % (field_name, table_name))
db.add_column(table_name, field_name, field)
# Algumas colunas necessitam de SQL adiada para ser executado. Este foi recolhido
# Durante a execução db.add_column ().
db.execute_deferred_sql()
db.commit_transaction()
示例4: add_necessary_db_columns
def add_necessary_db_columns(model_class):
'''
Takes a Django model class and creates relevant columns as necessary based
on the model_class. No columns or data are renamed or removed.
This is available in case a database exception occurs.
'''
db.start_transaction()
# Add field columns if missing
table_name = model_class._meta.db_table
fields = _get_fields(model_class)
db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]
for field_name, field in fields:
if field.column not in db_column_names:
try:
db.add_column(table_name, field_name, field)
except ValueError:
field.null=True
db.add_column(table_name, field_name, field)
# Some columns require deferred SQL to be run. This was collected
# when running db.add_column().
db.execute_deferred_sql()
db.commit_transaction()
示例5: test_alter_constraints
def test_alter_constraints(self):
"""
Tests that going from a PostiveIntegerField to an IntegerField drops
the constraint on the database.
"""
# Make the test table
db.create_table("test_alterc", [
('num', models.PositiveIntegerField()),
])
db.execute_deferred_sql()
# 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())
db.execute_deferred_sql()
# 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()
示例6: test_change_foreign_key_target
def test_change_foreign_key_target(self):
# Tables for FK to target
User = db.mock_model(model_name='User', db_table='auth_user', db_tablespace='', pk_field_name='id', pk_field_type=models.AutoField, pk_field_args=[], pk_field_kwargs={})
db.create_table("test_fk_changed_target", [
('eggs', models.IntegerField(primary_key=True)),
])
Egg = db.mock_model(model_name='Egg', db_table='test_fk_changed_target', db_tablespace='', pk_field_name='eggs', pk_field_type=models.AutoField, pk_field_args=[], pk_field_kwargs={})
# Table with a foreign key to the wrong table
db.create_table("test_fk_changing", [
('egg', models.ForeignKey(User, null=True)),
])
db.execute_deferred_sql()
# Change foreign key pointing
db.alter_column("test_fk_changing", "egg_id", models.ForeignKey(Egg, null=True))
db.execute_deferred_sql()
# Test that it is pointing at the right table now
try:
non_user_id = db.execute("SELECT MAX(id) FROM auth_user")[0][0] + 1
except (TypeError, IndexError):
# Got a "None" or no records, treat as 0
non_user_id = 17
db.execute("INSERT INTO test_fk_changed_target (eggs) VALUES (%s)", [non_user_id])
db.execute("INSERT INTO test_fk_changing (egg_id) VALUES (%s)", [non_user_id])
db.commit_transaction()
db.start_transaction() # The test framework expects tests to end in transaction
示例7: test_primary_key
def test_primary_key(self):
"""
Test the primary key operations
"""
# SQLite backend doesn't support this yet.
if db.backend_name == "sqlite3":
return
db.create_table(
"test_pk",
[
("id", models.IntegerField(primary_key=True)),
("new_pkey", models.IntegerField()),
("eggs", models.IntegerField(unique=True)),
],
)
db.execute_deferred_sql()
# Remove the default primary key, and make eggs it
db.drop_primary_key("test_pk")
db.create_primary_key("test_pk", "new_pkey")
# Try inserting a now-valid row pair
db.execute("INSERT INTO test_pk (id, new_pkey, eggs) VALUES (1, 2, 3)")
db.execute("INSERT INTO test_pk (id, new_pkey, eggs) VALUES (1, 3, 4)")
db.delete_table("test_pk")
示例8: 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()
示例9: add_necessary_db_columns
def add_necessary_db_columns(model_class):
""" Creates new table or relevant columns as necessary based on the model_class.
No columns or data are renamed or removed.
This is available in case a database exception occurs.
"""
db.start_transaction()
# Create table if missing
create_db_table(model_class)
# Add field columns if missing
table_name = model_class._meta.db_table
fields = _get_fields(model_class)
db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]
for field_name, field in fields:
if field.column not in db_column_names:
logger.debug("Adding field '%s' to table '%s'" % (field_name, table_name))
db.add_column(table_name, field_name, field)
# Some columns require deferred SQL to be run. This was collected
# when running db.add_column().
db.execute_deferred_sql()
db.commit_transaction()
示例10: finish_db_creation
def finish_db_creation(self):
""" Exceute deferred SQL after creating several models.
MUST BE CALLED after self.create_db_model()
"""
db.execute_deferred_sql()
示例11: _create_table_and_fields
def _create_table_and_fields(model_class):
""" creates a table and fields """
fields = [(f.name, f) for f in model_class._meta.local_fields]
table_name = model_class._meta.db_table
db.create_table(table_name, fields)
db.execute_deferred_sql()
示例12: create_db_structure
def create_db_structure(self, metadata_definition):
''' as seen in
http://dynamic-models.readthedocs.org/en/latest/topics/database-migration.html#topics-database-migration
'''
fields = [(f.name, f) for f in metadata_definition._meta.local_fields]
table_name = metadata_definition._meta.db_table
db.create_table(table_name, fields)
db.execute_deferred_sql()
db.send_create_signal(metadata_definition._meta.app_label, metadata_definition.__name__)
示例13: test_delete_fk_column
def test_delete_fk_column(self):
main_table = 'test_drop_foreign'
ref_table = 'test_df_ref'
self._create_foreign_tables(main_table, ref_table)
db.execute_deferred_sql()
constraints = db._find_foreign_constraints(main_table, 'foreign_id')
self.assertEquals(len(constraints), 1)
db.delete_column(main_table, 'foreign_id')
constraints = db._find_foreign_constraints(main_table, 'foreign_id')
self.assertEquals(len(constraints), 0)
db.delete_table(main_table)
db.delete_table(ref_table)
示例14: test_constraint_references
def test_constraint_references(self):
"""Tests that referred table is reported accurately"""
main_table = 'test_cns_ref'
reference_table = 'test_cr_foreign'
db.start_transaction()
self._create_foreign_tables(main_table, reference_table)
db.execute_deferred_sql()
constraint = db._find_foreign_constraints(main_table, 'foreign_id')[0]
references = db._lookup_constraint_references(main_table, constraint)
self.assertEquals((reference_table, 'id'), references)
db.delete_table(main_table)
db.delete_table(reference_table)
示例15: 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()