sqlitedb.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. ----
  8. """
  9. from __future__ import annotations
  10. import sys
  11. import re
  12. import sqlite3
  13. import threading
  14. import abc
  15. from searx import logger
  16. logger = logger.getChild('sqlitedb')
  17. class SQLiteAppl(abc.ABC):
  18. """Abstract base class for implementing convenient DB access in SQLite
  19. applications. In the constructor, a :py:obj:`SQLiteProperties` instance is
  20. already aggregated under ``self.properties``."""
  21. DDL_CREATE_TABLES: dict[str, str] = {}
  22. DB_SCHEMA: int = 1
  23. """As soon as changes are made to the DB schema, the version number must be
  24. increased. Changes to the version number require the DB to be recreated (or
  25. migrated / if an migration path exists and is implemented)."""
  26. SQLITE_THREADING_MODE = {
  27. 0: "single-thread",
  28. 1: "multi-thread",
  29. 3: "serialized"}[sqlite3.threadsafety] # fmt:skip
  30. """Threading mode of the SQLite library. Depends on the options used at
  31. compile time and is different for different distributions and architectures.
  32. Possible values are 0:``single-thread``, 1:``multi-thread``,
  33. 3:``serialized`` (see :py:obj:`sqlite3.threadsafety`). Pre- Python 3.11
  34. this value was hard coded to 1.
  35. Depending on this value, optimizations are made, e.g. in “serialized” mode
  36. it is not necessary to create a separate DB connector for each thread.
  37. """
  38. SQLITE_JOURNAL_MODE = "WAL"
  39. SQLITE_CONNECT_ARGS = {
  40. # "timeout": 5.0,
  41. # "detect_types": 0,
  42. "check_same_thread": bool(SQLITE_THREADING_MODE != "serialized"),
  43. "cached_statements": 0, # https://github.com/python/cpython/issues/118172
  44. # "uri": False,
  45. "autocommit": False,
  46. } # fmt:skip
  47. """Connection arguments (:py:obj:`sqlite3.connect`)
  48. ``check_same_thread``:
  49. Is disabled by default when :py:obj:`SQLITE_THREADING_MODE` is
  50. ``serialized``. The check is more of a hindrance in this case because it
  51. would prevent a DB connector from being used in multiple threads.
  52. ``autocommit``:
  53. Is disabled by default. Note: autocommit option has been added in Python
  54. 3.12.
  55. ``cached_statements``:
  56. Is set to ``0`` by default. Note: Python 3.12+ fetch result are not
  57. consistent in multi-threading application and causing an API misuse error.
  58. The multithreading use in SQLiteAppl is intended and supported if
  59. threadsafety is set to 3 (aka "serialized"). CPython supports “serialized”
  60. from version 3.12 on, but unfortunately only with errors:
  61. - https://github.com/python/cpython/issues/118172
  62. - https://github.com/python/cpython/issues/123873
  63. The workaround for SQLite3 multithreading cache inconsistency ist to set
  64. option ``cached_statements`` to ``0`` by default.
  65. """
  66. def __init__(self, db_url):
  67. self.db_url = db_url
  68. self.properties = SQLiteProperties(db_url)
  69. self.thread_local = threading.local()
  70. self._init_done = False
  71. self._compatibility()
  72. def _compatibility(self):
  73. if self.SQLITE_THREADING_MODE == "serialized":
  74. self._DB = None
  75. else:
  76. msg = (
  77. f"SQLite library is compiled with {self.SQLITE_THREADING_MODE} mode,"
  78. " read https://docs.python.org/3/library/sqlite3.html#sqlite3.threadsafety"
  79. )
  80. if threading.active_count() > 1:
  81. logger.error(msg)
  82. else:
  83. logger.warning(msg)
  84. if sqlite3.sqlite_version_info <= (3, 35):
  85. # See "Generalize UPSERT:" in https://sqlite.org/releaselog/3_35_0.html
  86. logger.critical(
  87. "SQLite runtime library version %s is not supported (require >= 3.35)", sqlite3.sqlite_version
  88. )
  89. def connect(self) -> sqlite3.Connection:
  90. """Creates a new DB connection (:py:obj:`SQLITE_CONNECT_ARGS`). If not
  91. already done, the DB schema is set up
  92. """
  93. if sys.version_info < (3, 12):
  94. # Prior Python 3.12 there is no "autocommit" option
  95. self.SQLITE_CONNECT_ARGS.pop("autocommit", None)
  96. self.init()
  97. logger.debug("%s: connect to DB: %s // %s", self.__class__.__name__, self.db_url, self.SQLITE_CONNECT_ARGS)
  98. conn = sqlite3.Connection(self.db_url, **self.SQLITE_CONNECT_ARGS) # type: ignore
  99. conn.execute(f"PRAGMA journal_mode={self.SQLITE_JOURNAL_MODE}")
  100. self.register_functions(conn)
  101. return conn
  102. def register_functions(self, conn):
  103. """Create user-defined_ SQL functions.
  104. ``REGEXP(<pattern>, <field>)`` : 0 | 1
  105. `re.search`_ returns (int) 1 for a match and 0 for none match of
  106. ``<pattern>`` in ``<field>``.
  107. .. code:: sql
  108. SELECT '12' AS field WHERE REGEXP('^[0-9][0-9]$', field)
  109. -- 12
  110. SELECT REGEXP('[0-9][0-9]', 'X12Y')
  111. -- 1
  112. SELECT REGEXP('[0-9][0-9]', 'X1Y')
  113. -- 0
  114. .. _user-defined: https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
  115. .. _deterministic: https://sqlite.org/deterministic.html
  116. .. _re.search: https://docs.python.org/3/library/re.html#re.search
  117. """
  118. conn.create_function('regexp', 2, lambda x, y: 1 if re.search(x, y) else 0, deterministic=True)
  119. @property
  120. def DB(self) -> sqlite3.Connection:
  121. """Provides a DB connection. The connection is a *singleton* and
  122. therefore well suited for read access. If
  123. :py:obj:`SQLITE_THREADING_MODE` is ``serialized`` only one DB connection
  124. is created for all threads.
  125. .. note::
  126. For dedicated `transaction control`_, it is recommended to create a
  127. new connection (:py:obj:`SQLiteAppl.connect`).
  128. .. _transaction control:
  129. https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions
  130. """
  131. if getattr(self.thread_local, 'DB', None) is None:
  132. self.thread_local.DB = self.connect()
  133. # Theoretically it is possible to reuse the DB cursor across threads as
  134. # of Python 3.12, in practice the threading of the cursor seems to me to
  135. # be so faulty that I prefer to establish one connection per thread
  136. self.thread_local.DB.commit()
  137. return self.thread_local.DB
  138. # In "serialized" mode, SQLite can be safely used by multiple threads
  139. # with no restriction.
  140. #
  141. # if self.SQLITE_THREADING_MODE != "serialized":
  142. # if getattr(self.thread_local, 'DB', None) is None:
  143. # self.thread_local.DB = self.connect()
  144. # return self.thread_local.DB
  145. #
  146. # if self._DB is None:
  147. # self._DB = self.connect() # pylint: disable=attribute-defined-outside-init
  148. # return self._DB
  149. def init(self):
  150. """Initializes the DB schema and properties, is only executed once even
  151. if called several times."""
  152. if self._init_done:
  153. return
  154. self._init_done = True
  155. logger.debug("init DB: %s", self.db_url)
  156. self.properties.init()
  157. ver = self.properties("DB_SCHEMA")
  158. if ver is None:
  159. with self.properties.DB:
  160. self.create_schema(self.properties.DB)
  161. else:
  162. ver = int(ver)
  163. if ver != self.DB_SCHEMA:
  164. raise sqlite3.DatabaseError("Expected DB schema v%s, DB schema is v%s" % (self.DB_SCHEMA, ver))
  165. logger.debug("DB_SCHEMA = %s", ver)
  166. def create_schema(self, conn):
  167. logger.debug("create schema ..")
  168. with conn:
  169. for table_name, sql in self.DDL_CREATE_TABLES.items():
  170. conn.execute(sql)
  171. self.properties.set(f"Table {table_name} created", table_name)
  172. self.properties.set("DB_SCHEMA", self.DB_SCHEMA)
  173. self.properties.set("LAST_MAINTENANCE", "")
  174. class SQLiteProperties(SQLiteAppl):
  175. """Simple class to manage properties of a DB application in the DB. The
  176. object has its own DB connection and transaction area.
  177. .. code:: sql
  178. CREATE TABLE IF NOT EXISTS properties (
  179. name TEXT,
  180. value TEXT,
  181. m_time INTEGER DEFAULT (strftime('%s', 'now')),
  182. PRIMARY KEY (name))
  183. """
  184. SQLITE_JOURNAL_MODE = "WAL"
  185. DDL_PROPERTIES = """\
  186. CREATE TABLE IF NOT EXISTS properties (
  187. name TEXT,
  188. value TEXT,
  189. m_time INTEGER DEFAULT (strftime('%s', 'now')), -- last modified (unix epoch) time in sec.
  190. PRIMARY KEY (name))"""
  191. """Table to store properties of the DB application"""
  192. SQL_GET = "SELECT value FROM properties WHERE name = ?"
  193. SQL_M_TIME = "SELECT m_time FROM properties WHERE name = ?"
  194. SQL_SET = (
  195. "INSERT INTO properties (name, value) VALUES (?, ?)"
  196. " ON CONFLICT(name) DO UPDATE"
  197. " SET value=excluded.value, m_time=strftime('%s', 'now')"
  198. )
  199. SQL_TABLE_EXISTS = (
  200. "SELECT name FROM sqlite_master"
  201. " WHERE type='table' AND name='properties'"
  202. ) # fmt:skip
  203. SQLITE_CONNECT_ARGS = dict(SQLiteAppl.SQLITE_CONNECT_ARGS)
  204. SQLITE_CONNECT_ARGS["autocommit"] = True # This option has no effect before Python 3.12
  205. def __init__(self, db_url: str): # pylint: disable=super-init-not-called
  206. self.db_url = db_url
  207. self.thread_local = threading.local()
  208. self._init_done = False
  209. self._compatibility()
  210. def init(self):
  211. """Initializes DB schema of the properties in the DB."""
  212. if self._init_done:
  213. return
  214. self._init_done = True
  215. logger.debug("init properties of DB: %s", self.db_url)
  216. with self.DB as conn:
  217. res = conn.execute(self.SQL_TABLE_EXISTS)
  218. if res.fetchone() is None: # DB schema needs to be be created
  219. self.create_schema(conn)
  220. def __call__(self, name, default=None):
  221. """Returns the value of the property ``name`` or ``default`` if property
  222. not exists in DB."""
  223. res = self.DB.execute(self.SQL_GET, (name,)).fetchone()
  224. if res is None:
  225. return default
  226. return res[0]
  227. def set(self, name, value):
  228. """Set ``value`` of property ``name`` in DB. If property already
  229. exists, update the ``m_time`` (and the value)."""
  230. self.DB.execute(self.SQL_SET, (name, value))
  231. if sys.version_info <= (3, 12):
  232. # Prior Python 3.12 there is no "autocommit" option / lets commit
  233. # explicitely.
  234. self.DB.commit()
  235. def row(self, name, default=None):
  236. """Returns the DB row of property ``name`` or ``default`` if property
  237. not exists in DB."""
  238. cur = self.DB.cursor()
  239. cur.execute("SELECT * FROM properties WHERE name = ?", (name,))
  240. res = cur.fetchone()
  241. if res is None:
  242. return default
  243. col_names = [column[0] for column in cur.description]
  244. return dict(zip(col_names, res))
  245. def m_time(self, name, default: int = 0) -> int:
  246. """Last modification time of this property."""
  247. res = self.DB.execute(self.SQL_M_TIME, (name,)).fetchone()
  248. if res is None:
  249. return default
  250. return int(res[0])
  251. def create_schema(self, conn):
  252. with conn:
  253. conn.execute(self.DDL_PROPERTIES)