class Result(_WithKeys, ResultInternal[
Known subclasses: sqlalchemy.engine.cursor.CursorResult
, sqlalchemy.engine.result.IteratorResult
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 |
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 |
Return exactly one scalar result or raise an exception. |
Method | scalar |
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 |
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 |
Return a safe iterator that yields raw row data. |
Method | _tuple |
return a callable that will retrieve the given keys from a :class:`_engine.Row`. |
Class Variable | _attributes |
Undocumented |
Class Variable | _row |
Undocumented |
Class Variable | _source |
Undocumented |
Instance Variable | _metadata |
Undocumented |
Instance Variable | _unique |
Undocumented |
Instance Variable | _yield |
Undocumented |
Property | _soft |
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 |
Undocumented |
Method | _fetchall |
Undocumented |
Method | _fetchiter |
Undocumented |
Method | _fetchmany |
Undocumented |
Method | _fetchone |
Undocumented |
Method | _iter |
Undocumented |
Method | _iterator |
Undocumented |
Method | _manyrow |
Undocumented |
Method | _next |
Undocumented |
Method | _onerow |
Undocumented |
Method | _only |
Undocumented |
Method | _raw |
Undocumented |
Method | _row |
Undocumented |
Method | _soft |
Undocumented |
Method | _unique |
Undocumented |
Class Variable | _is |
Undocumented |
Class Variable | _post |
Undocumented |
Class Variable | _real |
Undocumented |
Instance Variable | _generate |
Undocumented |
Inherited from InPlaceGenerative
(via _WithKeys
, ResultInternal
):
Method | _generate |
Undocumented |
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.
sqlalchemy.engine.cursor.CursorResult
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.
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.
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`
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.
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`
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.
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.
sqlalchemy.engine.cursor.CursorResult
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.
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`
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`
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`
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.
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`
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`
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.
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
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.
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`
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
_KeyIndexType
, raiseerr: bool
= True) -> Optional[ Callable[ [ Row[ Any]], Any]]
:
(source)
¶
return a callable that will retrieve the given key from a :class:`_engine.Row`.
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.
sqlalchemy.engine.cursor.CursorResult
, sqlalchemy.engine.result.ChunkedIteratorResult
, sqlalchemy.engine.result.MergedResult
Undocumented