From 8f31d7fe7c77e8a449b66f213da5407382d456e5 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Sat, 14 Sep 2024 18:04:33 -0500 Subject: [PATCH] Support executing SQL that returns rows --- src/pgwui_core/sql.py | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/pgwui_core/sql.py b/src/pgwui_core/sql.py index 0e5e870..baa9bd3 100644 --- a/src/pgwui_core/sql.py +++ b/src/pgwui_core/sql.py @@ -41,10 +41,23 @@ class SQLCommand(): ec(ex) Produces the exception to raise an instance of on failure Input: ex The exception raised by psycopg3 + fetcher(cur) Function to return the result(s) of the statement(s), + or None (the default) when the statement(s) produce + no results. + When SQL statements return results, the usual libpq + rules must be followed; all results must be retrieved + from the cursor before it can be reused and more statements + executed. + Input: + cur A psycopg3 cursor object. + result If a fetcher() is supplied, its return value is saved + in this attribute. Defaults to None. ''' stmt = attrs.field() args = attrs.field() ec = attrs.field(default=None) + fetcher = attrs.field(default=None) + result = attrs.field(default=None) def _explain_encoding_error(self, ex): '''Return a SQLEncodingError instance @@ -75,6 +88,7 @@ class SQLCommand(): Side effects: Does something in the db. Can raise a psycopg3 error + Can call the "fetcher" attribute to set the "results" attribute ''' try: cur.execute(self.stmt, self.args) @@ -91,6 +105,9 @@ class SQLCommand(): raise ex raise self.ec(ex) + if self.fetcher: + self.result = self.fetcher(cur) + @attrs.define(slots=False) class LogSQLCommand(SQLCommand): @@ -102,6 +119,17 @@ class LogSQLCommand(SQLCommand): ec(ex) Produces the exception to raise an instance of on failure Input: ex The exception raised by psycopg3 + fetcher(cur) Function to return the result(s) of the statement(s), + or None (the default) when the statement(s) produce + no results. + When SQL statements return results, the usual libpq + rules must be followed; all results must be retrieved + from the cursor before it can be reused and more statements + executed. + Input: + cur A psycopg3 cursor object. + result If a fetcher() is supplied, its return value is saved + in this attribute. Defaults to None. log_success Logs success log_failure(ex) @@ -122,6 +150,7 @@ class LogSQLCommand(SQLCommand): Side effects: Does something in the db. Can raise a psycopg3 error + Can call the "fetcher" attribute to set the "results" attribute ''' try: super().execute(cur) @@ -136,7 +165,7 @@ class LogSQLCommand(SQLCommand): class SQLData(core.DBData): ''' - SQL statements returning no data that execute in the db. + SQL statements that execute in the db. Attributes: stmts List of SQLCommand instances -- 2.34.1