class documentation

class Result(_WithKeys, ResultInternal):

Known subclasses: sqlalchemy.engine.cursor.CursorResult, sqlalchemy.engine.result.IteratorResult

View In Hierarchy

Represent a set of database results.

New in version 1.4: The .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.

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
def __init__(self, cursor_metadata):

Undocumented

def __iter__(self):

Undocumented

def __next__(self):

Undocumented

def _fetchall_impl(self):
def _fetchiter_impl(self):
def _fetchmany_impl(self, size=None):
def _fetchone_impl(self, hard_close=False):
def _getter(self, key, raiseerr=True):
return a callable that will retrieve the given key from a .Row.
def _raw_row_iterator(self):

Return a safe iterator that yields raw row data.

This is used by the ._engine.Result.merge method to merge multiple compatible results together.

def _soft_close(self, hard=False):
def _tuple_getter(self, keys):
return a callable that will retrieve the given keys from a .Row.
def all(self):

Return all rows in a list.

Closes the result set after invocation. Subsequent invocations will return an empty list.

New in version 1.4.
Returns
a list of .Row objects.
def close(self):

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.

New in version 1.4.27: - .close() was previously not generally available for all _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.
def columns(self, *col_expressions):

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
):
    # ...
New in version 1.4.
Parameters
*col​_expressionsindicates 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.
def fetchall(self):
A synonym for the _engine.Result.all method.
def fetchmany(self, size=None):

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.
def fetchone(self):

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.
def first(self):

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

_result.Result.scalar

_result.Result.one

Returns
a .Row object, or None if no rows remain.
def freeze(self):

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.

def mappings(self):

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.

New in version 1.4.
Returns
a new _result.MappingResult filtering object referring to this _result.Result object.
def merge(self, *others):

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.

def next(self):

Undocumented

def one(self):

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.

New in version 1.4.

See Also

_result.Result.first

_result.Result.one_or_none

_result.Result.scalar_one

Returns
The first .Row.
Raises
Unknown exception.MultipleResultsFound, .NoResultFound
def one_or_none(self):

Return at most one result or raise an exception.

Returns None if the result has no rows. Raises .MultipleResultsFound if multiple rows are returned.

New in version 1.4.

See Also

_result.Result.first

_result.Result.one

Returns
The first .Row or None if no row is available.
Raises
Unknown exception.MultipleResultsFound
def partitions(self, size=None):

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.

New in version 1.4.
Parameters
sizeindicate 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
def scalar(self):

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.
def scalar_one(self):

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

def scalar_one_or_none(self):

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

def scalars(self, index=0):

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.

New in version 1.4.
Parameters
indexinteger 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.
@_generative
def unique(self, strategy=None):

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
strategya 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.
@_generative
def yield_per(self, num):

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.

New in version 1.4.
Parameters
numnumber of rows to fetch each time the buffer is refilled. If set to a value below 1, fetches all rows for the next buffer.
_attributes =

Undocumented

_row_logging_fn =

Undocumented

_source_supports_scalars: bool =

Undocumented

_metadata =

Undocumented