From 4127482cc5edff8967b991bfc9398c47ce6e8a83 Mon Sep 17 00:00:00 2001 From: Miguel Grinberg Date: Mon, 13 Sep 2021 14:41:13 -0400 Subject: Add scalars method to connection and session classes Added new methods :meth:`_orm.Session.scalars`, :meth:`_engine.Connection.scalars`, :meth:`_asyncio.AsyncSession.scalars` and :meth:`_asyncio.AsyncSession.stream_scalars`, which provide a short cut to the use case of receiving a row-oriented :class:`_result.Result` object and converting it to a :class:`_result.ScalarResult` object via the :meth:`_engine.Result.scalars` method, to return a list of values rather than a list of rows. The new methods are analogous to the long existing :meth:`_orm.Session.scalar` and :meth:`_engine.Connection.scalar` methods used to return a single value from the first row only. Pull request courtesy Miguel Grinberg. Fixes: #6990 Closes: #6991 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/6991 Pull-request-sha: b3e0bb3042c55b0cc5af6a25cb3f31b929f88a47 Change-Id: Ia445775e24ca964b0162c2c8e5ca67dd1e39199f --- lib/sqlalchemy/engine/base.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'lib/sqlalchemy/engine') diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index a316f904f..25ced0343 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -1157,10 +1157,28 @@ class Connection(Connectable): """Executes and returns the first column of the first row. The underlying result/cursor is closed after execution. + """ return self.execute(object_, *multiparams, **params).scalar() + def scalars(self, object_, *multiparams, **params): + """Executes and returns a scalar result set, which yields scalar values + from the first column of each row. + + This method is equivalent to calling :meth:`_engine.Connection.execute` + to receive a :class:`_result.Result` object, then invoking the + :meth:`_result.Result.scalars` method to produce a + :class:`_result.ScalarResult` instance. + + :return: a :class:`_result.ScalarResult` + + .. versionadded:: 1.4.24 + + """ + + return self.execute(object_, *multiparams, **params).scalars() + def execute(self, statement, *multiparams, **params): r"""Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. -- cgit v1.2.1