Coverage for rdflib_ocdm / counter_handler / sqlite_counter_handler.py: 89%
46 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-30 21:23 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-30 21:23 +0000
1#!/usr/bin/python
3# SPDX-FileCopyrightText: 2023-2026 Arcangelo Massari <arcangelo.massari@unibo.it>
4#
5# SPDX-License-Identifier: ISC
7import sqlite3
8import urllib.parse
10from rdflib_ocdm.counter_handler.counter_handler import CounterHandler
13class SqliteCounterHandler(CounterHandler):
14 """A concrete implementation of the ``CounterHandler`` interface
15 that persistently stores the counter values within a SQLite
16 database."""
18 def __init__(self, database: str) -> None:
19 """
20 Constructor of the ``SqliteCounterHandler`` class.
22 :param database: The name of the database
23 :type info_dir: str
24 """
25 sqlite3.threadsafety = 3
26 self.con = sqlite3.connect(database, check_same_thread=False)
27 self.cur = self.con.cursor()
28 self.cur.execute("""CREATE TABLE IF NOT EXISTS info(
29 entity TEXT PRIMARY KEY,
30 count INTEGER)""")
32 def set_counter(self, new_value: int, entity_name: str) -> None:
33 """
34 It allows to set the counter value of provenance
35 entities.
37 :param new_value: The new counter value to be set
38 :type new_value: int
39 :param entity_name: The entity name
40 :type entity_name: str
41 :raises ValueError: if ``new_value`` is a negative integer.
42 :return: None
43 """
44 entity_name = urllib.parse.quote(str(entity_name))
45 if new_value < 0:
46 raise ValueError("new_value must be a non negative integer!")
47 self.cur.execute(
48 "INSERT OR REPLACE INTO info (entity, count)"
49 f" VALUES ('{entity_name}', {new_value})"
50 )
51 self.con.commit()
53 def read_counter(self, entity_name: str) -> int:
54 """
55 It allows to read the counter value of provenance entities.
57 :param entity_name: The entity name
58 :type entity_name: str
59 :return: The requested counter value.
60 """
61 entity_name = urllib.parse.quote(str(entity_name))
62 result = self.cur.execute(
63 f"SELECT count FROM info WHERE entity='{entity_name}'"
64 )
65 rows = result.fetchall()
66 if len(rows) == 1:
67 return rows[0][0]
68 elif len(rows) == 0:
69 return 0
70 else:
71 raise Exception(
72 "There is more than one counter for this entity. The database is broken"
73 )
75 def increment_counter(self, entity_name: str) -> int:
76 """
77 It allows to increment the counter value of graph and
78 provenance entities by one unit.
80 :param entity_name: The entity name
81 :type entity_name: str
82 :return: The newly-updated (already incremented) counter value.
83 """
84 cur_count = self.read_counter(entity_name)
85 count = cur_count + 1
86 self.set_counter(count, entity_name)
87 return count
89 def close(self) -> None:
90 """
91 Closes the database connection.
93 :return: None
94 """
95 try:
96 if hasattr(self, "cur") and self.cur: 96 ↛ 100line 96 didn't jump to line 100 because the condition on line 96 was always true
97 self.cur.close()
98 except (sqlite3.ProgrammingError, Exception):
99 pass
100 try:
101 if hasattr(self, "con") and self.con: 101 ↛ exitline 101 didn't return from function 'close' because the condition on line 101 was always true
102 self.con.close()
103 except (sqlite3.ProgrammingError, Exception):
104 pass
106 def __del__(self) -> None:
107 """
108 Destructor that ensures the database connection is closed.
110 :return: None
111 """
112 self.close()
114 def __enter__(self):
115 """
116 Context manager entry point.
118 :return: self
119 """
120 return self
122 def __exit__(self, exc_type, exc_val, exc_tb) -> None: # noqa: ARG002
123 """
124 Context manager exit point that ensures the database connection is closed.
126 :param exc_type: Exception type
127 :param exc_val: Exception value
128 :param exc_tb: Exception traceback
129 :return: None
130 """
131 self.close()