desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the database column data type for this field, for the provided connection.'
def db_type(self, connection):
data = DictWrapper(self.__dict__, connection.ops.quote_name, 'qn_') try: return (connection.creation.data_types[self.get_internal_type()] % data) except KeyError: return None
'Returns field\'s value just before saving.'
def pre_save(self, model_instance, add):
return getattr(model_instance, self.attname)
'Perform preliminary non-db specific value checks and conversions.'
def get_prep_value(self, value):
return value
'Returns field\'s value prepared for interacting with the database backend. Used by the default implementations of ``get_db_prep_save``and `get_db_prep_lookup```'
def get_db_prep_value(self, value, connection, prepared=False):
if (not prepared): value = self.get_prep_value(value) return value
'Returns field\'s value prepared for saving into a database.'
def get_db_prep_save(self, value, connection):
return self.get_db_prep_value(value, connection=connection, prepared=False)
'Perform preliminary non-db specific lookup checks and conversions'
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, 'prepare'): return value.prepare() if hasattr(value, '_prepare'): return value._prepare() if (lookup_type in ('regex', 'iregex', 'month', 'day', 'week_day', 'search', 'contains', 'icontains', 'iexact', 'startswith', 'istartswith', 'endswith', 'iendswith', 'isnull')): ...
'Returns field\'s value prepared for database lookup.'
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
if (not prepared): value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if (hasattr(value, 'as_sql') or hasattr(value, '_as_sql')): if hasattr(value, 'relabel_aliases'): return value ...
'Returns a boolean of whether this field has a default value.'
def has_default(self):
return (self.default is not NOT_PROVIDED)
'Returns the default value for this field.'
def get_default(self):
if self.has_default(): if callable(self.default): return self.default() return force_unicode(self.default, strings_only=True) if ((not self.empty_strings_allowed) or (self.null and (not connection.features.interprets_empty_strings_as_nulls))): return None return ''
'Returns choices with a default blank choices included, for use as SelectField choices for this field.'
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = ((include_blank and blank_choice) or []) if self.choices: return (first_choice + list(self.choices)) rel_model = self.rel.to if hasattr(self.rel, 'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_m...
'Returns flattened choices with a default blank choice included.'
def get_flatchoices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = ((include_blank and blank_choice) or []) return (first_choice + list(self.flatchoices))
'Returns a string value of this field from the passed obj. This is used by the serialization framework.'
def value_to_string(self, obj):
return smart_unicode(self._get_val_from_obj(obj))
'Flattened version of choices tuple.'
def _get_flatchoices(self):
flat = [] for (choice, value) in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat
'Returns a django.forms.Field instance for this database Field.'
def formfield(self, form_class=forms.CharField, **kwargs):
defaults = {'required': (not self.blank), 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] =...
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname)
'Formats a number into a string with the requisite number of digits and decimal places.'
def format_number(self, value):
from django.db.backends import util return util.format_number(value, self.max_digits, self.decimal_places)
'Returns a queryset based on the related model\'s base manager (rather than the default manager, as returned by __get__). Used by Model.delete().'
def delete_manager(self, instance):
return self.create_manager(instance, self.related.model._base_manager.__class__)
'Creates the managers used by other methods (__get__() and delete()).'
def create_manager(self, instance, superclass):
rel_field = self.related.field rel_model = self.related.model class RelatedManager(superclass, ): def get_query_set(self): db = (self._db or router.db_for_read(rel_model, instance=instance)) return superclass.get_query_set(self).using(db).filter(**self.core_filters) d...
'Should the related object be hidden?'
def is_hidden(self):
return (self.related_name and (self.related_name[(-1)] == '+'))
'Returns the Field in the \'to\' object to which this relationship is tied.'
def get_related_field(self):
data = self.to._meta.get_field_by_name(self.field_name) if (not data[2]): raise FieldDoesNotExist(("No related field named '%s'" % self.field_name)) return data[0]
'Should the related object be hidden?'
def is_hidden(self):
return (self.related_name and (self.related_name[(-1)] == '+'))
'Returns the field in the to\' object to which this relationship is tied (this is always the primary key on the target model). Provided for symmetry with ManyToOneRel.'
def get_related_field(self):
return self.to._meta.pk
'Here we check if the default value is an object and return the to_field if so.'
def get_default(self):
field_default = super(ForeignKey, self).get_default() if isinstance(field_default, self.rel.to): return getattr(field_default, self.rel.get_related_field().attname) return field_default
'Function that can be curried to provide the m2m table name for this relation'
def _get_m2m_db_table(self, opts):
if (self.rel.through is not None): return self.rel.through._meta.db_table elif self.db_table: return self.db_table else: return util.truncate_name(('%s_%s' % (opts.db_table, self.name)), connection.ops.max_name_length())
'Function that can be curried to provide the source accessor or DB column name for the m2m table'
def _get_m2m_attr(self, related, attr):
cache_attr = ('_m2m_%s_cache' % attr) if hasattr(self, cache_attr): return getattr(self, cache_attr) for f in self.rel.through._meta.fields: if (hasattr(f, 'rel') and f.rel and (f.rel.to == related.model)): setattr(self, cache_attr, getattr(f, attr)) return getattr(se...
'Function that can be curried to provide the related accessor or DB column name for the m2m table'
def _get_m2m_reverse_attr(self, related, attr):
cache_attr = ('_m2m_reverse_%s_cache' % attr) if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False for f in self.rel.through._meta.fields: if (hasattr(f, 'rel') and f.rel and (f.rel.to == related.parent_model)): if (related.model == related.parent_mode...
'Validates that the value is a valid list of foreign keys'
def isValidIDList(self, field_data, all_data):
mod = self.rel.to try: pks = map(int, field_data.split(',')) except ValueError: return objects = mod._default_manager.in_bulk(pks) if (len(objects) != len(pks)): badkeys = [k for k in pks if (k not in objects)] raise exceptions.ValidationError((ungettext('Please en...
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname).all()
'Oracle requires special cases for %% and & operators in query expressions'
def combine_expression(self, connector, sub_expressions):
if (connector == '%%'): return ('MOD(%s)' % ','.join(sub_expressions)) elif (connector == '&'): return ('BITAND(%s)' % ','.join(sub_expressions)) elif (connector == '|'): raise NotImplementedError('Bit-wise or is not supported in Oracle.') return super(DatabaseO...
'Destroy a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created.'
def _destroy_test_db(self, test_database_name, verbosity=1):
TEST_NAME = self._test_database_name() TEST_USER = self._test_database_user() TEST_PASSWD = self._test_database_passwd() TEST_TBLSPACE = self._test_database_tblspace() TEST_TBLSPACE_TMP = self._test_database_tblspace_tmp() self.connection.settings_dict['USER'] = self.remember['user'] self.co...
'Returns a list of table names in the current database.'
def get_table_list(self, cursor):
cursor.execute('SELECT TABLE_NAME FROM USER_TABLES') return [row[0].lower() 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 WHERE ROWNUM < 2' % self.connection.ops.quote_name(table_name))) description = [] for desc in cursor.description: description.append(((desc[0].lower(),) + desc[1:])) return description
'Table name comparison is case insensitive under Oracle'
def table_name_converter(self, name):
return name.lower()
'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):
cursor.execute('\n SELECT ta.column_id - 1, tb.table_name, tb.column_id - 1\n FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,\n user_tab_cols ta, user_tab_cols tb\n ...
'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):
sql = "SELECT LOWER(all_tab_cols.column_name) AS column_name,\n CASE user_constraints.constraint_type\n WHEN 'P' THEN 1 ELSE 0\n END AS is_primary_key,\n CASE ...
'Creates the SQL for this query. Returns the SQL string and list of parameters. This is overriden from the original Query class to handle the additional SQL Oracle requires to emulate LIMIT and OFFSET. If \'with_limits\' is False, any limit/offset information is not included in the query.'
def as_sql(self, with_limits=True, with_col_aliases=False):
do_offset = (with_limits and ((self.query.high_mark is not None) or self.query.low_mark)) if (not do_offset): (sql, params) = super(SQLCompiler, self).as_sql(with_limits=False, with_col_aliases=with_col_aliases) else: (sql, params) = super(SQLCompiler, self).as_sql(with_limits=False, with_co...
'Switch the isolation level when needing transaction support, so that the same transaction is visible across all the queries.'
def _enter_transaction_management(self, managed):
if (self.features.uses_autocommit and managed and (not self.isolation_level)): self._set_isolation_level(1)
'If the normal operating mode is "autocommit", switch back to that when leaving transaction management.'
def _leave_transaction_management(self, managed):
if (self.features.uses_autocommit and (not managed) and self.isolation_level): self._set_isolation_level(0)
'Do all the related feature configurations for changing isolation levels. This doesn\'t touch the uses_autocommit feature, since that controls the movement *between* isolation levels.'
def _set_isolation_level(self, level):
assert (level in (0, 1)) try: if (self.connection is not None): self.connection.set_isolation_level(level) finally: self.isolation_level = level self.features.uses_savepoints = bool(level)
'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):
cursor.execute("\n SELECT con.conkey, con.confkey, c2.relname\n FROM pg_constraint con, pg_class c1, pg_class c2\n WHERE c1.oid = con.conre...
'A hook for backend-specific changes required when entering manual transaction handling.'
def _enter_transaction_management(self, managed):
pass
'A hook for backend-specific changes required when leaving manual transaction handling. Will usually be implemented only when _enter_transaction_management() is also required.'
def _leave_transaction_management(self, managed):
pass
'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
'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()
'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 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 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 (compiler_name not in self._cache): self._cache[compiler_name] = getattr(import_module(self.compiler_module), compiler_name) return 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 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 appended to tables or rows to define a tablespace. Returns \'\' if the backend doesn\'t use tablespaces.'
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 datetime_safe.new_date(value).strftime('%Y-%m-%d')
'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 datetime 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 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 NotImplemented.'
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)
'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) return set([m for m in all_models if (self.table_name_converter(m._me...
'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...
'By default, there is no backend-specific validation'
def validate_field(self, errors, opts, f):
pass
'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...
'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 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 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...
'"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']
'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...