Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions python/grass/temporal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1446,10 +1449,14 @@ def close(self) -> None:
if not self.connected:
return

self.connection.commit()
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
Expand Down Expand Up @@ -1608,6 +1615,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
Expand All @@ -1629,7 +1640,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
"""
Expand All @@ -1652,6 +1664,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()

Expand Down
103 changes: 102 additions & 1 deletion python/grass/temporal/tests/grass_temporal_core_db_connection_test.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -25,13 +29,46 @@ 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())
db.connect()
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"""
Expand All @@ -49,3 +86,67 @@ def test_second_close_does_nothing():
db.close()
db.close()
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"""
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]
Loading