desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model).'
def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1, used=None, requested=None, restricted=None, nullable=None, dupe_set=None, avoid_set=None):
if ((not restricted) and self.query.max_depth and (cur_depth > self.query.max_depth)): return if (not opts): opts = self.query.get_meta() root_alias = self.query.get_initial_alias() self.query.related_select_cols = [] self.query.related_select_fields = [] if (not used...
'Converts the self.deferred_loading data structure to mapping of table names to sets of column names which are to be loaded. Returns the dictionary.'
def deferred_to_columns(self):
columns = {} self.query.deferred_to_data(columns, self.query.deferred_to_columns_cb) return columns
'Returns an iterator over the results from executing this query.'
def results_iter(self):
resolve_columns = hasattr(self, 'resolve_columns') fields = None has_aggregate_select = bool(self.query.aggregate_select) for rows in self.execute_sql(MULTI): for row in rows: if resolve_columns: if (fields is None): if self.query.select_fields: ...
'Run the query against the database and returns the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case...
def execute_sql(self, result_type=MULTI):
try: (sql, params) = self.as_sql() if (not sql): raise EmptyResultSet except EmptyResultSet: if (result_type == MULTI): return empty_iter() else: return cursor = self.connection.cursor() cursor.execute(sql, params) if (not result_ty...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self):
assert (len(self.query.tables) == 1), 'Can only delete from one table at a time.' qn = self.quote_name_unless_alias result = [('DELETE FROM %s' % qn(self.query.tables[0]))] (where, params) = self.query.where.as_sql(qn=qn, connection=self.connection) result.append(('WHER...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self):
from django.db.models.base import Model self.pre_sql_setup() if (not self.query.values): return ('', ()) table = self.query.tables[0] qn = self.quote_name_unless_alias result = [('UPDATE %s' % qn(table))] result.append('SET') (values, update_params) = ([], []) for (field, ...
'Execute the specified update. Returns the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available.'
def execute_sql(self, result_type):
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) rows = ((cursor and cursor.rowcount) or 0) is_empty = (cursor is None) del cursor for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty: ...
'If the update depends on results from other tables, we need to do some munging of the "where" conditions to match the format required for (portable) SQL updates. That is done here. Further, if we are going to be running multiple updates, we pull out the id values to update at this point so that they don\'t change as a...
def pre_sql_setup(self):
self.query.select_related = False self.query.clear_ordering(True) super(SQLUpdateCompiler, self).pre_sql_setup() count = self.query.count_active_tables() if ((not self.query.related_updates) and (count == 1)): return query = self.query.clone(klass=Query) query.bump_prefix() query...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self, qn=None):
if (qn is None): qn = self.quote_name_unless_alias sql = ('SELECT %s FROM (%s) subquery' % (', '.join([aggregate.as_sql(qn, self.connection) for aggregate in self.query.aggregate_select.values()]), self.query.subquery)) params = self.query.sub_params return (sql, params)
'Returns an iterator over the results from executing this query.'
def results_iter(self):
resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp needs_string_cast = self.connection.features.needs_datetime_string_...
'Adds \'objs\' to the collection of objects to be deleted. If the call is the result of a cascade, \'source\' should be the model that caused it, and \'nullable\' should be set to True if the relation can be null. Returns a list of all objects that were not already collected.'
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
if (not objs): return [] new_objs = [] model = objs[0].__class__ instances = self.data.setdefault(model, set()) for obj in objs: if (obj not in instances): new_objs.append(obj) instances.update(new_objs) if ((source is not None) and (not nullable)): if rev...
'Schedules a batch delete. Every instance of \'model\' that is related to an instance of \'obj\' through \'field\' will be deleted.'
def add_batch(self, model, field, objs):
self.batches.setdefault(model, {}).setdefault(field, set()).update(objs)
'Schedules a field update. \'objs\' must be a homogenous iterable collection of model instances (e.g. a QuerySet).'
def add_field_update(self, field, value, objs):
if (not objs): return model = objs[0].__class__ self.field_updates.setdefault(model, {}).setdefault((field, value), set()).update(objs)
'Adds \'objs\' to the collection of objects to be deleted as well as all parent instances. \'objs\' must be a homogenous iterable collection of model instances (e.g. a QuerySet). If \'collect_related\' is True, related objects will be handled by their respective on_delete handler. If the call is the result of a casca...
def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False):
new_objs = self.add(objs, source, nullable, reverse_dependency=reverse_dependency) if (not new_objs): return model = new_objs[0].__class__ for (parent_model, ptr) in model._meta.parents.iteritems(): if ptr: parent_objs = [getattr(obj, ptr.name) for obj in new_objs] ...
'Gets a QuerySet of objects related to ``objs`` via the relation ``related``.'
def related_objects(self, related, objs):
return related.model._base_manager.using(self.using).filter(**{('%s__in' % related.field.name): objs})
'Returns field\'s value prepared for saving into a database.'
def get_prep_value(self, value):
if (value is None): return None return unicode(value)
'Returns field\'s value just before saving.'
def pre_save(self, model_instance, add):
file = super(FileField, self).pre_save(model_instance, add) if (file and (not file._committed)): file.save(file.name, file, save=False) return file
'Updates field\'s width and height fields, if defined. This method is hooked up to model\'s post_init signal to update dimensions after instantiating a model instance. However, dimensions won\'t be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object fro...
def update_dimension_fields(self, instance, force=False, *args, **kwargs):
has_dimension_fields = (self.width_field or self.height_field) if (not has_dimension_fields): return file = getattr(instance, self.attname) if ((not file) and (not force)): return dimension_fields_filled = (not ((self.width_field and (not getattr(instance, self.width_field))) or (sel...
'Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can\'t be converted. Returns the converted value. Subclasses should override this.'
def to_python(self, value):
return value
'Validates value and throws ValidationError. Subclasses should override this to provide validation logic.'
def validate(self, value, model_instance):
if (not self.editable): return if (self._choices and value): for (option_key, option_value) in self.choices: if isinstance(option_value, (list, tuple)): for (optgroup_key, optgroup_value) in option_value: if (value == optgroup_key): ...
'Convert the value\'s type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.'
def clean(self, value, model_instance):
value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value
'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...
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname).all()
'Implements the interval functionality for expressions format for Oracle: (datefield + INTERVAL \'3 00:03:20.000000\' DAY(1) TO SECOND(6))'
def date_interval_sql(self, sql, connector, timedelta):
(minutes, seconds) = divmod(timedelta.seconds, 60) (hours, minutes) = divmod(minutes, 60) days = str(timedelta.days) day_precision = len(days) fmt = "(%s %s INTERVAL '%s %02d:%02d:%02d.%06d' DAY(%d) TO SECOND(6))" return (fmt % (sql, connector, days, hours, minutes, seconds,...
'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...
'We need to return the \'production\' DB name to get the test DB creation machinery to work. This isn\'t a great deal in this case because DB names as handled by Django haven\'t real counterparts in Oracle.'
def _get_test_db_name(self):
return self.connection.settings_dict['NAME']
'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):
table_name = table_name.upper() 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 ...
'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):
if (with_limits and (self.query.low_mark == self.query.high_mark)): return ('', ()) 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_alias...
'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
'Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirty is always fals...
def enter_transaction_management(self, managed=True):
if self.transaction_state: self.transaction_state.append(self.transaction_state[(-1)]) else: self.transaction_state.append(settings.TRANSACTIONS_MANAGED) if (self._dirty is None): self._dirty = False self._enter_transaction_management(managed)
'Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.)'
def leave_transaction_management(self):
self._leave_transaction_management(self.is_managed()) if self.transaction_state: del self.transaction_state[(-1)] else: raise TransactionManagementError("This code isn't under transaction management") if self._dirty: self.rollback() raise TransactionManagem...
'Returns True if the current transaction requires a commit for changes to happen.'
def is_dirty(self):
return self._dirty
'Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.'
def set_dirty(self):
if (self._dirty is not None): self._dirty = True else: raise TransactionManagementError("This code isn't under transaction management")
'Resets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether a commit or rollback should happen.'
def set_clean(self):
if (self._dirty is not None): self._dirty = False else: raise TransactionManagementError("This code isn't under transaction management") self.clean_savepoints()
'Checks whether the transaction manager is in manual or in auto state.'
def is_managed(self):
if self.transaction_state: return self.transaction_state[(-1)] return settings.TRANSACTIONS_MANAGED
'Puts the transaction manager into a manual state: managed transactions have to be committed explicitly by the user. If you switch off transaction management and there is a pending commit/rollback, the data will be commited.'
def managed(self, flag=True):
top = self.transaction_state if top: top[(-1)] = flag if ((not flag) and self.is_dirty()): self._commit() self.set_clean() else: raise TransactionManagementError("This code isn't under transaction management")
'Commits changes if the system is not in managed transaction mode.'
def commit_unless_managed(self):
if (not self.is_managed()): self._commit() self.clean_savepoints() else: self.set_dirty()
'Rolls back changes if the system is not in managed transaction mode.'
def rollback_unless_managed(self):
if (not self.is_managed()): self._rollback() else: self.set_dirty()
'Does the commit itself and resets the dirty flag.'
def commit(self):
self._commit() self.set_clean()
'This function does the rollback itself and resets the dirty flag.'
def rollback(self):
self._rollback() self.set_clean()
'Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit.'
def savepoint(self):
thread_ident = thread.get_ident() self.savepoint_state += 1 tid = str(thread_ident).replace('-', '') sid = ('s%s_x%d' % (tid, self.savepoint_state)) self._savepoint(sid) return sid
'Rolls back the most recent savepoint (if one exists). Does nothing if savepoints are not supported.'
def savepoint_rollback(self, sid):
if self.savepoint_state: self._savepoint_rollback(sid)
'Commits the most recent savepoint (if one exists). Does nothing if savepoints are not supported.'
def savepoint_commit(self, sid):
if self.savepoint_state: self._savepoint_commit(sid)
'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
'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 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