class documentation

Represent a set of database results. .. versionadded:: 1.4 The :class:`_engine.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 :class:`_engine.CursorResult` object which replaces the previous :class:`_engine.ResultProxy` interface. When using the ORM, a higher level object called :class:`_engine.ChunkedIteratorResult` is normally used. .. note:: In SQLAlchemy 1.4 and above, this object is used for ORM results returned by :meth:`_orm.Session.execute`, which can yield instances of ORM mapped objects either individually or within tuple-like rows. Note that the :class:`_engine.Result` object does not deduplicate instances or rows automatically as is the case with the legacy :class:`_orm.Query` object. For in-Python de-duplication of instances or rows, use the :meth:`_engine.Result.unique` modifier method. .. seealso:: :ref:`tutorial_fetching_rows` - in the :doc:`/tutorial/index`

Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Undocumented
Method __iter__ Undocumented
Method __next__ Undocumented
Method all Return all rows in a list.
Method close close this :class:`_engine.Result`.
Method columns Establish the columns that should be returned in each row.
Method fetchall A synonym for the :meth:`_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 :class:`_engine.Result` when invoked.
Method mappings Apply a mappings filter to returned rows, returning an instance of :class:`_engine.MappingResult`.
Method merge Merge this :class:`_engine.Result` with other compatible result objects.
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 scalar result or ``None``.
Method scalars Return a :class:`_engine.ScalarResult` filtering object which will return single elements rather than :class:`_row.Row` objects.
Method tuples Apply a "typed tuple" typing filter to returned rows.
Method unique Apply unique filtering to the objects returned by this :class:`_engine.Result`.
Method yield_per Configure the row-fetching strategy to fetch ``num`` rows at a time.
Class Variable __slots__ Undocumented
Property closed return ``True`` if this :class:`_engine.Result` reports .closed
Property t Apply a "typed tuple" typing filter to returned rows.
Method _getter return a callable that will retrieve the given key from a :class:`_engine.Row`.
Method _raw_row_iterator Return a safe iterator that yields raw row data.
Method _tuple_getter return a callable that will retrieve the given keys from a :class:`_engine.Row`.
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
Property _soft_closed Undocumented

Inherited from _WithKeys:

Method keys Return an iterable view which yields the string keys that would be represented by each :class:`_engine.Row`.

Inherited from ResultInternal (via _WithKeys):

Method _allrows Undocumented
Method _column_slices Undocumented
Method _fetchall_impl Undocumented
Method _fetchiter_impl Undocumented
Method _fetchmany_impl Undocumented
Method _fetchone_impl 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 _soft_close Undocumented
Method _unique_strategy Undocumented
Class Variable _is_cursor Undocumented
Class Variable _post_creational_filter Undocumented
Class Variable _real_result Undocumented
Instance Variable _generate_rows Undocumented

Inherited from InPlaceGenerative (via _WithKeys, ResultInternal):

Method _generate Undocumented
def __enter__(self) -> Self: (source)

Undocumented

def __exit__(self, type_: Any, value: Any, traceback: Any): (source)

Undocumented

def __iter__(self) -> Iterator[Row[_TP]]: (source)

Undocumented

def __next__(self) -> Row[_TP]: (source)

Undocumented

def all(self) -> Sequence[Row[_TP]]: (source)

Return all rows in a list. Closes the result set after invocation. Subsequent invocations will return an empty list. .. versionadded:: 1.4 :return: a list of :class:`_engine.Row` objects.

def close(self): (source)

close this :class:`_engine.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 :class:`.ResourceClosedError`. .. versionadded:: 1.4.27 - ``.close()`` was previously not generally available for all :class:`_engine.Result` classes, instead only being available on the :class:`_engine.CursorResult` returned for Core statement executions. As most other result objects, namely the ones used by the ORM, are proxying a :class:`_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: _KeyIndexType) -> Self: (source)

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 :class:`.ColumnElement` objects which correspond to a given statement construct. .. versionchanged:: 2.0 Due to a bug in 1.4, the :meth:`_engine.Result.columns` method had an incorrect behavior where calling upon the method with just one index would cause the :class:`_engine.Result` object to yield scalar values rather than :class:`_engine.Row` objects. In version 2.0, this behavior has been corrected such that calling upon :meth:`_engine.Result.columns` with a single index will produce a :class:`_engine.Result` object that continues to yield :class:`_engine.Row` objects, which include only a single column. 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 ): # ... .. versionadded:: 1.4 :param \*col_expressions: indicates columns to be returned. Elements may be integer row indexes, string column names, or appropriate :class:`.ColumnElement` objects corresponding to a select construct. :return: this :class:`_engine.Result` object with the modifications given.

