.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
sqlitedb.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Implementations to make access to SQLite databases a little more convenient.
3
4:py:obj:`SQLiteAppl`
5 Abstract class with which DB applications can be implemented.
6
7:py:obj:`SQLiteProperties`:
8 Class to manage properties stored in a database.
9
10----
11
12"""
13from __future__ import annotations
14
15import sys
16import re
17import sqlite3
18import threading
19import abc
20
21from searx import logger
22
23logger = logger.getChild('sqlitedb')
24
25
26class SQLiteAppl(abc.ABC):
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``."""
30
31 DDL_CREATE_TABLES: dict[str, str] = {}
32
33 DB_SCHEMA: int = 1
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)."""
37
38 SQLITE_THREADING_MODE = {
39 0: "single-thread",
40 1: "multi-thread",
41 3: "serialized"}[sqlite3.threadsafety] # fmt:skip
42 """Threading mode of the SQLite library. Depends on the options used at
43 compile time and is different for different distributions and architectures.
44
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.
48
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.
51 """
52
53 SQLITE_JOURNAL_MODE = "WAL"
54 SQLITE_CONNECT_ARGS = {
55 # "timeout": 5.0,
56 # "detect_types": 0,
57 "check_same_thread": bool(SQLITE_THREADING_MODE != "serialized"),
58 "cached_statements": 0, # https://github.com/python/cpython/issues/118172
59 # "uri": False,
60 "autocommit": False,
61 } # fmt:skip
62 """Connection arguments (:py:obj:`sqlite3.connect`)
63
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.
68
69 ``autocommit``:
70 Is disabled by default. Note: autocommit option has been added in Python
71 3.12.
72
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.
76
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:
80
81 - https://github.com/python/cpython/issues/118172
82 - https://github.com/python/cpython/issues/123873
83
84 The workaround for SQLite3 multithreading cache inconsistency ist to set
85 option ``cached_statements`` to ``0`` by default.
86 """
87
88 def __init__(self, db_url):
89
90 self.db_url = db_url
92 self.thread_local = threading.local()
93 self._init_done = False
94 self._compatibility()
95
96 def _compatibility(self):
97
98 if self.SQLITE_THREADING_MODE == "serialized":
99 self._DB = None
100 else:
101 msg = (
102 f"SQLite library is compiled with {self.SQLITE_THREADING_MODE} mode,"
103 " read https://docs.python.org/3/library/sqlite3.html#sqlite3.threadsafety"
104 )
105 if threading.active_count() > 1:
106 logger.error(msg)
107 else:
108 logger.warning(msg)
109
110 if sqlite3.sqlite_version_info <= (3, 35):
111 # See "Generalize UPSERT:" in https://sqlite.org/releaselog/3_35_0.html
112 logger.critical(
113 "SQLite runtime library version %s is not supported (require >= 3.35)", sqlite3.sqlite_version
114 )
115
116 def connect(self) -> sqlite3.Connection:
117 """Creates a new DB connection (:py:obj:`SQLITE_CONNECT_ARGS`). If not
118 already done, the DB schema is set up
119 """
120 if sys.version_info < (3, 12):
121 # Prior Python 3.12 there is no "autocommit" option
122 self.SQLITE_CONNECT_ARGS.pop("autocommit", None)
123
124 self.init()
125 logger.debug("%s: connect to DB: %s // %s", self.__class__.__name__, self.db_url, self.SQLITE_CONNECT_ARGS)
126 conn = sqlite3.Connection(self.db_url, **self.SQLITE_CONNECT_ARGS) # type: ignore
127 conn.execute(f"PRAGMA journal_mode={self.SQLITE_JOURNAL_MODE}")
128 self.register_functions(conn)
129 return conn
130
131 def register_functions(self, conn):
132 """Create user-defined_ SQL functions.
133
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>``.
137
138 .. code:: sql
139
140 SELECT '12' AS field WHERE REGEXP('^[0-9][0-9]$', field)
141 -- 12
142
143 SELECT REGEXP('[0-9][0-9]', 'X12Y')
144 -- 1
145 SELECT REGEXP('[0-9][0-9]', 'X1Y')
146 -- 0
147
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
151 """
152
153 conn.create_function('regexp', 2, lambda x, y: 1 if re.search(x, y) else 0, deterministic=True)
154
155 @property
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.
161
162 .. note::
163
164 For dedicated `transaction control`_, it is recommended to create a
165 new connection (:py:obj:`SQLiteAppl.connect`).
166
167 .. _transaction control:
168 https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions
169 """
170
171 if getattr(self.thread_local, 'DB', None) is None:
172 self.thread_local.DB = self.connect()
173
174 # Theoretically it is possible to reuse the DB cursor across threads as
175 # of Python 3.12, in practice the threading of the cursor seems to me to
176 # be so faulty that I prefer to establish one connection per thread
177
178 self.thread_local.DB.commit()
179 return self.thread_local.DB
180
181 # In "serialized" mode, SQLite can be safely used by multiple threads
182 # with no restriction.
183 #
184 # if self.SQLITE_THREADING_MODE != "serialized":
185 # if getattr(self.thread_local, 'DB', None) is None:
186 # self.thread_local.DB = self.connect()
187 # return self.thread_local.DB
188 #
189 # if self._DB is None:
190 # self._DB = self.connect() # pylint: disable=attribute-defined-outside-init
191 # return self._DB
192
193 def init(self):
194 """Initializes the DB schema and properties, is only executed once even
195 if called several times."""
196
197 if self._init_done:
198 return
199 self._init_done = True
200
201 logger.debug("init DB: %s", self.db_url)
202 self.properties.init()
203 ver = self.properties("DB_SCHEMA")
204 if ver is None:
205 with self.properties.DB:
206 self.create_schema(self.properties.DB)
207 else:
208 ver = int(ver)
209 if ver != self.DB_SCHEMA:
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)
212
213 def create_schema(self, conn):
214
215 logger.debug("create schema ..")
216 with conn:
217 for table_name, sql in self.DDL_CREATE_TABLES.items():
218 conn.execute(sql)
219 self.properties.set(f"Table {table_name} created", table_name)
220 self.properties.set("DB_SCHEMA", self.DB_SCHEMA)
221 self.properties.set("LAST_MAINTENANCE", "")
222
223
225 """Simple class to manage properties of a DB application in the DB. The
226 object has its own DB connection and transaction area.
227
228 .. code:: sql
229
230 CREATE TABLE IF NOT EXISTS properties (
231 name TEXT,
232 value TEXT,
233 m_time INTEGER DEFAULT (strftime('%s', 'now')),
234 PRIMARY KEY (name))
235
236 """
237
238 SQLITE_JOURNAL_MODE = "WAL"
239
240 DDL_PROPERTIES = """\
241CREATE TABLE IF NOT EXISTS properties (
242 name TEXT,
243 value TEXT,
244 m_time INTEGER DEFAULT (strftime('%s', 'now')), -- last modified (unix epoch) time in sec.
245 PRIMARY KEY (name))"""
246
247 """Table to store properties of the DB application"""
248
249 SQL_GET = "SELECT value FROM properties WHERE name = ?"
250 SQL_M_TIME = "SELECT m_time FROM properties WHERE name = ?"
251 SQL_SET = (
252 "INSERT INTO properties (name, value) VALUES (?, ?)"
253 " ON CONFLICT(name) DO UPDATE"
254 " SET value=excluded.value, m_time=strftime('%s', 'now')"
255 )
256 SQL_TABLE_EXISTS = (
257 "SELECT name FROM sqlite_master"
258 " WHERE type='table' AND name='properties'"
259 ) # fmt:skip
260 SQLITE_CONNECT_ARGS = dict(SQLiteAppl.SQLITE_CONNECT_ARGS)
261 SQLITE_CONNECT_ARGS["autocommit"] = True # This option has no effect before Python 3.12
262
263 def __init__(self, db_url: str): # pylint: disable=super-init-not-called
264
265 self.db_urldb_url = db_url
266 self.thread_localthread_local = threading.local()
268 self._compatibility()
269
270 def init(self):
271 """Initializes DB schema of the properties in the DB."""
272
273 if self._init_done_init_done:
274 return
275 self._init_done_init_done = True
276 logger.debug("init properties of DB: %s", self.db_urldb_url)
277 with self.DB as conn:
278 res = conn.execute(self.SQL_TABLE_EXISTS)
279 if res.fetchone() is None: # DB schema needs to be be created
281
282 def __call__(self, name, default=None):
283 """Returns the value of the property ``name`` or ``default`` if property
284 not exists in DB."""
285
286 res = self.DB.execute(self.SQL_GET, (name,)).fetchone()
287 if res is None:
288 return default
289 return res[0]
290
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)."""
294
295 self.DB.execute(self.SQL_SET, (name, value))
296
297 if sys.version_info <= (3, 12):
298 # Prior Python 3.12 there is no "autocommit" option / lets commit
299 # explicitely.
300 self.DB.commit()
301
302 def row(self, name, default=None):
303 """Returns the DB row of property ``name`` or ``default`` if property
304 not exists in DB."""
305
306 cur = self.DB.cursor()
307 cur.execute("SELECT * FROM properties WHERE name = ?", (name,))
308 res = cur.fetchone()
309 if res is None:
310 return default
311 col_names = [column[0] for column in cur.description]
312 return dict(zip(col_names, res))
313
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()
317 if res is None:
318 return default
319 return int(res[0])
320
321 def create_schema(self, conn):
322 with conn:
323 conn.execute(self.DDL_PROPERTIES)
__init__(self, db_url)
Definition sqlitedb.py:88
sqlite3.Connection connect(self)
Definition sqlitedb.py:116
register_functions(self, conn)
Definition sqlitedb.py:131
create_schema(self, conn)
Definition sqlitedb.py:213
sqlite3.Connection DB(self)
Definition sqlitedb.py:156
__call__(self, name, default=None)
Definition sqlitedb.py:282
int m_time(self, name, int default=0)
Definition sqlitedb.py:314
row(self, name, default=None)
Definition sqlitedb.py:302
__init__(self, str db_url)
Definition sqlitedb.py:263