]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Added `conection.execute()` method
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 8 Dec 2020 08:55:41 +0000 (09:55 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 8 Dec 2020 08:55:41 +0000 (09:55 +0100)
docs/connection.rst
psycopg3/psycopg3/connection.py
tests/test_connection.py
tests/test_connection_async.py

index b05df06a285b2aea83ce4d4482dc8a346baa6685..ba95df4f809699548c05e681196e39f601a3de42 100644 (file)
@@ -61,6 +61,15 @@ The `!Connection` class
         .. note:: You can use :ref:`with conn.cursor(): ...<usage>`
             to close the cursor automatically when the block is exited.
 
+    .. automethod:: execute(query: Query, params: Optional[Args]=None) -> Cursor
+
+        :param query: The query to execute
+        :type query: `!str`, `!bytes`, or `sql.Composable`
+        :param params: The parameters to pass to the query, if any
+        :type params: Sequence or Mapping
+
+        The cursor is what returned calling `cursor()` without parameters. See
+        :ref:`query-parameters` for all the details about executing queries.
 
     .. rubric:: Transaction management methods
 
@@ -142,6 +151,7 @@ The `!AsyncConnection` class
             automatically when the block is exited, but be careful about
             the async quirkness: see :ref:`async-with` for details.
 
+    .. automethod:: execute(query: Query, params: Optional[Args]=None) -> AsyncCursor
     .. automethod:: commit
     .. automethod:: rollback
 
index 7d8adde0c48d5cfe8debf331b84f1cf04f9cf772..d801a22384152da2c475993a6a08267b71c2e139 100644 (file)
@@ -26,7 +26,7 @@ from . import errors as e
 from . import encodings
 from .pq import TransactionStatus, ExecStatus, Format
 from .sql import Composable
-from .proto import DumpersMap, LoadersMap, PQGen, PQGenConn, RV, Query
+from .proto import DumpersMap, LoadersMap, PQGen, PQGenConn, RV, Query, Params
 from .waiting import wait, wait_async
 from .conninfo import make_conninfo
 from .generators import notifies
@@ -294,6 +294,13 @@ class Connection(BaseConnection):
 
         self._exec_command(b"begin")
 
+    def execute(
+        self, query: Query, params: Optional[Params] = None
+    ) -> "Cursor":
+        """Execute a query and return a cursor to read its results."""
+        cur = self.cursor()
+        return cur.execute(query, params)
+
     def commit(self) -> None:
         """Commit any pending transaction to the database."""
         with self.lock:
@@ -463,6 +470,12 @@ class AsyncConnection(BaseConnection):
 
         await self._exec_command(b"begin")
 
+    async def execute(
+        self, query: Query, params: Optional[Params] = None
+    ) -> "AsyncCursor":
+        cur = await self.cursor()
+        return await cur.execute(query, params)
+
     async def commit(self) -> None:
         async with self.lock:
             if self._savepoints:
index 867b3ce349b06d419a4a860254b3003f9c2a8705..af938857e0860b87e347a19a5f144dd5cb7f39fb 100644 (file)
@@ -427,3 +427,14 @@ def test_notify_handlers(conn):
 
     with pytest.raises(ValueError):
         conn.remove_notify_handler(cb1)
+
+
+def test_execute(conn):
+    cur = conn.execute("select %s, %s", [10, 20])
+    assert cur.fetchone() == (10, 20)
+
+    cur = conn.execute("select %(a)s, %(b)s", {"a": 11, "b": 21})
+    assert cur.fetchone() == (11, 21)
+
+    cur = conn.execute("select 12, 22")
+    assert cur.fetchone() == (12, 22)
index b21d771790ff07c890868d57f53e18f06fc3d72c..de1879e9c860a4fe76780f5d4d2ef799fb09079c 100644 (file)
@@ -445,3 +445,14 @@ async def test_notify_handlers(aconn):
 
     with pytest.raises(ValueError):
         aconn.remove_notify_handler(cb1)
+
+
+async def test_execute(aconn):
+    cur = await aconn.execute("select %s, %s", [10, 20])
+    assert await cur.fetchone() == (10, 20)
+
+    cur = await aconn.execute("select %(a)s, %(b)s", {"a": 11, "b": 21})
+    assert await cur.fetchone() == (11, 21)
+
+    cur = await aconn.execute("select 12, 22")
+    assert await cur.fetchone() == (12, 22)