From 8063c88dc51d713b7661713d8c7e57a928add25a Mon Sep 17 00:00:00 2001 From: Muhaddis-igis Date: Wed, 18 Nov 2026 16:54:11 +0500 Subject: [PATCH 1/2] grass.temporal: Roll back a failed transaction When a statement in execute_transaction() failed, the transaction stayed open. On SQLite, the next execute_transaction() or the commit() in close() then saved the statements that ran before the error, also at process exit through __del__(). On PostgreSQL, the connection stayed in the aborted transaction and the next execute_transaction() failed. Roll back in the finally block of execute_transaction(). close() no longer commits, so it rolls back a transaction that is still open. With psycopg2, that commit() was what saved the writes made with execute(), so execute() now commits after the statement on PostgreSQL. SQLite connections are in autocommit mode and need no commit there. Add tests that a failed transaction saves nothing, also when the caller keeps the connection or an error other than a database error stops it. --- python/grass/temporal/core.py | 14 ++- .../grass_temporal_core_db_connection_test.py | 92 ++++++++++++++++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index 861e98d2e94..34e7ba06e63 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -1438,6 +1438,9 @@ def connect(self, dbstring: str | None = None) -> None: def close(self) -> None: """Close the DBMI connection + + A transaction that is still open is rolled back, not committed. + TODO: There may be several temporal databases in a location, hence close all temporal databases that have been opened. Use a dictionary @@ -1446,7 +1449,6 @@ def close(self) -> None: if not self.connected: return - self.connection.commit() self.cursor.close() self.connection.close() self.connected = False @@ -1608,6 +1610,10 @@ def execute(self, statement, args=None): self.cursor.execute(statement, args) else: self.cursor.execute(statement) + # psycopg2 runs every statement in a transaction which it does not + # commit by itself. The SQLite connection is in autocommit mode. + if self.dbmi.__name__ == "psycopg2": + self.connection.commit() except db_errors: self.msgr.error(_("Unable to execute :\n %(sql)s") % {"sql": statement}) raise @@ -1629,7 +1635,8 @@ def execute_transaction(self, statement, mapset=None): """Execute a transactional SQL statement The BEGIN and END TRANSACTION statements will be added automatically - to the sql statement + to the sql statement. If the transaction fails, none of its statements + are saved. :param statement: The executable SQL statement or SQL script """ @@ -1652,6 +1659,9 @@ def execute_transaction(self, statement, mapset=None): ) raise finally: + # Discard what is left of a transaction that an error stopped. + # After a successful commit(), there is nothing to roll back. + self.connection.rollback() if connected: self.close() diff --git a/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py b/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py index 7121b804efc..1ce36f7b781 100644 --- a/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py +++ b/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py @@ -1,14 +1,18 @@ # SPDX-License-Identifier: GPL-2.0-or-later -"""Tests for closing temporal database connections in grass.temporal.core""" +"""Tests for connections and transactions of DBConnection in grass.temporal.core""" import os import sqlite3 +from contextlib import closing import pytest import grass.script as gs import grass.temporal as tgis +FAILING_TRANSACTION = "INSERT INTO t VALUES (1); INSERT INTO no_such_table VALUES (2)" +OTHER_ERROR = "not a database error" + @pytest.fixture def temporal_session(tmp_path, monkeypatch): @@ -25,6 +29,15 @@ def temporal_session(tmp_path, monkeypatch): yield +@pytest.fixture +def table_path(tmp_path): + """Path of an SQLite database with an empty table t""" + path = tmp_path / "transactions.db" + with closing(sqlite3.connect(path)) as connection: + connection.execute("CREATE TABLE t (x INTEGER)") + return path + + def connect_to_temporal_database(): """Return a connected DBConnection to the database of the current mapset""" db = tgis.DBConnection(backend="sqlite", dbstring=tgis.get_tgis_database_string()) @@ -32,6 +45,30 @@ def connect_to_temporal_database(): return db +def connect_to(path): + """Return a connected DBConnection to the SQLite database at path""" + db = tgis.DBConnection(backend="sqlite", dbstring=str(path)) + db.connect() + return db + + +def saved_rows(path): + """Return the values in table t, read with a new connection""" + with closing(sqlite3.connect(path)) as connection: + return [row[0] for row in connection.execute("SELECT x FROM t ORDER BY x")] + + +class InterruptingCursor: + """Cursor which starts the transaction, then fails with a non-database error""" + + def __init__(self, cursor): + self.cursor = cursor + + def executescript(self, script): + self.cursor.executescript("BEGIN TRANSACTION; INSERT INTO t VALUES (1);") + raise RuntimeError(OTHER_ERROR) + + @pytest.mark.usefixtures("temporal_session") def test_close_closes_the_sqlite_connection(): """After close(), the SQLite connection cannot be used anymore""" @@ -49,3 +86,56 @@ def test_second_close_does_nothing(): db.close() db.close() assert not db.is_connected() + + +@pytest.mark.usefixtures("temporal_session") +def test_close_rolls_back_an_open_transaction(table_path): + """close() does not commit a transaction that is still open""" + db = connect_to(table_path) + db.execute("BEGIN TRANSACTION") + db.execute("INSERT INTO t VALUES (1)") + db.close() + assert saved_rows(table_path) == [] + + +@pytest.mark.usefixtures("temporal_session") +def test_successful_transaction_is_saved(table_path): + """A transaction without errors is saved despite the rollback() in finally""" + db = tgis.DBConnection(backend="sqlite", dbstring=str(table_path)) + db.execute_transaction("INSERT INTO t VALUES (1); INSERT INTO t VALUES (2)") + assert saved_rows(table_path) == [1, 2] + + +@pytest.mark.usefixtures("temporal_session") +def test_failed_transaction_saves_nothing(table_path): + """No statement of a failed transaction is saved""" + db = tgis.DBConnection(backend="sqlite", dbstring=str(table_path)) + with pytest.raises(sqlite3.OperationalError, match="no such table"): + db.execute_transaction(FAILING_TRANSACTION) + assert saved_rows(table_path) == [] + + +@pytest.mark.usefixtures("temporal_session") +def test_failed_transaction_is_not_saved_by_the_next_one(table_path): + """A failed transaction leaves nothing open on the caller's connection""" + db = connect_to(table_path) + with pytest.raises(sqlite3.OperationalError, match="no such table"): + db.execute_transaction(FAILING_TRANSACTION) + assert not db.connection.in_transaction + db.execute_transaction("INSERT INTO t VALUES (3)") + db.close() + assert saved_rows(table_path) == [3] + + +@pytest.mark.usefixtures("temporal_session") +def test_transaction_stopped_by_other_error_is_not_saved(table_path): + """A transaction which a non-database error stopped is not saved later""" + db = connect_to(table_path) + cursor = db.cursor + db.cursor = InterruptingCursor(cursor) + with pytest.raises(RuntimeError, match=OTHER_ERROR): + db.execute_transaction("INSERT INTO t VALUES (1)") + db.cursor = cursor + db.execute_transaction("INSERT INTO t VALUES (3)") + db.close() + assert saved_rows(table_path) == [3] From 5364aaf80e860ba48e7129dd9ab1000bad0b30f0 Mon Sep 17 00:00:00 2001 From: Muhaddis-igis Date: Fri, 4 Dec 2026 11:05:07 +0500 Subject: [PATCH 2/2] grass.temporal: Count the connection as closed when close() fails If closing the cursor or the connection raised, close() stopped before setting connected to False, so the object still counted as connected and a later close() tried again on the broken connection. Set connected to False first, and close the connection even if closing the cursor raises. The error is still raised to the caller. Add a test with an SQLite connection that was closed underneath. --- python/grass/temporal/core.py | 9 +++++++-- .../tests/grass_temporal_core_db_connection_test.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index 34e7ba06e63..28ae5eb0bb0 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -1449,9 +1449,14 @@ def close(self) -> None: if not self.connected: return - self.cursor.close() - self.connection.close() + # Count the connection as closed even if closing it fails, for + # example when it was already closed, so that a later close() + # does not try again. self.connected = False + try: + self.cursor.close() + finally: + self.connection.close() def mogrify_sql_statement(self, content): """Return the SQL statement and arguments as executable SQL string diff --git a/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py b/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py index 1ce36f7b781..ec227464825 100644 --- a/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py +++ b/python/grass/temporal/tests/grass_temporal_core_db_connection_test.py @@ -88,6 +88,17 @@ def test_second_close_does_nothing(): assert not db.is_connected() +@pytest.mark.usefixtures("temporal_session") +def test_close_counts_a_broken_connection_as_closed(table_path): + """close() leaves the object disconnected even if closing fails""" + db = connect_to(table_path) + db.connection.close() + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + db.close() + assert not db.is_connected() + db.close() + + @pytest.mark.usefixtures("temporal_session") def test_close_rolls_back_an_open_transaction(table_path): """close() does not commit a transaction that is still open"""