desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Creates the SQL for this query. Returns the SQL string and list of
parameters.
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 ('', ())
self.pre_sql_setup()
self.refcounts_before = self.query.alias_refcount.copy()
out_cols = self.get_columns(with_col_aliases)
(ordering, ordering_group_by) = self.get_ordering()
distinct_fields = self.get_d... |
'Perform the same functionality as the as_sql() method, returning an
SQL string and parameters. However, the alias prefixes are bumped
beforehand (in a copy -- the current query isn\'t changed), and any
ordering is removed if the query is unsliced.
Used when nesting this query inside another.'
| def as_nested_sql(self):
| obj = self.query.clone()
if ((obj.low_mark == 0) and (obj.high_mark is None)):
obj.clear_ordering(True)
obj.bump_prefix()
return obj.get_compiler(connection=self.connection).as_sql()
|
'Returns the list of columns to use in the select statement. If no
columns have been specified, returns all columns relating to fields in
the model.
If \'with_aliases\' is true, any column names that are duplicated
(without the table names) are given unique aliases. This is needed in
some cases to avoid ambiguity with ... | def get_columns(self, with_aliases=False):
| qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
result = [('(%s) AS %s' % (col[0], qn2(alias))) for (alias, col) in self.query.extra_select.iteritems()]
aliases = set(self.query.extra_select.keys())
if with_aliases:
col_aliases = aliases.copy()
else:
... |
'Computes the default columns for selecting every field in the base
model. Will sometimes be called to pull in related models (e.g. via
select_related), in which case "opts" and "start_alias" will be given
to provide a starting point for the traversal.
Returns a list of strings, quoted appropriately for use in SQL
dire... | def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False):
| result = []
if (opts is None):
opts = self.query.model._meta
qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
aliases = set()
only_load = self.deferred_to_columns()
proxied_model = opts.concrete_model
if start_alias:
seen = {None: start_alias}
fo... |
'Returns a quoted list of fields to use in DISTINCT ON part of the query.
Note that this method can alter the tables in the query, and thus it
must be called before get_from_clause().'
| def get_distinct(self):
| qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
result = []
opts = self.query.model._meta
for name in self.query.distinct_fields:
parts = name.split(LOOKUP_SEP)
(field, col, alias, _, _) = self._setup_joins(parts, opts, None)
(col, alias) = self._final_... |
'Returns a tuple containing a list representing the SQL elements in the
"order by" clause, and the list of SQL elements that need to be added
to the GROUP BY clause as a result of the ordering.
Also sets the ordering_aliases attribute on this instance to a list of
extra aliases needed in the select.
Determining the ord... | def get_ordering(self):
| if self.query.extra_order_by:
ordering = self.query.extra_order_by
elif (not self.query.default_ordering):
ordering = self.query.order_by
else:
ordering = (self.query.order_by or self.query.model._meta.ordering or [])
qn = self.quote_name_unless_alias
qn2 = self.connection.op... |
'Returns the table alias (the name might be ambiguous, the alias will
not be) and column name for ordering by the given \'name\' parameter.
The \'name\' is of the form \'field1__field2__...__fieldN\'.'
| def find_ordering_name(self, name, opts, alias=None, default_order='ASC', already_seen=None):
| (name, order) = get_order_dir(name, default_order)
pieces = name.split(LOOKUP_SEP)
(field, col, alias, joins, opts) = self._setup_joins(pieces, opts, alias)
if (field.rel and (len(joins) > 1) and opts.ordering):
if (not already_seen):
already_seen = set()
join_tuple = tuple([... |
'A helper method for get_ordering and get_distinct. This method will
call query.setup_joins, handle refcounts and then promote the joins.
Note that get_ordering and get_distinct must produce same target
columns on same input, as the prefixes of get_ordering and get_distinct
must match. Executing SQL where this is not t... | def _setup_joins(self, pieces, opts, alias):
| if (not alias):
alias = self.query.get_initial_alias()
(field, target, opts, joins, _, _) = self.query.setup_joins(pieces, opts, alias, False)
alias = joins[(-1)]
col = target.column
if (not field.rel):
self.query.ref_alias(alias)
self.query.promote_alias_chain(joins, (self.query... |
'A helper method for get_distinct and get_ordering. This method will
trim extra not-needed joins from the tail of the join chain.
This is very similar to what is done in trim_joins, but we will
trim LEFT JOINS here. It would be a good idea to consolidate this
method and query.trim_joins().'
| def _final_join_removal(self, col, alias):
| if alias:
while 1:
join = self.query.alias_map[alias]
if (col != join[RHS_JOIN_COL]):
break
self.query.unref_alias(alias)
alias = join[LHS_ALIAS]
col = join[LHS_JOIN_COL]
return (col, alias)
|
'Returns a list of strings that are joined together to go after the
"FROM" part of the query, as well as a list any extra parameters that
need to be included. Sub-classes, can override this to create a
from-clause via a "select".
This should only be called after any SQL construction methods that
might change the tables... | def get_from_clause(self):
| result = []
qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
first = True
for alias in self.query.tables:
if (not self.query.alias_refcount[alias]):
continue
try:
(name, alias, join_type, lhs, lhs_col, col, nullable) = self.query.alias_ma... |
'Returns a tuple representing the SQL elements in the "group by" clause.'
| def get_grouping(self):
| qn = self.quote_name_unless_alias
(result, params) = ([], [])
if (self.query.group_by is not None):
if ((len(self.query.model._meta.fields) == len(self.query.select)) and self.connection.features.allows_group_by_pk):
self.query.group_by = [(self.query.model._meta.db_table, self.query.mod... |
'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)
if (self.query.select_for_update and transaction.is_managed(self.using)):
transaction.set_dirty(self.using)
for rows in self.execute_sql(MULTI):
for row in rows:
... |
'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):
| 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, model, val) in self.query.values:
if... |
'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)
|
'Displays the module, class and name of the field.'
| def __repr__(self):
| path = ('%s.%s' % (self.__class__.__module__, self.__class__.__name__))
name = getattr(self, 'name', None)
if (name is not None):
return ('<%s: %s>' % (path, name))
return ('<%s>' % path)
|
'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)
|
'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... |
'To check constraints, we set constraints to immediate. Then, when, we\'re done we must ensure they
are returned to deferred.'
| def check_constraints(self, table_names=None):
| self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
|
'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.connection.settings_dict['SA... |
'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... |
'To check constraints, we set constraints to immediate. Then, when, we\'re done we must ensure they
are returned to deferred.'
| def check_constraints(self, table_names=None):
| self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
|
'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(psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)
|
'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(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
|
'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 range(5))
try:
if (self.connection is not None):
self.connection.set_isolation_level(level)
finally:
self.isolation_level = level
self.features.uses_savepoints = bool(level)
|
'implements the interval functionality for expressions
format for Postgres:
(datefield + interval \'3 days 200 seconds 5 microseconds\')'
| def date_interval_sql(self, sql, connector, timedelta):
| modifiers = []
if timedelta.days:
modifiers.append((u'%s days' % timedelta.days))
if timedelta.seconds:
modifiers.append((u'%s seconds' % timedelta.seconds))
if timedelta.microseconds:
modifiers.append((u'%s microseconds' % timedelta.microseconds))
mods = u' '.joi... |
'Check that the backend fully supports the provided aggregate.
The implementation of population statistics (STDDEV_POP and VAR_POP)
under Postgres 8.2 - 8.2.4 is known to be faulty. Raise
NotImplementedError if this is the database in use.'
| def check_aggregate_support(self, aggregate):
| if (aggregate.sql_function in ('STDDEV_POP', 'VAR_POP')):
pg_version = self.connection.pg_version
if ((pg_version >= 80200) and (pg_version <= 80204)):
raise NotImplementedError(('PostgreSQL 8.2 to 8.2.4 is known to have a faulty implementation of %s. ... |
'Returns the maximum length of an identifier.
Note that the maximum length of an identifier is 63 by default, but can
be changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h .
This implementation simply returns 63, but can easily be overridden by a
custom database back... | def max_name_length(self):
| return 63
|
'Rollback and close the active transaction.'
| def _prepare_for_test_db_ddl(self):
| self.connection.connection.rollback()
self.connection.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute("\n SELECT c.relname\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n ... |
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| cursor.execute('\n SELECT column_name, is_nullable\n FROM information_schema.columns\n WHERE table_name = %s', [table_name])
null_map = dict(cursor.fetch... |
'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... |
'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('\n SELECT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary\n FROM pg_catalog.pg_class c, pg_catalog.pg_class c2,\n ... |
'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... |
'Validates that the connection isn\'t accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an exception if the validation fails.'
| def validate_thread_sharing(self):
| if ((not self.allow_thread_sharing) and (self._thread_ident != thread.get_ident())):
raise DatabaseError(("DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias '%s' was created in thread i... |
'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):
| self.validate_thread_sharing()
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):
| self.validate_thread_sharing()
if (not self.is_managed()):
self._rollback()
else:
self.set_dirty()
|
'Does the commit itself and resets the dirty flag.'
| def commit(self):
| self.validate_thread_sharing()
self._commit()
self.set_clean()
|
'This function does the rollback itself and resets the dirty flag.'
| def rollback(self):
| self.validate_thread_sharing()
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):
| self.validate_thread_sharing()
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):
| self.validate_thread_sharing()
if self.savepoint_state:
self._savepoint_commit(sid)
|
'Backends can implement as needed to temporarily disable foreign key constraint
checking.'
| def disable_constraint_checking(self):
| pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.