def fetchall(self) -> Sequence[Row[_TP]]: (source)

A synonym for the :meth:`_engine.Result.all` method.

def fetchmany(self, size: Optional[int] = None) -> Sequence[Row[_TP]]: (source)

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 :meth:`_engine.Result.partitions` method. :return: a list of :class:`_engine.Row` objects. .. seealso:: :meth:`_engine.Result.partitions`

def fetchone(self) -> Optional[Row[_TP]]: (source)

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 :meth:`_engine.Result.first` method. To iterate through all rows, iterate the :class:`_engine.Result` object directly. :return: a :class:`_engine.Row` object if no filters are applied, or ``None`` if no rows remain.

def first(self) -> Optional[Row[_TP]]: (source)

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 :meth:`_engine.Result.scalar` method, or combine :meth:`_engine.Result.scalars` and :meth:`_engine.Result.first`. Additionally, in contrast to the behavior of the legacy ORM :meth:`_orm.Query.first` method, **no limit is applied** to the SQL query which was invoked to produce this :class:`_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. .. seealso:: :ref:`migration_20_unify_select` :return: a :class:`_engine.Row` object, or None if no rows remain. .. seealso:: :meth:`_engine.Result.scalar` :meth:`_engine.Result.one`

def freeze(self) -> FrozenResult[_TP]: (source)

Return a callable object that will produce copies of this :class:`_engine.Result` when invoked. The callable object returned is an instance of :class:`_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 :class:`_engine.FrozenResult` is retrieved from a cache, it can be called any number of times where it will produce a new :class:`_engine.Result` object each time against its stored set of rows. .. seealso:: :ref:`do_orm_execute_re_executing` - example usage within the ORM to implement a result-set cache.

def mappings(self) -> MappingResult: (source)

Apply a mappings filter to returned rows, returning an instance of :class:`_engine.MappingResult`. When this filter is applied, fetching rows will return :class:`_engine.RowMapping` objects instead of :class:`_engine.Row` objects. .. versionadded:: 1.4 :return: a new :class:`_engine.MappingResult` filtering object referring to this :class:`_engine.Result` object.

def merge(self, *others: Result[Any]) -> MergedResult[_TP]: (source)

Merge this :class:`_engine.Result` with other compatible result objects. The object returned is an instance of :class:`_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 one(self) -> Row[_TP]: (source)

Return exactly one row or raise an exception. Raises :class:`.NoResultFound` if the result returns no rows, or :class:`.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 :meth:`_engine.Result.scalar_one` method, or combine :meth:`_engine.Result.scalars` and :meth:`_engine.Result.one`. .. versionadded:: 1.4 :return: The first :class:`_engine.Row`. :raises: :class:`.MultipleResultsFound`, :class:`.NoResultFound` .. seealso:: :meth:`_engine.Result.first` :meth:`_engine.Result.one_or_none` :meth:`_engine.Result.scalar_one`

def one_or_none(self) -> Optional[Row[_TP]]: (source)

Return at most one result or raise an exception. Returns ``None`` if the result has no rows. Raises :class:`.MultipleResultsFound` if multiple rows are returned. .. versionadded:: 1.4 :return: The first :class:`_engine.Row` or ``None`` if no row is available. :raises: :class:`.MultipleResultsFound` .. seealso:: :meth:`_engine.Result.first` :meth:`_engine.Result.one`

def partitions(self, size: Optional[int] = None) -> Iterator[Sequence[Row[_TP]]]: (source)

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. When using the ORM, the :meth:`_engine.Result.partitions` method is typically more effective from a memory perspective when it is combined with use of the :ref:`yield_per execution option <orm_queryguide_yield_per>`, which instructs both the DBAPI driver to use server side cursors, if available, as well as instructs the ORM loading internals to only build a certain amount of ORM objects from a result at a time before yielding them out. .. versionadded:: 1.4 :param size: indicate the maximum number of rows to be present in each list yielded. If None, makes use of the value set by the :meth:`_engine.Result.yield_per`, method, if it were called, or the :paramref:`_engine.Connection.execution_options.yield_per` execution option, which is equivalent in this regard. If yield_per weren't set, it makes use of the :meth:`_engine.Result.fetchmany` default, which may be backend specific and not well defined. :return: iterator of lists .. seealso:: :ref:`engine_stream_results` :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`

@overload
def scalar(self: Result[Tuple[_T]]) -> Optional[_T]:
@overload
def scalar(self) -> Any:
(source)

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 :meth:`_engine.CursorResult.close` method will have been called. :return: a Python scalar value, or ``None`` if no rows remain.

