From: Daniele Varrazzo Date: Tue, 24 Aug 2021 16:34:38 +0000 (+0200) Subject: Add cursor.statusmessage attribute X-Git-Tag: 3.0.beta1~46 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=832394cba9b3a80e94cc3b2d5d9d9bd69b1ed8cb;p=thirdparty%2Fpsycopg.git Add cursor.statusmessage attribute --- diff --git a/docs/api/cursors.rst b/docs/api/cursors.rst index 5785e37c8..f6841683a 100644 --- a/docs/api/cursors.rst +++ b/docs/api/cursors.rst @@ -172,6 +172,11 @@ The `!Cursor` class `!None` if the last operation didn't return a queryset. + .. autoattribute:: statusmessage + + This is the status tag you typically see in :program:`psql` after + a successful command, such as ``CREATE TABLE`` or ``UPDATE 42``. + .. autoattribute:: rowcount .. autoattribute:: rownumber diff --git a/psycopg/psycopg/cursor.py b/psycopg/psycopg/cursor.py index f1f9274d7..b826c7e40 100644 --- a/psycopg/psycopg/cursor.py +++ b/psycopg/psycopg/cursor.py @@ -169,6 +169,19 @@ class BaseCursor(Generic[ConnectionType, Row]): else: return None + @property + def statusmessage(self) -> Optional[str]: + """ + The command status tag from the last SQL command executed. + + `!None` if the cursor doesn't have a result available. + """ + msg = self.pgresult.command_status if self.pgresult else None + if msg: + return msg.decode("utf-8") + else: + return None + def _make_row_maker(self) -> RowMaker[Row]: raise NotImplementedError diff --git a/tests/test_cursor.py b/tests/test_cursor.py index d1875aeec..0f9173daf 100644 --- a/tests/test_cursor.py +++ b/tests/test_cursor.py @@ -42,6 +42,21 @@ def test_weakref(conn): assert w() is None +def test_statusmessage(conn): + cur = conn.cursor() + assert cur.statusmessage is None + + cur.execute("select generate_series(1, 10)") + assert cur.statusmessage == "SELECT 10" + + cur.execute("create table statusmessage ()") + assert cur.statusmessage == "CREATE TABLE" + + with pytest.raises(psycopg.ProgrammingError): + cur.execute("wat") + assert cur.statusmessage is None + + def test_execute_many_results(conn): cur = conn.cursor() assert cur.nextset() is None diff --git a/tests/test_cursor_async.py b/tests/test_cursor_async.py index bbc81bdd7..78a411f40 100644 --- a/tests/test_cursor_async.py +++ b/tests/test_cursor_async.py @@ -42,6 +42,21 @@ async def test_weakref(aconn): assert w() is None +async def test_statusmessage(aconn): + cur = aconn.cursor() + assert cur.statusmessage is None + + await cur.execute("select generate_series(1, 10)") + assert cur.statusmessage == "SELECT 10" + + await cur.execute("create table statusmessage ()") + assert cur.statusmessage == "CREATE TABLE" + + with pytest.raises(psycopg.ProgrammingError): + await cur.execute("wat") + assert cur.statusmessage is None + + async def test_execute_many_results(aconn): cur = aconn.cursor() assert cur.nextset() is None