class documentation

class CursorResult(Result[_T]): (source)

View In Hierarchy

A Result that is representing state from a DBAPI cursor. .. versionchanged:: 1.4 The :class:`.CursorResult`` class replaces the previous :class:`.ResultProxy` interface. This classes are based on the :class:`.Result` calling API which provides an updated usage model and calling facade for SQLAlchemy Core and SQLAlchemy ORM. Returns database rows via the :class:`.Row` class, which provides additional API features and behaviors on top of the raw data returned by the DBAPI. Through the use of filters such as the :meth:`.Result.scalars` method, other kinds of objects may also be returned. .. seealso:: :ref:`tutorial_selecting_data` - introductory material for accessing :class:`_engine.CursorResult` and :class:`.Row` objects.

Method __init__ Undocumented
Method close Close this :class:`_engine.CursorResult`.
Method last_inserted_params Return the collection of inserted parameters from this execution.
Method last_updated_params Return the collection of updated parameters from this execution.
Method lastrow_has_defaults Return ``lastrow_has_defaults()`` from the underlying :class:`.ExecutionContext`.
Method merge Merge this :class:`_engine.Result` with other compatible result objects.
Method postfetch_cols Return ``postfetch_cols()`` from the underlying :class:`.ExecutionContext`.
Method prefetch_cols Return ``prefetch_cols()`` from the underlying :class:`.ExecutionContext`.
Method splice_horizontally Return a new :class:`.CursorResult` that "horizontally splices" together the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`.
Method splice_vertically Return a new :class:`.CursorResult` that "vertically splices", i.e. "extends", the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`.
Method supports_sane_multi_rowcount Return ``supports_sane_multi_rowcount`` from the dialect.
Method supports_sane_rowcount Return ``supports_sane_rowcount`` from the dialect.
Method yield_per Configure the row-fetching strategy to fetch ``num`` rows at a time.
Class Variable __slots__ Undocumented
Instance Variable closed return ``True`` if this :class:`_engine.Result` reports .closed
Instance Variable connection Undocumented
Instance Variable context Undocumented
Instance Variable cursor Undocumented
Instance Variable cursor_strategy Undocumented
Instance Variable dialect Undocumented
Property inserted_primary_key Return the primary key for the row just inserted.
Property inserted_primary_key_rows Return the value of :attr:`_engine.CursorResult.inserted_primary_key` as a row contained within a list; some dialects may support a multiple row form as well.
Property is_insert True if this :class:`_engine.CursorResult` is the result of a executing an expression language compiled :func:`_expression.insert` construct.
Property lastrowid Return the 'lastrowid' accessor on the DBAPI cursor.
Property returned_defaults Return the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature.
Property returned_defaults_rows Return a list of rows each containing the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature.
Property returns_rows True if this :class:`_engine.CursorResult` returns zero or more rows.
Property rowcount Return the 'rowcount' for this result.
Method _fetchall_impl Undocumented
Method _fetchiter_impl Undocumented
Method _fetchmany_impl Undocumented
Method _fetchone_impl Undocumented
Method _init_metadata Undocumented
Method _raw_row_iterator Return a safe iterator that yields raw row data.
Method _rewind rewind this result back to the given rowset.
Method _soft_close Soft close this :class:`_engine.CursorResult`.
Class Variable _is_cursor Undocumented
Instance Variable _echo Undocumented
Instance Variable _metadata Undocumented
Instance Variable _row_logging_fn Undocumented
Instance Variable _soft_closed Undocumented
Instance Variable _yield_per Undocumented

Inherited from Result:

Method __enter__ Undocumented
Method __exit__ Undocumented
Method __iter__ Undocumented
Method __next__ Undocumented
Method all Return all rows in a list.
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 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`.
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 _tuple_getter return a callable that will retrieve the given keys from a :class:`_engine.Row`.
Class Variable _attributes Undocumented
Class Variable _source_supports_scalars Undocumented
Instance Variable _unique_filter_state Undocumented

Inherited from _WithKeys (via Result):

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

Inherited from ResultInternal (via Result, _WithKeys):

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 Result, _WithKeys, ResultInternal):

Method _generate Undocumented
def __init__(self, context: DefaultExecutionContext, cursor_strategy: ResultFetchStrategy, cursor_description: Optional[_DBAPICursorDescription]): (source)
def close(self) -> Any: (source)

Close this :class:`_engine.CursorResult`. This closes out the underlying DBAPI cursor corresponding to the statement execution, if one is still present. Note that the DBAPI cursor is automatically released when the :class:`_engine.CursorResult` exhausts all available rows. :meth:`_engine.CursorResult.close` is generally an optional method except in the case when discarding a :class:`_engine.CursorResult` that still has additional rows pending for fetch. After this method is called, it is no longer valid to call upon the fetch methods, which will raise a :class:`.ResourceClosedError` on subsequent use. .. seealso:: :ref:`connections_toplevel`

