2"""Implementations to make access to SQLite databases a little more convenient.
5 Abstract class with which DB applications can be implemented.
7:py:obj:`SQLiteProperties`:
8 Class to manage properties stored in a database.
13from __future__
import annotations
21from searx
import logger
23logger = logger.getChild(
'sqlitedb')
27 """Abstract base class for implementing convenient DB access in SQLite
28 applications. In the constructor, a :py:obj:`SQLiteProperties` instance is
29 already aggregated under ``self.properties``."""
31 DDL_CREATE_TABLES: dict[str, str] = {}
34 """As soon as changes are made to the DB schema, the version number must be
35 increased. Changes to the version number require the DB to be recreated (or
36 migrated / if an migration path exists and is implemented)."""
38 SQLITE_THREADING_MODE = {
41 3:
"serialized"}[sqlite3.threadsafety]
42 """Threading mode of the SQLite library. Depends on the options used at
43 compile time and is different for different distributions and architectures.
45 Possible values are 0:``single-thread``, 1:``multi-thread``,
46 3:``serialized`` (see :py:obj:`sqlite3.threadsafety`). Pre- Python 3.11
47 this value was hard coded to 1.
49 Depending on this value, optimizations are made, e.g. in “serialized” mode
50 it is not necessary to create a separate DB connector for each thread.
53 SQLITE_JOURNAL_MODE =
"WAL"
54 SQLITE_CONNECT_ARGS = {
57 "check_same_thread": bool(SQLITE_THREADING_MODE !=
"serialized"),
58 "cached_statements": 0,
62 """Connection arguments (:py:obj:`sqlite3.connect`)
64 ``check_same_thread``:
65 Is disabled by default when :py:obj:`SQLITE_THREADING_MODE` is
66 ``serialized``. The check is more of a hindrance in this case because it
67 would prevent a DB connector from being used in multiple threads.
70 Is disabled by default. Note: autocommit option has been added in Python
73 ``cached_statements``:
74 Is set to ``0`` by default. Note: Python 3.12+ fetch result are not
75 consistent in multi-threading application and causing an API misuse error.
77 The multithreading use in SQLiteAppl is intended and supported if
78 threadsafety is set to 3 (aka "serialized"). CPython supports “serialized”
79 from version 3.12 on, but unfortunately only with errors:
81 - https://github.com/python/cpython/issues/118172
82 - https://github.com/python/cpython/issues/123873
84 The workaround for SQLite3 multithreading cache inconsistency ist to set
85 option ``cached_statements`` to ``0`` by default.
102 f
"SQLite library is compiled with {self.SQLITE_THREADING_MODE} mode,"
103 " read https://docs.python.org/3/library/sqlite3.html#sqlite3.threadsafety"
105 if threading.active_count() > 1:
110 if sqlite3.sqlite_version_info <= (3, 35):
113 "SQLite runtime library version %s is not supported (require >= 3.35)", sqlite3.sqlite_version
117 """Creates a new DB connection (:py:obj:`SQLITE_CONNECT_ARGS`). If not
118 already done, the DB schema is set up
120 if sys.version_info < (3, 12):
127 conn.execute(f
"PRAGMA journal_mode={self.SQLITE_JOURNAL_MODE}")
132 """Create user-defined_ SQL functions.
134 ``REGEXP(<pattern>, <field>)`` : 0 | 1
135 `re.search`_ returns (int) 1 for a match and 0 for none match of
136 ``<pattern>`` in ``<field>``.
140 SELECT '12' AS field WHERE REGEXP('^[0-9][0-9]$', field)
143 SELECT REGEXP('[0-9][0-9]', 'X12Y')
145 SELECT REGEXP('[0-9][0-9]', 'X1Y')
148 .. _user-defined: https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
149 .. _deterministic: https://sqlite.org/deterministic.html
150 .. _re.search: https://docs.python.org/3/library/re.html#re.search
153 conn.create_function(
'regexp', 2,
lambda x, y: 1
if re.search(x, y)
else 0, deterministic=
True)
156 def DB(self) -> sqlite3.Connection:
157 """Provides a DB connection. The connection is a *singleton* and
158 therefore well suited for read access. If
159 :py:obj:`SQLITE_THREADING_MODE` is ``serialized`` only one DB connection
160 is created for all threads.
164 For dedicated `transaction control`_, it is recommended to create a
165 new connection (:py:obj:`SQLiteAppl.connect`).
167 .. _transaction control:
168 https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions
194 """Initializes the DB schema and properties, is only executed once even
195 if called several times."""
201 logger.debug(
"init DB: %s", self.
db_url)
210 raise sqlite3.DatabaseError(
"Expected DB schema v%s, DB schema is v%s" % (self.
DB_SCHEMA, ver))
211 logger.debug(
"DB_SCHEMA = %s", ver)
215 logger.debug(
"create schema ..")
219 self.
properties.set(f
"Table {table_name} created", table_name)
225 """Simple class to manage properties of a DB application in the DB. The
226 object has its own DB connection and transaction area.
230 CREATE TABLE IF NOT EXISTS properties (
233 m_time INTEGER DEFAULT (strftime('%s', 'now')),
238 SQLITE_JOURNAL_MODE =
"WAL"
240 DDL_PROPERTIES =
"""\
241CREATE TABLE IF NOT EXISTS properties (
244 m_time INTEGER DEFAULT (strftime('%s', 'now')), -- last modified (unix epoch) time in sec.
245 PRIMARY KEY (name))"""
247 """Table to store properties of the DB application"""
249 SQL_GET =
"SELECT value FROM properties WHERE name = ?"
250 SQL_M_TIME =
"SELECT m_time FROM properties WHERE name = ?"
252 "INSERT INTO properties (name, value) VALUES (?, ?)"
253 " ON CONFLICT(name) DO UPDATE"
254 " SET value=excluded.value, m_time=strftime('%s', 'now')"
257 "SELECT name FROM sqlite_master"
258 " WHERE type='table' AND name='properties'"
260 SQLITE_CONNECT_ARGS = dict(SQLiteAppl.SQLITE_CONNECT_ARGS)
261 SQLITE_CONNECT_ARGS[
"autocommit"] =
True
271 """Initializes DB schema of the properties in the DB."""
276 logger.debug(
"init properties of DB: %s", self.
db_urldb_url)
277 with self.
DB as conn:
279 if res.fetchone()
is None:
283 """Returns the value of the property ``name`` or ``default`` if property
286 res = self.
DB.execute(self.
SQL_GET, (name,)).fetchone()
291 def set(self, name, value):
292 """Set ``value`` of property ``name`` in DB. If property already
293 exists, update the ``m_time`` (and the value)."""
295 self.
DB.execute(self.
SQL_SET, (name, value))
297 if sys.version_info <= (3, 12):
302 def row(self, name, default=None):
303 """Returns the DB row of property ``name`` or ``default`` if property
306 cur = self.
DB.cursor()
307 cur.execute(
"SELECT * FROM properties WHERE name = ?", (name,))
311 col_names = [column[0]
for column
in cur.description]
312 return dict(zip(col_names, res))
314 def m_time(self, name, default: int = 0) -> int:
315 """Last modification time of this property."""
316 res = self.
DB.execute(self.
SQL_M_TIME, (name,)).fetchone()
sqlite3.Connection connect(self)
register_functions(self, conn)
create_schema(self, conn)
dict SQLITE_THREADING_MODE
sqlite3.Connection DB(self)
__call__(self, name, default=None)
int m_time(self, name, int default=0)
row(self, name, default=None)
create_schema(self, conn)
__init__(self, str db_url)