desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'test that a scalar select as a column is returned as such and that type conversion works OK. (this is half a SQLAlchemy Core test and half to catch database backends that may have unusual behavior with scalar selects.)'
def test_row_w_scalar_select(self):
datetable = self.tables.has_dates s = select([datetable.alias('x').c.today]).as_scalar() s2 = select([datetable.c.id, s.label('somelabel')]) row = config.db.execute(s2).first() eq_(row['somelabel'], datetime.datetime(2006, 5, 12, 12, 0, 0))
'Insert rows as represented by the fixtures() method.'
@classmethod def _load_fixtures(cls):
(headers, rows) = ({}, {}) for (table, data) in cls.fixtures().items(): if (len(data) < 2): continue if isinstance(table, util.string_types): table = cls.tables[table] headers[table] = data[0] rows[table] = data[1:] for table in cls.metadata.sorted_tab...
'Run a setup method, framing the operation with a Base class that will catch new subclasses to be established within the "classes" registry.'
@classmethod def _with_register_classes(cls, fn):
cls_registry = cls.classes class FindFixture(type, ): def __init__(cls, classname, bases, dict_): cls_registry[classname] = cls return type.__init__(cls, classname, bases, dict_) class _Base(util.with_metaclass(FindFixture, object), ): pass class Basic(BasicEntity...
'Return True if this rule has been consumed, False if not. Should raise an AssertionError if this rule\'s condition has definitely failed.'
def is_consumed(self):
raise NotImplementedError()
'Return True if the last test of this rule passed, False if failed, None if no test was applied.'
def rule_passed(self):
raise NotImplementedError()
'Return True if this rule has been consumed. Should raise an AssertionError if this rule\'s condition has not been consumed or has failed.'
def consume_final(self):
if (self._result is None): assert False, 'Rule has not been consumed' return self.is_consumed()
'\'Deep, sparse compare. Deeply compare two entities, following the non-None attributes of the non-persisted object, if possible.'
def __eq__(self, other):
if (other is self): return True elif (not (self.__class__ == other.__class__)): return False if (id(self) in _recursion_stack): return True _recursion_stack.add(id(self)) try: try: self_key = sa.orm.attributes.instance_state(self).key except sa.orm...
'return true if the given state is marked as deleted within this uowtransaction.'
def is_deleted(self, state):
return ((state in self.states) and self.states[state][0])
'remove pending actions for a state from the uowtransaction.'
def remove_state_actions(self, state):
isdelete = self.states[state][0] self.states[state] = (isdelete, True)
'facade to attributes.get_state_history(), including caching of results.'
def get_attribute_history(self, state, key, passive=attributes.PASSIVE_NO_INITIALIZE):
hashkey = ('history', state, key) if (hashkey in self.attributes): (history, state_history, cached_passive) = self.attributes[hashkey] if ((not (cached_passive & attributes.SQL_OK)) and (passive & attributes.SQL_OK)): impl = state.manager[key].impl history = impl.get_hist...
'return a dynamic mapping of (Mapper, DependencyProcessor) to True or False, indicating if the DependencyProcessor operates on objects of that Mapper. The result is stored in the dictionary persistently once calculated.'
@util.memoized_property def _mapper_for_dep(self):
return util.PopulateDict((lambda tup: (tup[0]._props.get(tup[1].key) is tup[1].prop)))
'Filter the given list of InstanceStates to those relevant to the given DependencyProcessor.'
def filter_states_for_dep(self, dep, states):
mapper_for_dep = self._mapper_for_dep return [s for s in states if mapper_for_dep[(s.manager.mapper, dep)]]
'Generate the full, unsorted collection of PostSortRecs as well as dependency pairs for this UOWTransaction.'
def _generate_actions(self):
while True: ret = False for action in list(self.presort_actions.values()): if action.execute(self): ret = True if (not ret): break self.cycles = cycles = topological.find_cycles(self.dependencies, list(self.postsort_actions.values())) if cycles...
'mark processed objects as clean / deleted after a successful flush(). this method is called within the flush() method after the execute() method has succeeded and the transaction has been committed.'
def finalize_flush_changes(self):
states = set(self.states) isdel = set((s for (s, (isdelete, listonly)) in self.states.items() if isdelete)) other = states.difference(isdel) self.session._remove_newly_deleted(isdel) self.session._register_newly_persistent(other)
'Receive a class when the mapper is first constructed, and has applied instrumentation to the mapped class. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s behavior isn\'t modified by this method.'
def instrument_class(self, mapper, class_):
return EXT_CONTINUE
'Receive an instance when it\'s constructor is called. This method is only called during a userland construction of an object. It is not called when an object is loaded from the database. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s behavior isn\'t modified by this me...
def init_instance(self, mapper, class_, oldinit, instance, args, kwargs):
return EXT_CONTINUE
'Receive an instance when it\'s constructor has been called, and raised an exception. This method is only called during a userland construction of an object. It is not called when an object is loaded from the database. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s beha...
def init_failed(self, mapper, class_, oldinit, instance, args, kwargs):
return EXT_CONTINUE
'Perform pre-processing on the given result row and return a new row instance. This is called when the mapper first receives a row, before the object identity or the instance itself has been derived from that row. The given row may or may not be a ``RowProxy`` object - it will always be a dictionary-like object which...
def translate_row(self, mapper, context, row):
return EXT_CONTINUE
'Receive a row when a new object instance is about to be created from that row. The method can choose to create the instance itself, or it can return EXT_CONTINUE to indicate normal object creation should take place. mapper The mapper doing the operation selectcontext The QueryContext generated from the Query. row The ...
def create_instance(self, mapper, selectcontext, row, class_):
return EXT_CONTINUE
'Receive an object instance before that instance is appended to a result list. If this method returns EXT_CONTINUE, result appending will proceed normally. if this method returns any other value or None, result appending will not proceed for this instance, giving this extension an opportunity to do the appending itsel...
def append_result(self, mapper, selectcontext, row, instance, result, **flags):
return EXT_CONTINUE
'Receive an instance before that instance has its attributes populated. This usually corresponds to a newly loaded instance but may also correspond to an already-loaded instance which has unloaded attributes to be populated. The method may be called many times for a single instance, as multiple result rows are used to...
def populate_instance(self, mapper, selectcontext, row, instance, **flags):
return EXT_CONTINUE
'Receive an object instance after it has been created via ``__new__``, and after initial attribute population has occurred. This typically occurs when the instance is created based on incoming result rows, and is only called once for that instance\'s lifetime. Note that during a result-row load, this method is called u...
def reconstruct_instance(self, mapper, instance):
return EXT_CONTINUE
'Receive an object instance before that instance is inserted into its table. This is a good place to set up primary key values and such that aren\'t handled otherwise. Column-based attributes can be modified within this method which will result in the new value being inserted. However *no* changes to the overall flush...
def before_insert(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive an object instance after that instance is inserted. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s behavior isn\'t modified by this method.'
def after_insert(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive an object instance before that instance is updated. Note that this method is called for all instances that are marked as "dirty", even those which have no net changes to their column-based attributes. An object is marked as dirty when any of its column-based attributes have a "set attribute" operation called o...
def before_update(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive an object instance after that instance is updated. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s behavior isn\'t modified by this method.'
def after_update(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive an object instance before that instance is deleted. Note that *no* changes to the overall flush plan can be made here; and manipulation of the ``Session`` will not have the desired effect. To manipulate the ``Session`` within an extension, use ``SessionExtension``. The return value is only significant within t...
def before_delete(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive an object instance after that instance is deleted. The return value is only significant within the ``MapperExtension`` chain; the parent mapper\'s behavior isn\'t modified by this method.'
def after_delete(self, mapper, connection, instance):
return EXT_CONTINUE
'Receive a collection append event. The returned value will be used as the actual value to be appended.'
def append(self, state, value, initiator):
return value
'Receive a remove event. No return value is defined.'
def remove(self, state, value, initiator):
pass
'Receive a set event. The returned value will be used as the actual value to be set.'
def set(self, state, value, oldvalue, initiator):
return value
'Return the mapped class ultimately represented by this :class:`.AliasedInsp`.'
@property def class_(self):
return self.mapper.class_
'Provide a column-level property for use with a Mapper. Column-based properties can normally be applied to the mapper\'s ``properties`` dictionary using the :class:`.Column` element directly. Use this function when the given column is not directly present within the mapper\'s selectable; examples include SQL expression...
def __init__(self, *columns, **kwargs):
self._orig_columns = [expression._labeled(c) for c in columns] self.columns = [expression._labeled(_orm_full_deannotate(c)) for c in columns] self.group = kwargs.pop('group', None) self.deferred = kwargs.pop('deferred', False) self.instrument = kwargs.pop('_instrument', True) self.comparator_fac...
'Return the primary column or expression for this ColumnProperty.'
@property def expression(self):
return self.columns[0]
'proxy attribute access down to the mapped column. this allows user-defined comparison methods to be accessed.'
def __getattr__(self, key):
return getattr(self.__clause_element__(), key)
'Adapt incoming clauses to transformations which have been applied within this query.'
def _adapt_clause(self, clause, as_filter, orm_only):
adapters = [] orm_only = getattr(self, '_orm_only_adapt', orm_only) if (as_filter and self._filter_aliases): for fa in self._filter_aliases._visitor_iterator: adapters.append((orm_only, fa.replace)) if self._from_obj_alias: adapters.append((getattr(self, '_orm_only_from_obj_a...
'The full SELECT statement represented by this Query. The statement by default will not have disambiguating labels applied to the construct unless with_labels(True) is called first.'
@property def statement(self):
stmt = self._compile_context(labels=self._with_labels).statement if self._params: stmt = stmt.params(self._params) return stmt._annotate({'no_replacement_traverse': True})
'return the full SELECT statement represented by this :class:`.Query`, embedded within an :class:`.Alias`. Eager JOIN generation within the query is disabled. :param name: string name to be assigned as the alias; this is passed through to :meth:`.FromClause.alias`. If ``None``, a name will be deterministically generate...
def subquery(self, name=None, with_labels=False, reduce_columns=False):
q = self.enable_eagerloads(False) if with_labels: q = q.with_labels() q = q.statement if reduce_columns: q = q.reduce_columns() return q.alias(name=name)
'Return the full SELECT statement represented by this :class:`.Query` represented as a common table expression (CTE). .. versionadded:: 0.7.6 Parameters and usage are the same as those of the :meth:`.SelectBase.cte` method; see that method for further details. Here is the `Postgresql WITH RECURSIVE example <http://www....
def cte(self, name=None, recursive=False):
return self.enable_eagerloads(False).statement.cte(name=name, recursive=recursive)
'Return the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.label`. .. versionadded:: 0.6.5'
def label(self, name):
return self.enable_eagerloads(False).statement.label(name)
'Return the full SELECT statement represented by this :class:`.Query`, converted to a scalar subquery. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.as_scalar`. .. versionadded:: 0.6.5'
def as_scalar(self):
return self.enable_eagerloads(False).statement.as_scalar()
'Return the :class:`.Select` object emitted by this :class:`.Query`. Used for :func:`.inspect` compatibility, this is equivalent to:: query.enable_eagerloads(False).with_labels().statement'
@property def selectable(self):
return self.__clause_element__()
'Control whether or not eager joins and subqueries are rendered. When set to False, the returned Query will not render eager joins regardless of :func:`~sqlalchemy.orm.joinedload`, :func:`~sqlalchemy.orm.subqueryload` options or mapper-level ``lazy=\'joined\'``/``lazy=\'subquery\'`` configurations. This is used primari...
@_generative() def enable_eagerloads(self, value):
self._enable_eagerloads = value
'Apply column labels to the return value of Query.statement. Indicates that this Query\'s `statement` accessor should return a SELECT statement that applies labels to all columns in the form <tablename>_<columnname>; this is commonly used to disambiguate columns from multiple tables which have the same name. When the `...
@_generative() def with_labels(self):
self._with_labels = True
'Control whether assertions are generated. When set to False, the returned Query will not assert its state before certain operations, including that LIMIT/OFFSET has not been applied when filter() is called, no criterion exists when get() is called, and no "from_statement()" exists when filter()/order_by()/group_by() e...
@_generative() def enable_assertions(self, value):
self._enable_assertions = value
'A readonly attribute which returns the current WHERE criterion for this Query. This returned value is a SQL expression construct, or ``None`` if no criterion has been established.'
@property def whereclause(self):
return self._criterion
'indicate that this query applies to objects loaded within a certain path. Used by deferred loaders (see strategies.py) which transfer query options from an originating query to a newly generated query intended for the deferred load.'
@_generative() def _with_current_path(self, path):
self._current_path = path
'Load columns for inheriting classes. :meth:`.Query.with_polymorphic` applies transformations to the "main" mapped class represented by this :class:`.Query`. The "main" mapped class here means the :class:`.Query` object\'s first argument is a full class, i.e. ``session.query(SomeClass)``. These transformations allow ad...
@_generative(_no_clauseelement_condition) def with_polymorphic(self, cls_or_mappers, selectable=None, polymorphic_on=None):
if (not self._primary_entity): raise sa_exc.InvalidRequestError('No primary mapper set up for this Query.') entity = self._entities[0]._clone() self._entities = ([entity] + self._entities[1:]) entity.set_with_polymorphic(self, cls_or_mappers, selectable=selectable, polymorph...
'Yield only ``count`` rows at a time. WARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten. In particular, it\'s usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=\'joined\' or \'subq...
@_generative() def yield_per(self, count):
self._yield_per = count self._execution_options = self._execution_options.union({'stream_results': True})
'Return an instance based on the given primary key identifier, or ``None`` if not found. E.g.:: my_user = session.query(User).get(5) some_object = session.query(VersionedFoo).get((5, 10)) :meth:`~.Query.get` is special in that it provides direct access to the identity map of the owning :class:`.Session`. If the given p...
def get(self, ident):
if hasattr(ident, '__composite_values__'): ident = ident.__composite_values__() ident = util.to_list(ident) mapper = self._only_full_mapper_zero('get') if (len(ident) != len(mapper.primary_key)): raise sa_exc.InvalidRequestError(('Incorrect number of values in identifier ...
'Return a :class:`.Query` construct which will correlate the given FROM clauses to that of an enclosing :class:`.Query` or :func:`~.expression.select`. The method here accepts mapped classes, :func:`.aliased` constructs, and :func:`.mapper` constructs as arguments, which are resolved into expression constructs, in addi...
@_generative() def correlate(self, *args):
self._correlate = self._correlate.union(((_interpret_as_from(s) if (s is not None) else None) for s in args))
'Return a Query with a specific \'autoflush\' setting. Note that a Session with autoflush=False will not autoflush, even if this flag is set to True at the Query level. Therefore this flag is usually used only to disable autoflush for a specific Query.'
@_generative() def autoflush(self, setting):
self._autoflush = setting
'Return a :class:`.Query` that will expire and refresh all instances as they are loaded, or reused from the current :class:`.Session`. :meth:`.populate_existing` does not improve behavior when the ORM is used normally - the :class:`.Session` object\'s usual behavior of maintaining a transaction and expiring all attribu...
@_generative() def populate_existing(self):
self._populate_existing = True
'Set the \'invoke all eagers\' flag which causes joined- and subquery loaders to traverse into already-loaded related objects and collections. Default is that of :attr:`.Query._invoke_all_eagers`.'
@_generative() def _with_invoke_all_eagers(self, value):
self._invoke_all_eagers = value
'Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. The method uses the :func:`.with_parent` function to generate the clause, the result of which is passed to :meth:`.Query.filter`. Parameter...
def with_parent(self, instance, property=None):
if (property is None): mapper = object_mapper(instance) for prop in mapper.iterate_properties: if (isinstance(prop, properties.RelationshipProperty) and (prop.mapper is self._mapper_zero())): property = prop break else: raise sa_exc.Inv...
'add a mapped entity to the list of result columns to be returned.'
@_generative() def add_entity(self, entity, alias=None):
if (alias is not None): entity = aliased(entity, alias) self._entities = list(self._entities) m = _MapperEntity(self, entity) self._set_entity_selectables([m])
'Return a :class:`.Query` that will use the given :class:`.Session`.'
@_generative() def with_session(self, session):
self.session = session
'return a Query that selects from this Query\'s SELECT statement. \*entities - optional list of entities which will replace those being selected.'
def from_self(self, *entities):
fromclause = self.with_labels().enable_eagerloads(False)._enable_single_crit(False).statement.correlate(None) q = self._from_selectable(fromclause) if entities: q._set_entities(entities) return q
'Return an iterator yielding result tuples corresponding to the given list of columns'
def values(self, *columns):
if (not columns): return iter(()) q = self._clone() q._set_entities(columns, entity_wrapper=_ColumnEntity) if (not q._yield_per): q._yield_per = 10 return iter(q)
'Return a scalar result corresponding to the given column expression.'
def value(self, column):
try: return next(self.values(column))[0] except StopIteration: return None
'Return a new :class:`.Query` replacing the SELECT list with the given entities. e.g.:: # Users, filtered on some arbitrary criterion # and then ordered by related email address q = session.query(User).\ join(User.address).\ filter(User.name.like(\'%ed%\')).\ order_by(Address.email) # given *only* User.id==5, Address.e...
@_generative() def with_entities(self, *entities):
self._set_entities(entities)
'Add one or more column expressions to the list of result columns to be returned.'
@_generative() def add_columns(self, *column):
self._entities = list(self._entities) l = len(self._entities) for c in column: _ColumnEntity(self, c) self._set_entity_selectables(self._entities[l:])
'Add a column expression to the list of result columns to be returned. Pending deprecation: :meth:`.add_column` will be superseded by :meth:`.add_columns`.'
@util.pending_deprecation('0.7', ':meth:`.add_column` is superseded by :meth:`.add_columns`', False) def add_column(self, column):
return self.add_columns(column)
'Return a new Query object, applying the given list of mapper options. Most supplied options regard changing how column- and relationship-mapped attributes are loaded. See the sections :ref:`deferred` and :doc:`/orm/loading` for reference documentation.'
def options(self, *args):
return self._options(False, *args)
'Return a new :class:`.Query` object transformed by the given function. E.g.:: def filter_something(criterion): def transform(q): return q.filter(criterion) return transform q = q.with_transformation(filter_something(x==5)) This allows ad-hoc recipes to be created for :class:`.Query` objects. See the example at :ref:`...
def with_transformation(self, fn):
return fn(self)
'Add an indexing hint for the given entity or selectable to this :class:`.Query`. Functionality is passed straight through to :meth:`~sqlalchemy.sql.expression.Select.with_hint`, with the addition that ``selectable`` can be a :class:`.Table`, :class:`.Alias`, or ORM entity / mapped class /etc.'
@_generative() def with_hint(self, selectable, text, dialect_name='*'):
selectable = inspect(selectable).selectable self._with_hints += ((selectable, text, dialect_name),)
'Set non-SQL options which take effect during execution. The options are the same as those accepted by :meth:`.Connection.execution_options`. Note that the ``stream_results`` execution option is enabled automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()` method is used.'
@_generative() def execution_options(self, **kwargs):
self._execution_options = self._execution_options.union(kwargs)
'Return a new :class:`.Query` object with the specified "locking mode", which essentially refers to the ``FOR UPDATE`` clause. .. deprecated:: 0.9.0 superseded by :meth:`.Query.with_for_update`. :param mode: a string representing the desired locking mode. Valid values are: * ``None`` - translates to no lockmode * ``\'u...
@_generative() def with_lockmode(self, mode):
self._for_update_arg = LockmodeArg.parse_legacy_query(mode)
'return a new :class:`.Query` with the specified options for the ``FOR UPDATE`` clause. The behavior of this method is identical to that of :meth:`.SelectBase.with_for_update`. When called with no arguments, the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause appended. When additional arguments are s...
@_generative() def with_for_update(self, read=False, nowait=False, of=None):
self._for_update_arg = LockmodeArg(read=read, nowait=nowait, of=of)
'add values for bind parameters which may have been specified in filter(). parameters may be specified using \**kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that \**kwargs is convenient, however some parameter dictionaries contain unicode keys in which case \**kwarg...
@_generative() def params(self, *args, **kwargs):
if (len(args) == 1): kwargs.update(args[0]) elif (len(args) > 0): raise sa_exc.ArgumentError('params() takes zero or one positional argument, which is a dictionary.') self._params = self._params.copy() self._params.update(kwargs)
'apply the given filtering criterion to a copy of this :class:`.Query`, using SQL expressions. e.g.:: session.query(MyClass).filter(MyClass.name == \'some name\') Multiple criteria are joined together by AND:: session.query(MyClass).\ filter(MyClass.name == \'some name\', MyClass.id > 5) The criterion is any SQL expres...
@_generative(_no_statement_condition, _no_limit_offset) def filter(self, *criterion):
for criterion in list(criterion): criterion = expression._literal_as_text(criterion) criterion = self._adapt_clause(criterion, True, True) if (self._criterion is not None): self._criterion = (self._criterion & criterion) else: self._criterion = criterion
'apply the given filtering criterion to a copy of this :class:`.Query`, using keyword expressions. e.g.:: session.query(MyClass).filter_by(name = \'some name\') Multiple criteria are joined together by AND:: session.query(MyClass).\ filter_by(name = \'some name\', id = 5) The keyword expressions are extracted from the ...
def filter_by(self, **kwargs):
clauses = [(_entity_descriptor(self._joinpoint_zero(), key) == value) for (key, value) in kwargs.items()] return self.filter(sql.and_(*clauses))
'apply one or more ORDER BY criterion to the query and return the newly resulting ``Query`` All existing ORDER BY settings can be suppressed by passing ``None`` - this will suppress any ORDER BY configured on mappers as well. Alternatively, an existing ORDER BY setting on the Query object can be entirely cancelled by p...
@_generative(_no_statement_condition, _no_limit_offset) def order_by(self, *criterion):
if (len(criterion) == 1): if (criterion[0] is False): if ('_order_by' in self.__dict__): del self._order_by return if (criterion[0] is None): self._order_by = None return criterion = self._adapt_col_list(criterion) if ((self._or...
'apply one or more GROUP BY criterion to the query and return the newly resulting :class:`.Query`'
@_generative(_no_statement_condition, _no_limit_offset) def group_by(self, *criterion):
criterion = list(chain(*[_orm_columns(c) for c in criterion])) criterion = self._adapt_col_list(criterion) if (self._group_by is False): self._group_by = criterion else: self._group_by = (self._group_by + criterion)
'apply a HAVING criterion to the query and return the newly resulting :class:`.Query`. :meth:`~.Query.having` is used in conjunction with :meth:`~.Query.group_by`. HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:: q = session.query(User.id).\ join(User.ad...
@_generative(_no_statement_condition, _no_limit_offset) def having(self, criterion):
if isinstance(criterion, util.string_types): criterion = sql.text(criterion) if ((criterion is not None) and (not isinstance(criterion, sql.ClauseElement))): raise sa_exc.ArgumentError('having() argument must be of type sqlalchemy.sql.ClauseElement or string') criteri...
'Produce a UNION of this Query against one or more queries. e.g.:: q1 = sess.query(SomeClass).filter(SomeClass.foo==\'bar\') q2 = sess.query(SomeClass).filter(SomeClass.bar==\'foo\') q3 = q1.union(q2) The method accepts multiple Query objects so as to control the level of nesting. A series of ``union()`` calls such as...
def union(self, *q):
return self._from_selectable(expression.union(*([self] + list(q))))
'Produce a UNION ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples.'
def union_all(self, *q):
return self._from_selectable(expression.union_all(*([self] + list(q))))
'Produce an INTERSECT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples.'
def intersect(self, *q):
return self._from_selectable(expression.intersect(*([self] + list(q))))
'Produce an INTERSECT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples.'
def intersect_all(self, *q):
return self._from_selectable(expression.intersect_all(*([self] + list(q))))
'Produce an EXCEPT of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples.'
def except_(self, *q):
return self._from_selectable(expression.except_(*([self] + list(q))))
'Produce an EXCEPT ALL of this Query against one or more queries. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See that method for usage examples.'
def except_all(self, *q):
return self._from_selectable(expression.except_all(*([self] + list(q))))
'Create a SQL JOIN against this :class:`.Query` object\'s criterion and apply generatively, returning the newly resulting :class:`.Query`. **Simple Relationship Joins** Consider a mapping between two classes ``User`` and ``Address``, with a relationship ``User.addresses`` representing a collection of ``Address`` object...
def join(self, *props, **kwargs):
(aliased, from_joinpoint) = (kwargs.pop('aliased', False), kwargs.pop('from_joinpoint', False)) if kwargs: raise TypeError(('unknown arguments: %s' % ','.join(kwargs.keys))) return self._join(props, outerjoin=False, create_aliases=aliased, from_joinpoint=from_joinpoint)
'Create a left outer join against this ``Query`` object\'s criterion and apply generatively, returning the newly resulting ``Query``. Usage is the same as the ``join()`` method.'
def outerjoin(self, *props, **kwargs):
(aliased, from_joinpoint) = (kwargs.pop('aliased', False), kwargs.pop('from_joinpoint', False)) if kwargs: raise TypeError(('unknown arguments: %s' % ','.join(kwargs))) return self._join(props, outerjoin=True, create_aliases=aliased, from_joinpoint=from_joinpoint)
'consumes arguments from join() or outerjoin(), places them into a consistent format with which to form the actual JOIN constructs.'
@_generative(_no_statement_condition, _no_limit_offset) def _join(self, keys, outerjoin, create_aliases, from_joinpoint):
if (not from_joinpoint): self._reset_joinpoint() if ((len(keys) == 2) and isinstance(keys[0], (expression.FromClause, type, AliasedClass)) and isinstance(keys[1], (str, expression.ClauseElement, interfaces.PropComparator))): keys = (keys,) for arg1 in util.to_list(keys): if isinstanc...
'append a JOIN to the query\'s from clause.'
def _join_left_to_right(self, left, right, onclause, outerjoin, create_aliases, prop):
self._polymorphic_adapters = self._polymorphic_adapters.copy() if (left is None): if self._from_obj: left = self._from_obj[0] elif self._entities: left = self._entities[0].entity_zero_or_selectable if (left is None): raise sa_exc.InvalidRequestError(("Don't ...
'Return a new :class:`.Query`, where the "join point" has been reset back to the base FROM entities of the query. This method is usually used in conjunction with the ``aliased=True`` feature of the :meth:`~.Query.join` method. See the example in :meth:`~.Query.join` for how this is used.'
@_generative(_no_statement_condition) def reset_joinpoint(self):
self._reset_joinpoint()
'Set the FROM clause of this :class:`.Query` explicitly. :meth:`.Query.select_from` is often used in conjunction with :meth:`.Query.join` in order to control which entity is selected from on the "left" side of the join. The entity or selectable object here effectively replaces the "left edge" of any calls to :meth:`~.Q...
@_generative(_no_clauseelement_condition) def select_from(self, *from_obj):
self._set_select_from(from_obj, False)
'Set the FROM clause of this :class:`.Query` to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities. This method is similar to the :meth:`.Query.select_from` method, in that it sets the FROM clause of the query. However, where :meth:`.Query.select_from` only affects what is pl...
@_generative(_no_clauseelement_condition) def select_entity_from(self, from_obj):
self._set_select_from([from_obj], True)
'apply LIMIT/OFFSET to the ``Query`` based on a " "range and return the newly resulting ``Query``.'
@_generative(_no_statement_condition) def slice(self, start, stop):
if ((start is not None) and (stop is not None)): self._offset = ((self._offset or 0) + start) self._limit = (stop - start) elif ((start is None) and (stop is not None)): self._limit = stop elif ((start is not None) and (stop is None)): self._offset = ((self._offset or 0) + st...
'Apply a ``LIMIT`` to the query and return the newly resulting ``Query``.'
@_generative(_no_statement_condition) def limit(self, limit):
self._limit = limit
'Apply an ``OFFSET`` to the query and return the newly resulting ``Query``.'
@_generative(_no_statement_condition) def offset(self, offset):
self._offset = offset
'Apply a ``DISTINCT`` to the query and return the newly resulting ``Query``. :param \*expr: optional column expressions. When present, the Postgresql dialect will render a ``DISTINCT ON (<expressions>>)`` construct.'
@_generative(_no_statement_condition) def distinct(self, *criterion):
if (not criterion): self._distinct = True else: criterion = self._adapt_col_list(criterion) if isinstance(self._distinct, list): self._distinct += criterion else: self._distinct = criterion
'Apply the prefixes to the query and return the newly resulting ``Query``. :param \*prefixes: optional prefixes, typically strings, not using any commas. In particular is useful for MySQL keywords. e.g.:: query = sess.query(User.name).\ prefix_with(\'HIGH_PRIORITY\').\ prefix_with(\'SQL_SMALL_RESULT\', \'ALL\') Would...
@_generative() def prefix_with(self, *prefixes):
if self._prefixes: self._prefixes += prefixes else: self._prefixes = prefixes
'Return the results represented by this ``Query`` as a list. This results in an execution of the underlying query.'
def all(self):
return list(self)
'Execute the given SELECT statement and return results. This method bypasses all internal statement compilation, and the statement is executed without modification. The statement argument is either a string, a ``select()`` construct, or a ``text()`` construct, and should return the set of columns appropriate to the ent...
@_generative(_no_clauseelement_condition) def from_statement(self, statement):
if isinstance(statement, util.string_types): statement = sql.text(statement) if (not isinstance(statement, (expression.TextClause, expression.SelectBase))): raise sa_exc.ArgumentError('from_statement accepts text(), select(), and union() objects only.') self._statement =...
'Return the first result of this ``Query`` or None if the result doesn\'t contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling ``first(...
def first(self):
if (self._statement is not None): ret = list(self)[0:1] else: ret = list(self[0:1]) if (len(ret) > 0): return ret[0] else: return None
'Return exactly one result or raise an exception. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound`` if multiple object identities are returned, or if multiple rows are returned for a query that does not return object identities. Note that an en...
def one(self):
ret = list(self) l = len(ret) if (l == 1): return ret[0] elif (l == 0): raise orm_exc.NoResultFound('No row was found for one()') else: raise orm_exc.MultipleResultsFound('Multiple rows were found for one()')
'Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound. >>> session.query(Item).scalar() <Item> >>> session.query(Item.id).scalar() 1 >>> session.query(Item.id).filter(Item.id < 0).scalar() None >>> session.query(Item.id, Item.name).scalar()...
def scalar(self):
try: ret = self.one() if (not isinstance(ret, tuple)): return ret return ret[0] except orm_exc.NoResultFound: return None
'Return metadata about the columns which would be returned by this :class:`.Query`. Format is a list of dictionaries:: user_alias = aliased(User, name=\'user2\') q = sess.query(User, User.id, user_alias) # this expression: q.column_descriptions # would return: \'name\':\'User\', \'type\':User, \'aliased\':False, \'expr...
@property def column_descriptions(self):
return [{'name': ent._label_name, 'type': ent.type, 'aliased': getattr(ent, 'is_aliased_class', False), 'expr': ent.expr} for ent in self._entities]
'Given a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator. e.g.:: result = engine.execute("select * from users") for u in session.query(User).instances(result): print u'
def instances(self, cursor, __context=None):
context = __context if (context is None): context = QueryContext(self) return loading.instances(self, cursor, context)