def last_inserted_params(self): (source)

Return the collection of inserted parameters from this execution. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() construct.

def last_updated_params(self): (source)

Return the collection of updated parameters from this execution. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an update() construct.

def lastrow_has_defaults(self): (source)

Return ``lastrow_has_defaults()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details.

def merge(self, *others: Result[Any]) -> MergedResult[Any]: (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 postfetch_cols(self): (source)

Return ``postfetch_cols()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() or update() construct.

def prefetch_cols(self): (source)

Return ``prefetch_cols()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() or update() construct.

def splice_horizontally(self, other): (source)

Return a new :class:`.CursorResult` that "horizontally splices" together the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is not intended for general use. "horizontally splices" means that for each row in the first and second result sets, a new row that concatenates the two rows together is produced, which then becomes the new row. The incoming :class:`.CursorResult` must have the identical number of rows. It is typically expected that the two result sets come from the same sort order as well, as the result rows are spliced together based on their position in the result. The expected use case here is so that multiple INSERT..RETURNING statements against different tables can produce a single result that looks like a JOIN of those two tables. E.g.:: r1 = connection.execute( users.insert().returning(users.c.user_name, users.c.user_id), user_values ) r2 = connection.execute( addresses.insert().returning( addresses.c.address_id, addresses.c.address, addresses.c.user_id, ), address_values ) rows = r1.splice_horizontally(r2).all() assert ( rows == [ ("john", 1, 1, "foo@bar.com", 1), ("jack", 2, 2, "bar@bat.com", 2), ] ) .. versionadded:: 2.0 .. seealso:: :meth:`.CursorResult.splice_vertically`

def splice_vertically(self, other): (source)

Return a new :class:`.CursorResult` that "vertically splices", i.e. "extends", the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is not intended for general use. "vertically splices" means the rows of the given result are appended to the rows of this cursor result. The incoming :class:`.CursorResult` must have rows that represent the identical list of columns in the identical order as they are in this :class:`.CursorResult`. .. versionadded:: 2.0 .. seealso:: :meth:`.CursorResult.splice_horizontally`

def supports_sane_multi_rowcount(self): (source)

Return ``supports_sane_multi_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background.

def supports_sane_rowcount(self): (source)

Return ``supports_sane_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background.

@_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

connection = (source)

Undocumented

Undocumented

Undocumented

cursor_strategy = (source)

Undocumented

Undocumented

@property
inserted_primary_key = (source)

Return the primary key for the row just inserted. The return value is a :class:`_result.Row` object representing a named tuple of primary key values in the order in which the primary key columns are configured in the source :class:`_schema.Table`. .. versionchanged:: 1.4.8 - the :attr:`_engine.CursorResult.inserted_primary_key` value is now a named tuple via the :class:`_result.Row` class, rather than a plain tuple. This accessor only applies to single row :func:`_expression.insert` constructs which did not explicitly specify :meth:`_expression.Insert.returning`. Support for multirow inserts, while not yet available for most backends, would be accessed using the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor. Note that primary key columns which specify a server_default clause, or otherwise do not qualify as "autoincrement" columns (see the notes at :class:`_schema.Column`), and were generated using the database-side default, will appear in this list as ``None`` unless the backend supports "returning" and the insert statement executed with the "implicit returning" enabled. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() construct.

@property
inserted_primary_key_rows = (source)

Return the value of :attr:`_engine.CursorResult.inserted_primary_key` as a row contained within a list; some dialects may support a multiple row form as well. .. note:: As indicated below, in current SQLAlchemy versions this accessor is only useful beyond what's already supplied by :attr:`_engine.CursorResult.inserted_primary_key` when using the :ref:`postgresql_psycopg2` dialect. Future versions hope to generalize this feature to more dialects. This accessor is added to support dialects that offer the feature that is currently implemented by the :ref:`psycopg2_executemany_mode` feature, currently **only the psycopg2 dialect**, which provides for many rows to be INSERTed at once while still retaining the behavior of being able to return server-generated primary key values. * **When using the psycopg2 dialect, or other dialects that may support "fast executemany" style inserts in upcoming releases** : When invoking an INSERT statement while passing a list of rows as the second argument to :meth:`_engine.Connection.execute`, this accessor will then provide a list of rows, where each row contains the primary key value for each row that was INSERTed. * **When using all other dialects / backends that don't yet support this feature**: This accessor is only useful for **single row INSERT statements**, and returns the same information as that of the :attr:`_engine.CursorResult.inserted_primary_key` within a single-element list. When an INSERT statement is executed in conjunction with a list of rows to be INSERTed, the list will contain one row per row inserted in the statement, however it will contain ``None`` for any server-generated values. Future releases of SQLAlchemy will further generalize the "fast execution helper" feature of psycopg2 to suit other dialects, thus allowing this accessor to be of more general use. .. versionadded:: 1.4 .. seealso:: :attr:`_engine.CursorResult.inserted_primary_key`

True if this :class:`_engine.CursorResult` is the result of a executing an expression language compiled :func:`_expression.insert` construct. When True, this implies that the :attr:`inserted_primary_key` attribute is accessible, assuming the statement did not include a user defined "returning" construct.

Return the 'lastrowid' accessor on the DBAPI cursor. This is a DBAPI specific method and is only functional for those backends which support it, for statements where it is appropriate. It's behavior is not consistent across backends. Usage of this method is normally unnecessary when using insert() expression constructs; the :attr:`~CursorResult.inserted_primary_key` attribute provides a tuple of primary key values for a newly inserted row, regardless of database backend.

@property
returned_defaults = (source)

Return the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature. The value is an instance of :class:`.Row`, or ``None`` if :meth:`.ValuesBase.return_defaults` was not used or if the backend does not support RETURNING. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ValuesBase.return_defaults`

@property
returned_defaults_rows = (source)

Return a list of rows each containing the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature. The return value is a list of :class:`.Row` objects. .. versionadded:: 1.4

@property
returns_rows = (source)

True if this :class:`_engine.CursorResult` returns zero or more rows. I.e. if it is legal to call the methods :meth:`_engine.CursorResult.fetchone`, :meth:`_engine.CursorResult.fetchmany` :meth:`_engine.CursorResult.fetchall`. Overall, the value of :attr:`_engine.CursorResult.returns_rows` should always be synonymous with whether or not the DBAPI cursor had a ``.description`` attribute, indicating the presence of result columns, noting that a cursor that returns zero rows still has a ``.description`` if a row-returning statement was emitted. This attribute should be True for all results that are against SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE that use RETURNING. For INSERT/UPDATE/DELETE statements that were not using RETURNING, the value will usually be False, however there are some dialect-specific exceptions to this, such as when using the MSSQL / pyodbc dialect a SELECT is emitted inline in order to retrieve an inserted primary key value.

@util.memoized_property
rowcount: int = (source)

Return the 'rowcount' for this result. The 'rowcount' reports the number of rows *matched* by the WHERE criterion of an UPDATE or DELETE statement. .. note:: Notes regarding :attr:`_engine.CursorResult.rowcount`: * This attribute returns the number of rows *matched*, which is not necessarily the same as the number of rows that were actually *modified* - an UPDATE statement, for example, may have no net change on a given row if the SET values given are the same as those present in the row already. Such a row would be matched but not modified. On backends that feature both styles, such as MySQL, rowcount is configured by default to return the match count in all cases. * :attr:`_engine.CursorResult.rowcount` is *only* useful in conjunction with an UPDATE or DELETE statement. Contrary to what the Python DBAPI says, it does *not* return the number of rows available from the results of a SELECT statement as DBAPIs cannot support this functionality when rows are unbuffered. * :attr:`_engine.CursorResult.rowcount` may not be fully implemented by all dialects. In particular, most DBAPIs do not support an aggregate rowcount result from an executemany call. The :meth:`_engine.CursorResult.supports_sane_rowcount` and :meth:`_engine.CursorResult.supports_sane_multi_rowcount` methods will report from the dialect if each usage is known to be supported. * Statements that use RETURNING may not return a correct rowcount. .. seealso:: :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`

def _fetchall_impl(self): (source)
def _fetchiter_impl(self): (source)
def _fetchmany_impl(self, size=None): (source)
def _fetchone_impl(self, hard_close=False): (source)
def _init_metadata(self, context, cursor_description): (source)

Undocumented

def _raw_row_iterator(self): (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 _rewind(self, rows): (source)

rewind this result back to the given rowset. this is used internally for the case where an :class:`.Insert` construct combines the use of :meth:`.Insert.return_defaults` along with the "supplemental columns" feature.

def _soft_close(self, hard=False): (source)

Soft close this :class:`_engine.CursorResult`. This releases all DBAPI cursor resources, but leaves the CursorResult "open" from a semantic perspective, meaning the fetchXXX() methods will continue to return empty results. This method is called automatically when: * all result rows are exhausted using the fetchXXX() methods. * cursor.description is None. This method is **not public**, but is documented in order to clarify the "autoclose" process used. .. versionadded:: 1.0.0 .. seealso:: :meth:`_engine.CursorResult.close`

Undocumented