sqlitedb.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Implementations to make access to SQLite databases a little more convenient.
  3. :py:obj:`SQLiteAppl`
  4. Abstract class with which DB applications can be implemented.
  5. :py:obj:`SQLiteProperties`:
  6. Class to manage properties stored in a database.
  7. Examplarical implementations based on :py:obj:`SQLiteAppl`:
  8. :py:obj:`searx.cache.ExpireCacheSQLite` :
  9. Cache that manages key/value pairs in a SQLite DB, in which the key/value
  10. pairs are deleted after an "expire" time. This type of cache is used, for
  11. example, for the engines, see :py:obj:`searx.enginelib.EngineCache`.
  12. :py:obj:`searx.favicons.cache.FaviconCacheSQLite` :
  13. Favicon cache that manages the favicon BLOBs in a SQLite DB.
  14. ----
  15. """
  16. from __future__ import annotations
  17. import abc
  18. import datetime
  19. import re
  20. import sqlite3
  21. import sys
  22. import threading
  23. import uuid
  24. from searx import logger
  25. logger = logger.getChild("sqlitedb")
  26. THREAD_LOCAL = threading.local()
  27. class DBSession:
  28. """A *thead-local* DB session"""
  29. @classmethod
  30. def get_connect(cls, app: SQLiteAppl) -> sqlite3.Connection:
  31. """Returns a thread local DB connection. The connection is only
  32. established once per thread.
  33. """
  34. if getattr(THREAD_LOCAL, "DBSession_map", None) is None:
  35. THREAD_LOCAL.DBSession_map = {}
  36. session = THREAD_LOCAL.DBSession_map.get(app.db_url)
  37. if session is None:
  38. session = cls(app)
  39. return session.conn
  40. def __init__(self, app: SQLiteAppl):
  41. self.uuid = uuid.uuid4()
  42. self.app = app
  43. self._conn = None
  44. # self.__del__ will be called, when thread ends
  45. if getattr(THREAD_LOCAL, "DBSession_map", None) is None:
  46. THREAD_LOCAL.DBSession_map = {}
  47. THREAD_LOCAL.DBSession_map[self.app.db_url] = self
  48. @property
  49. def conn(self) -> sqlite3.Connection:
  50. msg = f"[{threading.current_thread().ident}] DBSession: " f"{self.app.__class__.__name__}({self.app.db_url})"
  51. if self._conn is None:
  52. self._conn = self.app.connect()
  53. logger.debug("%s --> created new connection", msg)
  54. # else:
  55. # logger.debug("%s --> already connected", msg)
  56. return self._conn
  57. def __del__(self):
  58. try:
  59. if self._conn is not None:
  60. # HINT: Don't use Python's logging facility in a destructor, it
  61. # will produce error reports when python aborts the process or
  62. # thread, because at this point objects that the logging module
  63. # needs, do not exist anymore.
  64. # msg = f"DBSession: close [{self.uuid}] {self.app.__class__.__name__}({self.app.db_url})"
  65. # logger.debug(msg)
  66. self._conn.close()
  67. except Exception: # pylint: disable=broad-exception-caught
  68. pass
  69. class SQLiteAppl(abc.ABC):
  70. """Abstract base class for implementing convenient DB access in SQLite
  71. applications. In the constructor, a :py:obj:`SQLiteProperties` instance is
  72. already aggregated under ``self.properties``."""
  73. DDL_CREATE_TABLES: dict[str, str] = {}
  74. DB_SCHEMA: int = 1
  75. """As soon as changes are made to the DB schema, the version number must be
  76. increased. Changes to the version number require the DB to be recreated (or
  77. migrated / if an migration path exists and is implemented)."""
  78. SQLITE_THREADING_MODE = {
  79. 0: "single-thread",
  80. 1: "multi-thread",
  81. 3: "serialized"}[sqlite3.threadsafety] # fmt:skip
  82. """Threading mode of the SQLite library. Depends on the options used at
  83. compile time and is different for different distributions and architectures.
  84. Possible values are 0:``single-thread``, 1:``multi-thread``,
  85. 3:``serialized`` (see :py:obj:`sqlite3.threadsafety`). Pre- Python 3.11
  86. this value was hard coded to 1.
  87. Depending on this value, optimizations are made, e.g. in “serialized” mode
  88. it is not necessary to create a separate DB connector for each thread.
  89. """
  90. SQLITE_JOURNAL_MODE = "WAL"
  91. """``SQLiteAppl`` applications are optimzed for WAL_ mode, its not recommend
  92. to change the journal mode (see :py:obj:`SQLiteAppl.tear_down`).
  93. .. _WAL: https://sqlite.org/wal.html
  94. """
  95. SQLITE_CONNECT_ARGS = {
  96. # "timeout": 5.0,
  97. # "detect_types": 0,
  98. "check_same_thread": bool(SQLITE_THREADING_MODE != "serialized"),
  99. "cached_statements": 0, # https://github.com/python/cpython/issues/118172
  100. # "uri": False,
  101. "isolation_level": None,
  102. } # fmt:skip
  103. """Connection arguments (:py:obj:`sqlite3.connect`)
  104. ``check_same_thread``:
  105. Is disabled by default when :py:obj:`SQLITE_THREADING_MODE` is
  106. ``serialized``. The check is more of a hindrance in this case because it
  107. would prevent a DB connector from being used in multiple threads.
  108. ``cached_statements``:
  109. Is set to ``0`` by default. Note: Python 3.12+ fetch result are not
  110. consistent in multi-threading application and causing an API misuse error.
  111. The multithreading use in SQLiteAppl is intended and supported if
  112. threadsafety is set to 3 (aka "serialized"). CPython supports “serialized”
  113. from version 3.12 on, but unfortunately only with errors:
  114. - https://github.com/python/cpython/issues/118172
  115. - https://github.com/python/cpython/issues/123873
  116. The workaround for SQLite3 multithreading cache inconsistency ist to set
  117. option ``cached_statements`` to ``0`` by default.
  118. """
  119. def __init__(self, db_url):
  120. self.db_url = db_url
  121. self.properties = SQLiteProperties(db_url)
  122. self._init_done = False
  123. self._compatibility()
  124. # atexit.register(self.tear_down)
  125. # def tear_down(self):
  126. # """:ref:`Vacuuming the WALs` upon normal interpreter termination
  127. # (:py:obj:`atexit.register`).
  128. # .. _SQLite: Vacuuming the WALs: https://www.theunterminatedstring.com/sqlite-vacuuming/
  129. # """
  130. # self.DB.execute("PRAGMA wal_checkpoint(TRUNCATE)")
  131. def _compatibility(self):
  132. if self.SQLITE_THREADING_MODE == "serialized":
  133. self._DB = None
  134. else:
  135. msg = (
  136. f"SQLite library is compiled with {self.SQLITE_THREADING_MODE} mode,"
  137. " read https://docs.python.org/3/library/sqlite3.html#sqlite3.threadsafety"
  138. )
  139. if threading.active_count() > 1:
  140. logger.error(msg)
  141. else:
  142. logger.warning(msg)
  143. if sqlite3.sqlite_version_info <= (3, 35):
  144. # See "Generalize UPSERT:" in https://sqlite.org/releaselog/3_35_0.html
  145. logger.critical(
  146. "SQLite runtime library version %s is not supported (require >= 3.35)", sqlite3.sqlite_version
  147. )
  148. def _connect(self) -> sqlite3.Connection:
  149. conn = sqlite3.Connection(self.db_url, **self.SQLITE_CONNECT_ARGS) # type: ignore
  150. conn.execute(f"PRAGMA journal_mode={self.SQLITE_JOURNAL_MODE}")
  151. self.register_functions(conn)
  152. return conn
  153. def connect(self) -> sqlite3.Connection:
  154. """Creates a new DB connection (:py:obj:`SQLITE_CONNECT_ARGS`). If not
  155. already done, the DB schema is set up. The caller must take care of
  156. closing the resource. Alternatively, :py:obj:`SQLiteAppl.DB` can also
  157. be used (the resource behind `self.DB` is automatically closed when the
  158. process or thread is terminated).
  159. """
  160. if sys.version_info < (3, 12):
  161. # Prior Python 3.12 there is no "autocommit" option
  162. self.SQLITE_CONNECT_ARGS.pop("autocommit", None)
  163. msg = (
  164. f"[{threading.current_thread().ident}] {self.__class__.__name__}({self.db_url})"
  165. f" {self.SQLITE_CONNECT_ARGS} // {self.SQLITE_JOURNAL_MODE}"
  166. )
  167. logger.debug(msg)
  168. with self._connect() as conn:
  169. self.init(conn)
  170. return conn
  171. def register_functions(self, conn):
  172. """Create user-defined_ SQL functions.
  173. ``REGEXP(<pattern>, <field>)`` : 0 | 1
  174. `re.search`_ returns (int) 1 for a match and 0 for none match of
  175. ``<pattern>`` in ``<field>``.
  176. .. code:: sql
  177. SELECT '12' AS field WHERE REGEXP('^[0-9][0-9]$', field)
  178. -- 12
  179. SELECT REGEXP('[0-9][0-9]', 'X12Y')
  180. -- 1
  181. SELECT REGEXP('[0-9][0-9]', 'X1Y')
  182. -- 0
  183. .. _user-defined: https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
  184. .. _deterministic: https://sqlite.org/deterministic.html
  185. .. _re.search: https://docs.python.org/3/library/re.html#re.search
  186. """
  187. conn.create_function("regexp", 2, lambda x, y: 1 if re.search(x, y) else 0, deterministic=True)
  188. @property
  189. def DB(self) -> sqlite3.Connection:
  190. """Provides a DB connection. The connection is a *singleton* and
  191. therefore well suited for read access. If
  192. :py:obj:`SQLITE_THREADING_MODE` is ``serialized`` only one DB connection
  193. is created for all threads.
  194. .. note::
  195. For dedicated `transaction control`_, it is recommended to create a
  196. new connection (:py:obj:`SQLiteAppl.connect`).
  197. .. _transaction control:
  198. https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions
  199. """
  200. conn = None
  201. if self.SQLITE_THREADING_MODE == "serialized":
  202. # Theoretically it is possible to reuse the DB cursor across threads
  203. # as of Python 3.12, in practice the threading of the cursor seems
  204. # to me a little faulty that I prefer to establish one connection
  205. # per thread.
  206. #
  207. # may we can activate this code one day ..
  208. # if self._DB is None:
  209. # self._DB = self.connect()
  210. # conn = self._DB
  211. conn = DBSession.get_connect(self)
  212. else:
  213. conn = DBSession.get_connect(self)
  214. # Since more than one instance of SQLiteAppl share the same DB
  215. # connection, we need to make sure that each SQLiteAppl instance has run
  216. # its init method at least once.
  217. self.init(conn)
  218. return conn
  219. def init(self, conn: sqlite3.Connection) -> bool:
  220. """Initializes the DB schema and properties, is only executed once even
  221. if called several times.
  222. If the initialization has not yet taken place, it is carried out and a
  223. `True` is returned to the caller at the end. If the initialization has
  224. already been carried out in the past, `False` is returned.
  225. """
  226. if self._init_done:
  227. return False
  228. self._init_done = True
  229. logger.debug("init DB: %s", self.db_url)
  230. self.properties.init(conn)
  231. ver = self.properties("DB_SCHEMA")
  232. if ver is None:
  233. with conn:
  234. self.create_schema(conn)
  235. else:
  236. ver = int(ver)
  237. if ver != self.DB_SCHEMA:
  238. raise sqlite3.DatabaseError("Expected DB schema v%s, DB schema is v%s" % (self.DB_SCHEMA, ver))
  239. logger.debug("DB_SCHEMA = %s", ver)
  240. return True
  241. def create_schema(self, conn: sqlite3.Connection):
  242. logger.debug("create schema ..")
  243. self.properties.set("DB_SCHEMA", self.DB_SCHEMA)
  244. self.properties.set("LAST_MAINTENANCE", "")
  245. with conn:
  246. for table_name, sql in self.DDL_CREATE_TABLES.items():
  247. conn.execute(sql)
  248. self.properties.set(f"Table {table_name} created", table_name)
  249. class SQLiteProperties(SQLiteAppl):
  250. """Simple class to manage properties of a DB application in the DB. The
  251. object has its own DB connection and transaction area.
  252. .. code:: sql
  253. CREATE TABLE IF NOT EXISTS properties (
  254. name TEXT,
  255. value TEXT,
  256. m_time INTEGER DEFAULT (strftime('%s', 'now')),
  257. PRIMARY KEY (name))
  258. """
  259. SQLITE_JOURNAL_MODE = "WAL"
  260. DDL_PROPERTIES = """\
  261. CREATE TABLE IF NOT EXISTS properties (
  262. name TEXT,
  263. value TEXT,
  264. m_time INTEGER DEFAULT (strftime('%s', 'now')), -- last modified (unix epoch) time in sec.
  265. PRIMARY KEY (name))"""
  266. """Table to store properties of the DB application"""
  267. SQL_GET = "SELECT value FROM properties WHERE name = ?"
  268. SQL_M_TIME = "SELECT m_time FROM properties WHERE name = ?"
  269. SQL_SET = (
  270. "INSERT INTO properties (name, value) VALUES (?, ?)"
  271. " ON CONFLICT(name) DO UPDATE"
  272. " SET value=excluded.value, m_time=strftime('%s', 'now')"
  273. )
  274. SQL_DELETE = "DELETE FROM properties WHERE name = ?"
  275. SQL_TABLE_EXISTS = (
  276. "SELECT name FROM sqlite_master"
  277. " WHERE type='table' AND name='properties'"
  278. ) # fmt:skip
  279. SQLITE_CONNECT_ARGS = dict(SQLiteAppl.SQLITE_CONNECT_ARGS)
  280. def __init__(self, db_url: str): # pylint: disable=super-init-not-called
  281. self.db_url = db_url
  282. self._init_done = False
  283. self._compatibility()
  284. def init(self, conn: sqlite3.Connection) -> bool:
  285. """Initializes DB schema of the properties in the DB."""
  286. if self._init_done:
  287. return False
  288. self._init_done = True
  289. logger.debug("init properties of DB: %s", self.db_url)
  290. res = conn.execute(self.SQL_TABLE_EXISTS)
  291. if res.fetchone() is None: # DB schema needs to be be created
  292. self.create_schema(conn)
  293. return True
  294. def __call__(self, name: str, default=None):
  295. """Returns the value of the property ``name`` or ``default`` if property
  296. not exists in DB."""
  297. res = self.DB.execute(self.SQL_GET, (name,)).fetchone()
  298. if res is None:
  299. return default
  300. return res[0]
  301. def set(self, name: str, value: str | int):
  302. """Set ``value`` of property ``name`` in DB. If property already
  303. exists, update the ``m_time`` (and the value)."""
  304. with self.DB:
  305. self.DB.execute(self.SQL_SET, (name, value))
  306. def delete(self, name: str) -> int:
  307. """Delete of property ``name`` from DB."""
  308. with self.DB:
  309. cur = self.DB.execute(self.SQL_DELETE, (name,))
  310. return cur.rowcount
  311. def row(self, name: str, default=None):
  312. """Returns the DB row of property ``name`` or ``default`` if property
  313. not exists in DB."""
  314. res = self.DB.execute("SELECT * FROM properties WHERE name = ?", (name,))
  315. row = res.fetchone()
  316. if row is None:
  317. return default
  318. col_names = [column[0] for column in row.description]
  319. return dict(zip(col_names, row))
  320. def m_time(self, name: str, default: int = 0) -> int:
  321. """Last modification time of this property."""
  322. res = self.DB.execute(self.SQL_M_TIME, (name,))
  323. row = res.fetchone()
  324. if row is None:
  325. return default
  326. return int(row[0])
  327. def create_schema(self, conn):
  328. with conn:
  329. conn.execute(self.DDL_PROPERTIES)
  330. def __str__(self) -> str:
  331. lines = []
  332. for row in self.DB.execute("SELECT name, value, m_time FROM properties"):
  333. name, value, m_time = row
  334. m_time = datetime.datetime.fromtimestamp(m_time).strftime("%Y-%m-%d %H:%M:%S")
  335. lines.append(f"[last modified: {m_time}] {name:20s}: {value}")
  336. return "\n".join(lines)