class Result(_WithKeys, ResultInternal):
Known subclasses: sqlalchemy.engine.cursor.CursorResult
, sqlalchemy.engine.result.IteratorResult
Represent a set of database results.
.Result
object provides a completely
updated usage model and calling facade for SQLAlchemy Core and
SQLAlchemy ORM. In Core, it forms the basis of the
.CursorResult
object which replaces the previous
.ResultProxy
interface. When using the ORM, a higher level
object called .ChunkedIteratorResult
is normally used.Note
In SQLAlchemy 1.4 and above, this object is
used for ORM results returned by _orm.Session.execute
, which can
yield instances of ORM mapped objects either individually or within
tuple-like rows. Note that the _result.Result
object does not
deduplicate instances or rows automatically as is the case with the
legacy _orm.Query
object. For in-Python de-duplication of
instances or rows, use the _result.Result.unique
modifier
method.
See Also
:ref:`tutorial_fetching_rows` - in the :doc:`/tutorial/index`
Method | __init__ |
Undocumented |
Method | __iter__ |
Undocumented |
Method | __next__ |
Undocumented |
Method | _fetchall_impl |
Undocumented |
Method | _fetchiter_impl |
Undocumented |
Method | _fetchmany_impl |
Undocumented |
Method | _fetchone_impl |
Undocumented |
Method | _getter |
return a callable that will retrieve the given key from a .Row . |
Method | _raw_row_iterator |
Return a safe iterator that yields raw row data. |
Method | _soft_close |
Undocumented |
Method | _tuple_getter |
return a callable that will retrieve the given keys from a .Row . |
Method | all |
Return all rows in a list. |
Method | close |
close this _result.Result . |
Method | columns |
Establish the columns that should be returned in each row. |
Method | fetchall |
A synonym for the _engine.Result.all method. |
Method | fetchmany |
Fetch many rows. |
Method | fetchone |
Fetch one row. |
Method | first |
Fetch the first row or None if no row is present. |
Method | freeze |
Return a callable object that will produce copies of this .Result when invoked. |
Method | mappings |
Apply a mappings filter to returned rows, returning an instance of _result.MappingResult . |
Method | merge |
Merge this .Result with other compatible result objects. |
Method | next |
Undocumented |
Method | one |
Return exactly one row or raise an exception. |
Method | one_or_none |
Return at most one result or raise an exception. |
Method | partitions |
Iterate through sub-lists of rows of the size given. |
Method | scalar |
Fetch the first column of the first row, and close the result set. |
Method | scalar_one |
Return exactly one scalar result or raise an exception. |
Method | scalar_one_or_none |
Return exactly one or no scalar result. |
Method | scalars |
Return a _result.ScalarResult filtering object which will return single elements rather than _row.Row objects. |
Method | unique |
Apply unique filtering to the objects returned by this _engine.Result . |
Method | yield_per |
Configure the row-fetching strategy to fetch num rows at a time. |
Class Variable | _attributes |
Undocumented |
Class Variable | _row_logging_fn |
Undocumented |
Class Variable | _source_supports_scalars |
Undocumented |
Instance Variable | _metadata |
Undocumented |
Instance Variable | _unique_filter_state |
Undocumented |
Instance Variable | _yield_per |
Undocumented |
Inherited from _WithKeys
:
Method | keys |
Return an iterable view which yields the string keys that would be represented by each .Row . |
Inherited from ResultInternal
:
Method | _allrows |
Undocumented |
Method | _column_slices |
Undocumented |
Method | _iter_impl |
Undocumented |
Method | _iterator_getter |
Undocumented |
Method | _manyrow_getter |
Undocumented |
Method | _next_impl |
Undocumented |
Method | _onerow_getter |
Undocumented |
Method | _only_one_row |
Undocumented |
Method | _raw_all_rows |
Undocumented |
Method | _row_getter |
Undocumented |
Method | _unique_strategy |
Undocumented |
Class Variable | _post_creational_filter |
Undocumented |
Class Variable | _real_result |
Undocumented |
Instance Variable | _generate_rows |
Undocumented |
Inherited from InPlaceGenerative
(via ResultInternal
):
Method | _generate |
Undocumented |
sqlalchemy.engine.result.IteratorResult
Undocumented
.Row
.Return a safe iterator that yields raw row data.
This is used by the ._engine.Result.merge
method
to merge multiple compatible results together.
Return all rows in a list.
Closes the result set after invocation. Subsequent invocations will return an empty list.
Returns | |
a list of .Row objects. |
sqlalchemy.engine.cursor.CursorResult
close this _result.Result
.
The behavior of this method is implementation specific, and is
not implemented by default. The method should generally end
the resources in use by the result object and also cause any
subsequent iteration or row fetching to raise
.ResourceClosedError
.
_result.Result
classes, instead only
being available on the _engine.CursorResult
returned for
Core statement executions. As most other result objects, namely the
ones used by the ORM, are proxying a _engine.CursorResult
in any case, this allows the underlying cursor result to be closed
from the outside facade for the case when the ORM query is using
the yield_per execution option where it does not immediately
exhaust and autoclose the database cursor.Establish the columns that should be returned in each row.
This method may be used to limit the columns returned as well
as to reorder them. The given list of expressions are normally
a series of integers or string key names. They may also be
appropriate .ColumnElement
objects which correspond to
a given statement construct.
E.g.:
statement = select(table.c.x, table.c.y, table.c.z) result = connection.execute(statement) for z, y in result.columns('z', 'y'): # ...
Example of using the column objects from the statement itself:
for z, y in result.columns( statement.selected_columns.c.z, statement.selected_columns.c.y ): # ...
Parameters | |
*col_expressions | indicates columns to be returned. Elements
may be integer row indexes, string column names, or appropriate
.ColumnElement objects corresponding to a select construct. |
Returns | |
this _engine.Result object with the modifications
given. |
Fetch many rows.
When all rows are exhausted, returns an empty list.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch rows in groups, use the ._result.Result.partitions
method.
Returns | |
a list of .Row objects. |
Fetch one row.
When all rows are exhausted, returns None.
This method is provided for backwards compatibility with SQLAlchemy 1.x.x.
To fetch the first row of a result only, use the
_engine.Result.first
method. To iterate through all
rows, iterate the _engine.Result
object directly.
Returns | |
a .Row object if no filters are applied, or None
if no rows remain. |
Fetch the first row or None if no row is present.
Closes the result set and discards remaining rows.
Note
This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the .Result.scalar
method,
or combine .Result.scalars
and .Result.first
.
Additionally, in contrast to the behavior of the legacy ORM
_orm.Query.first
method, no limit is applied to the
SQL query which was invoked to produce this _engine.Result
;
for a DBAPI driver that buffers results in memory before yielding
rows, all rows will be sent to the Python process and all but
the first row will be discarded.
See Also
See Also
_result.Result.scalar
_result.Result.one
Returns | |
a .Row object, or None
if no rows remain. |
Return a callable object that will produce copies of this
.Result
when invoked.
The callable object returned is an instance of
_engine.FrozenResult
.
This is used for result set caching. The method must be called
on the result when it has been unconsumed, and calling the method
will consume the result fully. When the _engine.FrozenResult
is retrieved from a cache, it can be called any number of times where
it will produce a new _engine.Result
object each time
against its stored set of rows.
See Also
:ref:`do_orm_execute_re_executing` - example usage within the ORM to implement a result-set cache.
Apply a mappings filter to returned rows, returning an instance of
_result.MappingResult
.
When this filter is applied, fetching rows will return
.RowMapping
objects instead of .Row
objects.
Returns | |
a new _result.MappingResult filtering object
referring to this _result.Result object. |
sqlalchemy.engine.cursor.CursorResult
Merge this .Result
with other compatible result
objects.
The object returned is an instance of _engine.MergedResult
,
which will be composed of iterators from the given result
objects.
The new result will use the metadata from this result object. The subsequent result objects must be against an identical set of result / cursor metadata, otherwise the behavior is undefined.
Return exactly one row or raise an exception.
Raises .NoResultFound
if the result returns no
rows, or .MultipleResultsFound
if multiple rows
would be returned.
Note
This method returns one row, e.g. tuple, by default.
To return exactly one single scalar value, that is, the first
column of the first row, use the .Result.scalar_one
method,
or combine .Result.scalars
and .Result.one
.
See Also
_result.Result.first
_result.Result.one_or_none
_result.Result.scalar_one
Returns | |
The first .Row . | |
Raises | |
Unknown exception | .MultipleResultsFound , .NoResultFound |
Return at most one result or raise an exception.
Returns None if the result has no rows.
Raises .MultipleResultsFound
if multiple rows are returned.
See Also
_result.Result.first
_result.Result.one
Returns | |
The first .Row or None if no row is available. | |
Raises | |
Unknown exception | .MultipleResultsFound |
Iterate through sub-lists of rows of the size given.
Each list will be of the size given, excluding the last list to be yielded, which may have a small number of rows. No empty lists will be yielded.
The result object is automatically closed when the iterator is fully consumed.
Note that the backend driver will usually buffer the entire result ahead of time unless the :paramref:`.Connection.execution_options.stream_results` execution option is used indicating that the driver should not pre-buffer results, if possible. Not all drivers support this option and the option is silently ignored for those who do not.
Parameters | |
size | indicate the maximum number of rows to be present
in each list yielded. If None, makes use of the value set by
_engine.Result.yield_per , if present, otherwise uses the
_engine.Result.fetchmany default which may be backend
specific. |
Returns | |
iterator of lists |
Fetch the first column of the first row, and close the result set.
Returns None if there are no rows to fetch.
No validation is performed to test if additional rows remain.
After calling this method, the object is fully closed,
e.g. the _engine.CursorResult.close
method will have been called.
Returns | |
a Python scalar value , or None if no rows remain. |
Return exactly one scalar result or raise an exception.
This is equivalent to calling .Result.scalars
and then
.Result.one
.
See Also
.Result.one
.Result.scalars
Return exactly one or no scalar result.
This is equivalent to calling .Result.scalars
and then
.Result.one_or_none
.
See Also
.Result.one_or_none
.Result.scalars
Return a _result.ScalarResult
filtering object which
will return single elements rather than _row.Row
objects.
E.g.:
>>> result = conn.execute(text("select int_id from table")) >>> result.scalars().all() [1, 2, 3]
When results are fetched from the _result.ScalarResult
filtering object, the single column-row that would be returned by the
_result.Result
is instead returned as the column's value.
Parameters | |
index | integer or row key indicating the column to be fetched from each row, defaults to 0 indicating the first column. |
Returns | |
a new _result.ScalarResult filtering object referring
to this _result.Result object. |
Apply unique filtering to the objects returned by this
_engine.Result
.
When this filter is applied with no arguments, the rows or objects returned will filtered such that each row is returned uniquely. The algorithm used to determine this uniqueness is by default the Python hashing identity of the whole tuple. In some cases a specialized per-entity hashing scheme may be used, such as when using the ORM, a scheme is applied which works against the primary key identity of returned objects.
The unique filter is applied after all other filters, which means
if the columns returned have been refined using a method such as the
_engine.Result.columns
or _engine.Result.scalars
method, the uniquing is applied to only the column or columns
returned. This occurs regardless of the order in which these
methods have been called upon the _engine.Result
object.
The unique filter also changes the calculus used for methods like
_engine.Result.fetchmany
and _engine.Result.partitions
.
When using _engine.Result.unique
, these methods will continue
to yield the number of rows or objects requested, after uniquing
has been applied. However, this necessarily impacts the buffering
behavior of the underlying cursor or datasource, such that multiple
underlying calls to cursor.fetchmany() may be necessary in order
to accumulate enough objects in order to provide a unique collection
of the requested size.
Parameters | |
strategy | a callable that will be applied to rows or objects
being iterated, which should return an object that represents the
unique value of the row. A Python set() is used to store
these identities. If not passed, a default uniqueness strategy
is used which may have been assembled by the source of this
_engine.Result object. |
Configure the row-fetching strategy to fetch num rows at a time.
This impacts the underlying behavior of the result when iterating over
the result object, or otherwise making use of methods such as
_engine.Result.fetchone
that return one row at a time. Data
from the underlying cursor or other data source will be buffered up to
this many rows in memory, and the buffered collection will then be
yielded out one row at at time or as many rows are requested. Each time
the buffer clears, it will be refreshed to this many rows or as many
rows remain if fewer remain.
The _engine.Result.yield_per
method is generally used in
conjunction with the
:paramref:`_engine.Connection.execution_options.stream_results`
execution option, which will allow the database dialect in use to make
use of a server side cursor, if the DBAPI supports it.
Most DBAPIs do not use server side cursors by default, which means all
rows will be fetched upfront from the database regardless of the
_engine.Result.yield_per
setting. However,
_engine.Result.yield_per
may still be useful in that it batches
the SQLAlchemy-side processing of the raw data from the database, and
additionally when used for ORM scenarios will batch the conversion of
database rows into ORM entity rows.
Parameters | |
num | number of rows to fetch each time the buffer is refilled. If set to a value below 1, fetches all rows for the next buffer. |
sqlalchemy.engine.cursor.CursorResult
, sqlalchemy.engine.result.ChunkedIteratorResult
, sqlalchemy.engine.result.MergedResult
Undocumented