@overload
def scalar_one(self: Result[Tuple[_T]]) -> _T:
@overload
def scalar_one(self) -> Any:
(source)

Return exactly one scalar result or raise an exception. This is equivalent to calling :meth:`_engine.Result.scalars` and then :meth:`_engine.Result.one`. .. seealso:: :meth:`_engine.Result.one` :meth:`_engine.Result.scalars`

@overload
def scalar_one_or_none(self: Result[Tuple[_T]]) -> Optional[_T]:
@overload
def scalar_one_or_none(self) -> Optional[Any]:
(source)

Return exactly one scalar result or ``None``. This is equivalent to calling :meth:`_engine.Result.scalars` and then :meth:`_engine.Result.one_or_none`. .. seealso:: :meth:`_engine.Result.one_or_none` :meth:`_engine.Result.scalars`

@overload
def scalars(self: Result[Tuple[_T]]) -> ScalarResult[_T]:
@overload
def scalars(self: Result[Tuple[_T]], index: Literal[0]) -> ScalarResult[_T]:
@overload
def scalars(self, index: _KeyIndexType = 0) -> ScalarResult[Any]:
(source)

Return a :class:`_engine.ScalarResult` filtering object which will return single elements rather than :class:`_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 :class:`_engine.ScalarResult` filtering object, the single column-row that would be returned by the :class:`_engine.Result` is instead returned as the column's value. .. versionadded:: 1.4 :param index: integer or row key indicating the column to be fetched from each row, defaults to ``0`` indicating the first column. :return: a new :class:`_engine.ScalarResult` filtering object referring to this :class:`_engine.Result` object.

def tuples(self) -> TupleResult[_TP]: (source)

Apply a "typed tuple" typing filter to returned rows. This method returns the same :class:`_engine.Result` object at runtime, however annotates as returning a :class:`_engine.TupleResult` object that will indicate to :pep:`484` typing tools that plain typed ``Tuple`` instances are returned rather than rows. This allows tuple unpacking and ``__getitem__`` access of :class:`_engine.Row` objects to by typed, for those cases where the statement invoked itself included typing information. .. versionadded:: 2.0 :return: the :class:`_engine.TupleResult` type at typing time. .. seealso:: :attr:`_engine.Result.t` - shorter synonym :attr:`_engine.Row.t` - :class:`_engine.Row` version

@_generative
def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self: (source)

Apply unique filtering to the objects returned by this :class:`_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 :meth:`_engine.Result.columns` or :meth:`_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 :class:`_engine.Result` object. The unique filter also changes the calculus used for methods like :meth:`_engine.Result.fetchmany` and :meth:`_engine.Result.partitions`. When using :meth:`_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. :param 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 :class:`_engine.Result` object.

@_generative
def yield_per(self, num: int) -> Self: (source)

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 :meth:`_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 a 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 :meth:`_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 a specific "server side cursor" mode separate from its default mode of operation. .. tip:: Consider using the :paramref:`_engine.Connection.execution_options.yield_per` execution option, which will simultaneously set :paramref:`_engine.Connection.execution_options.stream_results` to ensure the use of server side cursors, as well as automatically invoke the :meth:`_engine.Result.yield_per` method to establish a fixed row buffer size at once. The :paramref:`_engine.Connection.execution_options.yield_per` execution option is available for ORM operations, with :class:`_orm.Session`-oriented use described at :ref:`orm_queryguide_yield_per`. The Core-only version which works with :class:`_engine.Connection` is new as of SQLAlchemy 1.4.40. .. versionadded:: 1.4 :param 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. .. seealso:: :ref:`engine_stream_results` - describes Core behavior for :meth:`_engine.Result.yield_per` :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`

return ``True`` if this :class:`_engine.Result` reports .closed .. versionadded:: 1.4.43

Apply a "typed tuple" typing filter to returned rows. The :attr:`_engine.Result.t` attribute is a synonym for calling the :meth:`_engine.Result.tuples` method. .. versionadded:: 2.0

def _getter(self, key: _KeyIndexType, raiseerr: bool = True) -> Optional[Callable[[Row[Any]], Any]]: (source)

return a callable that will retrieve the given key from a :class:`_engine.Row`.

def _raw_row_iterator(self) -> Iterator[_RowData]: (source)

Return a safe iterator that yields raw row data. This is used by the :meth:`_engine.Result.merge` method to merge multiple compatible results together.

def _tuple_getter(self, keys: Sequence[_KeyIndexType]) -> _TupleGetterType: (source)

return a callable that will retrieve the given keys from a :class:`_engine.Row`.

_attributes: util.immutabledict[Any, Any] = (source)

Undocumented