desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Backends can implement as needed to re-enable foreign key constraint checking.'
| def enable_constraint_checking(self):
| pass
|
'Backends can override this method if they can apply constraint checking (e.g. via "SET CONSTRAINTS
ALL IMMEDIATE"). Should raise an IntegrityError if any invalid foreign key references are encountered.'
| def check_constraints(self, table_names=None):
| pass
|
'Perform manual checks of any database features that might vary between installs'
| def confirm(self):
| self._confirmed = True
self.supports_transactions = self._supports_transactions()
self.supports_stddev = self._supports_stddev()
self.can_introspect_foreign_keys = self._can_introspect_foreign_keys()
|
'Confirm support for transactions'
| def _supports_transactions(self):
| cursor = self.connection.cursor()
cursor.execute('CREATE TABLE ROLLBACK_TEST (X INT)')
self.connection._commit()
cursor.execute('INSERT INTO ROLLBACK_TEST (X) VALUES (8)')
self.connection._rollback()
cursor.execute('SELECT COUNT(X) FROM ROLLBACK_TEST')
(co... |
'Confirm support for STDDEV and related stats functions'
| def _supports_stddev(self):
| class StdDevPop(object, ):
sql_function = 'STDDEV_POP'
try:
self.connection.ops.check_aggregate_support(StdDevPop())
except NotImplementedError:
self.supports_stddev = False
|
'Confirm support for introspected foreign keys'
| def _can_introspect_foreign_keys(self):
| return True
|
'Returns any SQL needed to support auto-incrementing primary keys, or
None if no SQL is necessary.
This SQL is executed when a table is created.'
| def autoinc_sql(self, table, column):
| return None
|
'Returns the maximum allowed batch size for the backend. The fields
are the fields going to be inserted in the batch, the objs contains
all the objects to be inserted.'
| def bulk_batch_size(self, fields, objs):
| return len(objs)
|
'Given a lookup_type of \'year\', \'month\' or \'day\', returns the SQL that
extracts a value from the given date field field_name.'
| def date_extract_sql(self, lookup_type, field_name):
| raise NotImplementedError()
|
'Implements the date interval functionality for expressions'
| def date_interval_sql(self, sql, connector, timedelta):
| raise NotImplementedError()
|
'Given a lookup_type of \'year\', \'month\' or \'day\', returns the SQL that
truncates the given date field field_name to a DATE object with only
the given specificity.'
| def date_trunc_sql(self, lookup_type, field_name):
| raise NotImplementedError()
|
'Returns the SQL necessary to cast a datetime value so that it will be
retrieved as a Python datetime object instead of a string.
This SQL should include a \'%s\' in place of the field\'s name.'
| def datetime_cast_sql(self):
| return '%s'
|
'Returns the SQL necessary to make a constraint "initially deferred"
during a CREATE TABLE statement.'
| def deferrable_sql(self):
| return ''
|
'Returns an SQL DISTINCT clause which removes duplicate rows from the
result set. If any fields are given, only the given fields are being
checked for duplicates.'
| def distinct_sql(self, fields):
| if fields:
raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')
else:
return 'DISTINCT'
|
'Returns the SQL command that drops a foreign key.'
| def drop_foreignkey_sql(self):
| return 'DROP CONSTRAINT'
|
'Returns any SQL necessary to drop the sequence for the given table.
Returns None if no SQL is necessary.'
| def drop_sequence_sql(self, table):
| return None
|
'Given a cursor object that has just performed an INSERT...RETURNING
statement into a table that has an auto-incrementing ID, returns the
newly created ID.'
| def fetch_returned_insert_id(self, cursor):
| return cursor.fetchone()[0]
|
'Given a column type (e.g. \'BLOB\', \'VARCHAR\'), returns the SQL necessary
to cast it before using it in a WHERE statement. Note that the
resulting string should contain a \'%s\' placeholder for the column being
searched against.'
| def field_cast_sql(self, db_type):
| return '%s'
|
'Returns a list used in the "ORDER BY" clause to force no ordering at
all. Returning an empty list means that nothing will be included in the
ordering.'
| def force_no_ordering(self):
| return []
|
'Returns the FOR UPDATE SQL clause to lock rows for an update operation.'
| def for_update_sql(self, nowait=False):
| if nowait:
return 'FOR UPDATE NOWAIT'
else:
return 'FOR UPDATE'
|
'Returns the SQL WHERE clause to use in order to perform a full-text
search of the given field_name. Note that the resulting string should
contain a \'%s\' placeholder for the value being searched against.'
| def fulltext_search_sql(self, field_name):
| raise NotImplementedError('Full-text search is not implemented for this database backend')
|
'Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
accordin... | def last_executed_query(self, cursor, sql, params):
| from django.utils.encoding import smart_unicode, force_unicode
to_unicode = (lambda s: force_unicode(s, strings_only=True, errors='replace'))
if isinstance(params, (list, tuple)):
u_params = tuple([to_unicode(val) for val in params])
else:
u_params = dict([(to_unicode(k), to_unicode(v)) ... |
'Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column.'
| def last_insert_id(self, cursor, table_name, pk_name):
| return cursor.lastrowid
|
'Returns the string to use in a query when performing lookups
("contains", "like", etc). The resulting string should contain a \'%s\'
placeholder for the column being searched against.'
| def lookup_cast(self, lookup_type):
| return '%s'
|
'Returns the maximum number of items that can be passed in a single \'IN\'
list condition, or None if the backend does not impose a limit.'
| def max_in_list_size(self):
| return None
|
'Returns the maximum length of table and column names, or None if there
is no limit.'
| def max_name_length(self):
| return None
|
'Returns the value to use for the LIMIT when we are wanting "LIMIT
infinity". Returns None if the limit clause can be omitted in this case.'
| def no_limit_value(self):
| raise NotImplementedError
|
'Returns the value to use during an INSERT statement to specify that
the field should use its default value.'
| def pk_default_value(self):
| return 'DEFAULT'
|
'Returns the value of a CLOB column, for backends that return a locator
object that requires additional processing.'
| def process_clob(self, value):
| return value
|
'For backends that support returning the last insert ID as part
of an insert query, this method returns the SQL and params to
append to the INSERT query. The returned fragment should
contain a format string to hold the appropriate column.'
| def return_insert_id(self):
| pass
|
'Returns the SQLCompiler class corresponding to the given name,
in the namespace corresponding to the `compiler_module` attribute
on this backend.'
| def compiler(self, compiler_name):
| if (self._cache is None):
self._cache = import_module(self.compiler_module)
return getattr(self._cache, compiler_name)
|
'Returns a quoted version of the given table, index or column name. Does
not quote the given name if it\'s already been quoted.'
| def quote_name(self, name):
| raise NotImplementedError()
|
'Returns a SQL expression that returns a random value.'
| def random_function_sql(self):
| return 'RANDOM()'
|
'Returns the string to use in a query when performing regular expression
lookups (using "regex" or "iregex"). The resulting string should
contain a \'%s\' placeholder for the column being searched against.
If the feature is not supported (or part of it is not supported), a
NotImplementedError exception can be raised.'
| def regex_lookup(self, lookup_type):
| raise NotImplementedError
|
'Returns the SQL for starting a new savepoint. Only required if the
"uses_savepoints" feature is True. The "sid" parameter is a string
for the savepoint id.'
| def savepoint_create_sql(self, sid):
| raise NotImplementedError
|
'Returns the SQL for committing the given savepoint.'
| def savepoint_commit_sql(self, sid):
| raise NotImplementedError
|
'Returns the SQL for rolling back the given savepoint.'
| def savepoint_rollback_sql(self, sid):
| raise NotImplementedError
|
'Returns the SQL that will set the connection\'s time zone.
Returns \'\' if the backend doesn\'t support time zones.'
| def set_time_zone_sql(self):
| return ''
|
'Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.'
| def sql_flush(self, style, tables, sequences):
| raise NotImplementedError()
|
'Returns a list of the SQL statements required to reset sequences for
the given models.
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.'
| def sequence_reset_sql(self, style, model_list):
| return []
|
'Returns the SQL statement required to start a transaction.'
| def start_transaction_sql(self):
| return 'BEGIN;'
|
'Returns the SQL that will be used in a query to define the tablespace.
Returns \'\' if the backend doesn\'t support tablespaces.
If inline is True, the SQL is appended to a row; otherwise it\'s appended
to the entire CREATE TABLE or CREATE INDEX statement.'
| def tablespace_sql(self, tablespace, inline=False):
| return ''
|
'Prepares a value for use in a LIKE query.'
| def prep_for_like_query(self, x):
| from django.utils.encoding import smart_unicode
return smart_unicode(x).replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
|
'Transform a date value to an object compatible with what is expected
by the backend driver for date columns.'
| def value_to_db_date(self, value):
| if (value is None):
return None
return unicode(value)
|
'Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.'
| def value_to_db_datetime(self, value):
| if (value is None):
return None
return unicode(value)
|
'Transform a time value to an object compatible with what is expected
by the backend driver for time columns.'
| def value_to_db_time(self, value):
| if (value is None):
return None
if is_aware(value):
raise ValueError('Django does not support timezone-aware times.')
return unicode(value)
|
'Transform a decimal.Decimal value to an object compatible with what is
expected by the backend driver for decimal (numeric) columns.'
| def value_to_db_decimal(self, value, max_digits, decimal_places):
| if (value is None):
return None
return util.format_number(value, max_digits, decimal_places)
|
'Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a field value using a year lookup
`value` is an int, containing the looked-up year.'
| def year_lookup_bounds(self, value):
| first = '%s-01-01 00:00:00'
second = '%s-12-31 23:59:59.999999'
return [(first % value), (second % value)]
|
'Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a DateField value using a year lookup
`value` is an int, containing the looked-up year.
By default, it just calls `self.year_lookup_bounds`. Some backends need
this hook because on their DB date fields can\'t be comp... | def year_lookup_bounds_for_date_field(self, value):
| return self.year_lookup_bounds(value)
|
'Coerce the value returned by the database backend into a consistent type that
is compatible with the field type.'
| def convert_values(self, value, field):
| internal_type = field.get_internal_type()
if (internal_type == 'DecimalField'):
return value
elif ((internal_type and internal_type.endswith('IntegerField')) or (internal_type == 'AutoField')):
return int(value)
elif (internal_type in ('DateField', 'DateTimeField', 'TimeField')):
... |
'Check that the backend supports the provided aggregate
This is used on specific backends to rule out known aggregates
that are known to have faulty implementations. If the named
aggregate function has a known problem, the backend should
raise NotImplementedError.'
| def check_aggregate_support(self, aggregate_func):
| pass
|
'Combine a list of subexpressions into a single expression, using
the provided connecting operator. This is required because operators
can vary between backends (e.g., Oracle with %% and &) and between
subexpression types (e.g., date expressions)'
| def combine_expression(self, connector, sub_expressions):
| conn = (' %s ' % connector)
return conn.join(sub_expressions)
|
'Allow modification of insert parameters. Needed for Oracle Spatial
backend due to #10888.'
| def modify_insert_params(self, placeholders, params):
| return params
|
'Hook for a database backend to use the cursor description to
match a Django field type to a database column.
For Oracle, the column data_type on its own is insufficient to
distinguish between a FloatField and IntegerField, for example.'
| def get_field_type(self, data_type, description):
| return self.data_types_reverse[data_type]
|
'Apply a conversion to the name for the purposes of comparison.
The default table name converter is for case sensitive comparison.'
| def table_name_converter(self, name):
| return name
|
'Returns a list of names of all tables that exist in the database.'
| def table_names(self):
| cursor = self.connection.cursor()
return self.get_table_list(cursor)
|
'Returns a list of all table names that have associated Django models and
are in INSTALLED_APPS.
If only_existing is True, the resulting list will only include the tables
that actually exist in the database.'
| def django_table_names(self, only_existing=False):
| from django.db import models, router
tables = set()
for app in models.get_apps():
for model in models.get_models(app):
if (not model._meta.managed):
continue
if (not router.allow_syncdb(self.connection.alias, model)):
continue
table... |
'Returns a set of all models represented by the provided list of table names.'
| def installed_models(self, tables):
| from django.db import models, router
all_models = []
for app in models.get_apps():
for model in models.get_models(app):
if router.allow_syncdb(self.connection.alias, model):
all_models.append(model)
tables = map(self.table_name_converter, tables)
return set([m for... |
'Returns a list of information about all DB sequences for all models in all apps.'
| def sequence_list(self):
| from django.db import models, router
apps = models.get_apps()
sequence_list = []
for app in apps:
for model in models.get_models(app):
if (not model._meta.managed):
continue
if (not router.allow_syncdb(self.connection.alias, model)):
contin... |
'Backends can override this to return a list of (column_name, referenced_table_name,
referenced_column_name) for all key columns in given table.'
| def get_key_columns(self, cursor, table_name):
| raise NotImplementedError
|
'Backends can override this to return the column name of the primary key for the given table.'
| def get_primary_key_column(self, cursor, table_name):
| raise NotImplementedError
|
'By default, there is no backend-specific validation'
| def validate_field(self, errors, opts, f):
| pass
|
'Confirm support for STDDEV and related stats functions
SQLite supports STDDEV as an extension package; so
connection.ops.check_aggregate_support() can\'t unilaterally
rule out support for STDDEV. We need to manually check
whether the call works.'
| def _supports_stddev(self):
| cursor = self.connection.cursor()
cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
try:
cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
has_support = True
except utils.DatabaseError:
has_support = False
cursor.execute('DROP TABLE STDDEV_TEST')... |
'SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
999 variables per query.'
| def bulk_batch_size(self, fields, objs):
| return ((999 // len(fields)) if (len(fields) > 0) else len(objs))
|
'SQLite returns floats when it should be returning decimals,
and gets dates and datetimes wrong.
For consistency with other backends, coerce when required.'
| def convert_values(self, value, field):
| internal_type = field.get_internal_type()
if (internal_type == 'DecimalField'):
return util.typecast_decimal(field.format_number(value))
elif ((internal_type and internal_type.endswith('IntegerField')) or (internal_type == 'AutoField')):
return int(value)
elif (internal_type == 'DateFiel... |
'Checks each table name in `table_names` for rows with invalid foreign key references. This method is
intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint checks were off.
Raises an Integrit... | def check_constraints(self, table_names=None):
| cursor = self.cursor()
if (table_names is None):
table_names = self.introspection.get_table_list(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if (not primary_key_column_name):
continue
... |
'SQLite3 doesn\'t support constraints'
| def sql_for_pending_references(self, model, style, pending_references):
| return []
|
'SQLite3 doesn\'t support constraints'
| def sql_remove_table_constraints(self, model, references_to_delete, style):
| return []
|
'Returns a tuple that uniquely identifies a test database.
This takes into account the special cases of ":memory:" and "" for
SQLite since the databases will be distinct despite having the same
TEST_NAME. See http://www.sqlite.org/inmemorydb.html'
| def test_db_signature(self):
| settings_dict = self.connection.settings_dict
test_dbname = self._get_test_db_name()
sig = [self.connection.settings_dict['NAME']]
if (test_dbname == ':memory:'):
sig.append(self.connection.alias)
return tuple(sig)
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute("\n SELECT name FROM sqlite_master\n WHERE type='table' AND NOT name='sqlite_sequence'\n ORDER BY name")
return [row[0] for row i... |
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| return [(info['name'], info['type'], None, None, None, None, info['null_ok']) for info in self._table_info(cursor, table_name)]
|
'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'
| def get_relations(self, cursor, table_name):
| relations = {}
cursor.execute('SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s', [table_name, 'table'])
results = cursor.fetchone()[0].strip()
results = results[(results.index('(') + 1):results.rindex(')')]
for (field_index, field_desc) in enumerate(r... |
'Returns a list of (column_name, referenced_table_name, referenced_column_name) for all
key columns in given table.'
| def get_key_columns(self, cursor, table_name):
| key_columns = []
cursor.execute('SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s', [table_name, 'table'])
results = cursor.fetchone()[0].strip()
results = results[(results.index('(') + 1):results.rindex(')')]
for (field_index, field_desc) in enumerate... |
'Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{\'primary_key\': boolean representing whether it\'s the primary key,
\'unique\': boolean representing whether it\'s a unique index}'
| def get_indexes(self, cursor, table_name):
| indexes = {}
for info in self._table_info(cursor, table_name):
indexes[info['name']] = {'primary_key': (info['pk'] != 0), 'unique': False}
cursor.execute(('PRAGMA index_list(%s)' % self.connection.ops.quote_name(table_name)))
for (index, unique) in [(field[1], field[2]) for field in cursor.fe... |
'Get the column name of the primary key for the given table.'
| def get_primary_key_column(self, cursor, table_name):
| cursor.execute('SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s', [table_name, 'table'])
results = cursor.fetchone()[0].strip()
results = results[(results.index('(') + 1):results.rindex(')')]
for field_desc in results.split(','):
field_desc = fiel... |
'Internal method used in Django tests. Don\'t rely on this from your code'
| def _mysql_storage_engine(self):
| if (self._storage_engine is None):
cursor = self.connection.cursor()
cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)')
cursor.execute("SHOW TABLE STATUS WHERE Name='INTROSPECT_TEST'")
result = cursor.fetchone()
cursor.execute('DROP TABLE INT... |
'Confirm support for introspected foreign keys'
| def _can_introspect_foreign_keys(self):
| return (self._mysql_storage_engine() != 'MyISAM')
|
'"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don\'t want any
implicit sorting going on.'
| def force_no_ordering(self):
| return ['NULL']
|
'Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
to indicate constraint checks need to be re-enabled.'
| def disable_constraint_checking(self):
| self.cursor().execute('SET foreign_key_checks=0')
return True
|
'Re-enable foreign key checks after they have been disabled.'
| def enable_constraint_checking(self):
| self.cursor().execute('SET foreign_key_checks=1')
|
'Checks each table name in `table_names` for rows with invalid foreign key references. This method is
intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint checks were off.
Raises an Integrit... | def check_constraints(self, table_names=None):
| cursor = self.cursor()
if (table_names is None):
table_names = self.introspection.get_table_list(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if (not primary_key_column_name):
continue
... |
'There are some field length restrictions for MySQL:
- Prior to version 5.0.3, character fields could not exceed 255
characters in length.
- No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.'
| def validate_field(self, errors, opts, f):
| from django.db import models
db_version = self.connection.get_server_version()
varchar_fields = (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)
if (isinstance(f, varchar_fields) and (f.max_length > 255)):
if (db_version < (5, 0, 3)):
msg = '"%(name)s": %(cl... |
'All inline references are pending under MySQL'
| def sql_for_inline_foreign_key_references(self, field, known_models, style):
| return ([], True)
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute('SHOW TABLES')
return [row[0] for row in cursor.fetchall()]
|
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| cursor.execute(('SELECT * FROM %s LIMIT 1' % self.connection.ops.quote_name(table_name)))
return cursor.description
|
'Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.'
| def _name_to_index(self, cursor, table_name):
| return dict([(d[0], i) for (i, d) in enumerate(self.get_table_description(cursor, table_name))])
|
'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'
| def get_relations(self, cursor, table_name):
| my_field_dict = self._name_to_index(cursor, table_name)
constraints = self.get_key_columns(cursor, table_name)
relations = {}
for (my_fieldname, other_table, other_field) in constraints:
other_field_index = self._name_to_index(cursor, other_table)[other_field]
my_field_index = my_field_d... |
'Returns a list of (column_name, referenced_table_name, referenced_column_name) for all
key columns in given table.'
| def get_key_columns(self, cursor, table_name):
| key_columns = []
try:
cursor.execute('\n SELECT column_name, referenced_table_name, referenced_column_name\n FROM information_schema.key_column_usage\n ... |
'Returns the name of the primary key column for the given table'
| def get_primary_key_column(self, cursor, table_name):
| for column in self.get_indexes(cursor, table_name).iteritems():
if column[1]['primary_key']:
return column[0]
return None
|
'Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{\'primary_key\': boolean representing whether it\'s the primary key,
\'unique\': boolean representing whether it\'s a unique index}'
| def get_indexes(self, cursor, table_name):
| cursor.execute(('SHOW INDEX FROM %s' % self.connection.ops.quote_name(table_name)))
indexes = {}
for row in cursor.fetchall():
indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': (not bool(row[1]))}
return indexes
|
'Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.'
| def _digest(self, *args):
| return ('%x' % (abs(hash(args)) % 4294967296L))
|
'Returns the SQL required to create a single model, as a tuple of:
(list_of_sql, pending_references_dict)'
| def sql_create_model(self, model, style, known_models=set()):
| opts = model._meta
if ((not opts.managed) or opts.proxy):
return ([], {})
final_output = []
table_output = []
pending_references = {}
qn = self.connection.ops.quote_name
for f in opts.local_fields:
col_type = f.db_type(connection=self.connection)
tablespace = (f.db_ta... |
'Return the SQL snippet defining the foreign key reference for a field.'
| def sql_for_inline_foreign_key_references(self, field, known_models, style):
| qn = self.connection.ops.quote_name
if (field.rel.to in known_models):
output = [((((((style.SQL_KEYWORD('REFERENCES') + ' ') + style.SQL_TABLE(qn(field.rel.to._meta.db_table))) + ' (') + style.SQL_FIELD(qn(field.rel.to._meta.get_field(field.rel.field_name).column))) + ')') + self.connection.ops.d... |
'Returns any ALTER TABLE statements to add constraints after the fact.'
| def sql_for_pending_references(self, model, style, pending_references):
| from django.db.backends.util import truncate_name
if ((not model._meta.managed) or model._meta.proxy):
return []
qn = self.connection.ops.quote_name
final_output = []
opts = model._meta
if (model in pending_references):
for (rel_class, f) in pending_references[model]:
... |
'Returns the CREATE INDEX SQL statements for a single model.'
| def sql_indexes_for_model(self, model, style):
| if ((not model._meta.managed) or model._meta.proxy):
return []
output = []
for f in model._meta.local_fields:
output.extend(self.sql_indexes_for_field(model, f, style))
return output
|
'Return the CREATE INDEX SQL statements for a single model field.'
| def sql_indexes_for_field(self, model, f, style):
| from django.db.backends.util import truncate_name
if (f.db_index and (not f.unique)):
qn = self.connection.ops.quote_name
tablespace = (f.db_tablespace or model._meta.db_tablespace)
if tablespace:
tablespace_sql = self.connection.ops.tablespace_sql(tablespace)
if ... |
'Return the DROP TABLE and restraint dropping statements for a single
model.'
| def sql_destroy_model(self, model, references_to_delete, style):
| if ((not model._meta.managed) or model._meta.proxy):
return []
qn = self.connection.ops.quote_name
output = [('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'), style.SQL_TABLE(qn(model._meta.db_table))))]
if (model in references_to_delete):
output.extend(self.sql_remove_table_constraint... |
'Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.'
| def create_test_db(self, verbosity=1, autoclobber=False):
| from django.core.management import call_command
test_database_name = self._get_test_db_name()
if (verbosity >= 1):
test_db_repr = ''
if (verbosity >= 2):
test_db_repr = (" ('%s')" % test_database_name)
print ("Creating test database for alias '%s'%s..." ... |
'Internal implementation - returns the name of the test DB that will be
created. Only useful when called from create_test_db() and
_create_test_db() and when no external munging is done with the \'NAME\'
or \'TEST_NAME\' settings.'
| def _get_test_db_name(self):
| if self.connection.settings_dict['TEST_NAME']:
return self.connection.settings_dict['TEST_NAME']
return (TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'])
|
'Internal implementation - creates the test db tables.'
| def _create_test_db(self, verbosity, autoclobber):
| suffix = self.sql_table_creation_suffix()
test_database_name = self._get_test_db_name()
qn = self.connection.ops.quote_name
cursor = self.connection.cursor()
self._prepare_for_test_db_ddl()
try:
cursor.execute(('CREATE DATABASE %s %s' % (qn(test_database_name), suffix)))
exc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.