.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.sqlitedb.SQLiteAppl Class Reference
+ Inheritance diagram for searx.sqlitedb.SQLiteAppl:
+ Collaboration diagram for searx.sqlitedb.SQLiteAppl:

Public Member Functions

 __init__ (self, db_url)
 
sqlite3.Connection connect (self)
 
 register_functions (self, conn)
 
sqlite3.Connection DB (self)
 
 init (self)
 
 create_schema (self, conn)
 

Public Attributes

 db_url = db_url
 
 properties = SQLiteProperties(db_url)
 
 thread_local = threading.local()
 

Static Public Attributes

dict DDL_CREATE_TABLES = {}
 
int DB_SCHEMA = 1
 
dict SQLITE_THREADING_MODE
 
str SQLITE_JOURNAL_MODE = "WAL"
 
dict SQLITE_CONNECT_ARGS
 

Protected Member Functions

 _compatibility (self)
 

Protected Attributes

bool _init_done = False
 
 _DB = None
 

Detailed Description

Abstract base class for implementing convenient DB access in SQLite
applications.  In the constructor, a :py:obj:`SQLiteProperties` instance is
already aggregated under ``self.properties``.

Definition at line 26 of file sqlitedb.py.

Constructor & Destructor Documentation

◆ __init__()

searx.sqlitedb.SQLiteAppl.__init__ ( self,
db_url )

Reimplemented in searx.favicons.cache.FaviconCacheSQLite, and searx.sqlitedb.SQLiteProperties.

Definition at line 88 of file sqlitedb.py.

88 def __init__(self, db_url):
89
90 self.db_url = db_url
91 self.properties = SQLiteProperties(db_url)
92 self.thread_local = threading.local()
93 self._init_done = False
94 self._compatibility()
95

Member Function Documentation

◆ _compatibility()

searx.sqlitedb.SQLiteAppl._compatibility ( self)
protected

Definition at line 96 of file sqlitedb.py.

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

References searx.sqlitedb.SQLiteAppl.SQLITE_THREADING_MODE.

◆ connect()

sqlite3.Connection searx.sqlitedb.SQLiteAppl.connect ( self)
Creates a new DB connection (:py:obj:`SQLITE_CONNECT_ARGS`).  If not
already done, the DB schema is set up

Definition at line 116 of file sqlitedb.py.

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

References searx.favicons.cache.FaviconCacheStats.__class__, searx.favicons.cache.FaviconCacheConfig.db_url, searx.sqlitedb.SQLiteAppl.db_url, searx.sqlitedb.SQLiteProperties.db_url, searx.sqlitedb.SQLiteAppl.init(), searx.sqlitedb.SQLiteProperties.init(), searx.sqlitedb.SQLiteAppl.register_functions(), searx.sqlitedb.SQLiteAppl.SQLITE_CONNECT_ARGS, and searx.sqlitedb.SQLiteProperties.SQLITE_CONNECT_ARGS.

Referenced by searx.sqlitedb.SQLiteAppl.DB(), and searx.favicons.cache.FaviconCacheSQLite.set().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ create_schema()

searx.sqlitedb.SQLiteAppl.create_schema ( self,
conn )

Reimplemented in searx.sqlitedb.SQLiteProperties.

Definition at line 213 of file sqlitedb.py.

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

References searx.favicons.cache.FaviconCacheSQLite.DB_SCHEMA, searx.sqlitedb.SQLiteAppl.DB_SCHEMA, searx.favicons.cache.FaviconCacheSQLite.DDL_CREATE_TABLES, searx.sqlitedb.SQLiteAppl.DDL_CREATE_TABLES, and searx.sqlitedb.SQLiteAppl.properties.

Referenced by searx.sqlitedb.SQLiteAppl.init(), and searx.sqlitedb.SQLiteProperties.init().

+ Here is the caller graph for this function:

◆ DB()

sqlite3.Connection searx.sqlitedb.SQLiteAppl.DB ( self)
Provides a DB connection.  The connection is a *singleton* and
therefore well suited for read access.  If
:py:obj:`SQLITE_THREADING_MODE` is ``serialized`` only one DB connection
is created for all threads.

.. note::

   For dedicated `transaction control`_, it is recommended to create a
   new connection (:py:obj:`SQLiteAppl.connect`).

.. _transaction control:
    https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions

Definition at line 156 of file sqlitedb.py.

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

References searx.sqlitedb.SQLiteAppl.connect(), searx.sqlitedb.SQLiteAppl.thread_local, and searx.sqlitedb.SQLiteProperties.thread_local.

Referenced by searx.favicons.cache.FaviconCacheSQLite.__call__(), searx.sqlitedb.SQLiteProperties.__call__(), searx.favicons.cache.FaviconCacheSQLite._query_val(), searx.sqlitedb.SQLiteProperties.init(), searx.sqlitedb.SQLiteProperties.m_time(), searx.sqlitedb.SQLiteProperties.row(), and searx.sqlitedb.SQLiteProperties.set().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ init()

searx.sqlitedb.SQLiteAppl.init ( self)
Initializes the DB schema and properties, is only executed once even
if called several times.

Reimplemented in searx.sqlitedb.SQLiteProperties.

Definition at line 193 of file sqlitedb.py.

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

References searx.sqlitedb.SQLiteAppl._init_done, searx.sqlitedb.SQLiteProperties._init_done, searx.sqlitedb.SQLiteAppl.create_schema(), searx.sqlitedb.SQLiteProperties.create_schema(), searx.favicons.cache.FaviconCacheSQLite.DB_SCHEMA, searx.sqlitedb.SQLiteAppl.DB_SCHEMA, searx.favicons.cache.FaviconCacheConfig.db_url, searx.sqlitedb.SQLiteAppl.db_url, searx.sqlitedb.SQLiteProperties.db_url, and searx.sqlitedb.SQLiteAppl.properties.

Referenced by searx.sqlitedb.SQLiteAppl.connect().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ register_functions()

searx.sqlitedb.SQLiteAppl.register_functions ( self,
conn )
Create user-defined_ SQL functions.

``REGEXP(<pattern>, <field>)`` : 0 | 1
   `re.search`_ returns (int) 1 for a match and 0 for none match of
   ``<pattern>`` in ``<field>``.

   .. code:: sql

      SELECT '12' AS field WHERE REGEXP('^[0-9][0-9]$', field)
      -- 12

      SELECT REGEXP('[0-9][0-9]', 'X12Y')
      -- 1
      SELECT REGEXP('[0-9][0-9]', 'X1Y')
      -- 0

.. _user-defined: https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
.. _deterministic: https://sqlite.org/deterministic.html
.. _re.search: https://docs.python.org/3/library/re.html#re.search

Definition at line 131 of file sqlitedb.py.

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

Referenced by searx.sqlitedb.SQLiteAppl.connect().

+ Here is the caller graph for this function:

Member Data Documentation

◆ _DB

searx.sqlitedb.SQLiteAppl._DB = None
protected

Definition at line 99 of file sqlitedb.py.

◆ _init_done

bool searx.sqlitedb.SQLiteAppl._init_done = False
protected

◆ DB_SCHEMA

searx.sqlitedb.SQLiteAppl.DB_SCHEMA = 1
static

◆ db_url

searx.sqlitedb.SQLiteAppl.db_url = db_url

◆ DDL_CREATE_TABLES

dict searx.sqlitedb.SQLiteAppl.DDL_CREATE_TABLES = {}
static

Definition at line 31 of file sqlitedb.py.

Referenced by searx.sqlitedb.SQLiteAppl.create_schema().

◆ properties

◆ SQLITE_CONNECT_ARGS

searx.sqlitedb.SQLiteAppl.SQLITE_CONNECT_ARGS
static
Initial value:
= {
# "timeout": 5.0,
# "detect_types": 0,
"check_same_thread": bool(SQLITE_THREADING_MODE != "serialized"),
"cached_statements": 0, # https://github.com/python/cpython/issues/118172
# "uri": False,
"autocommit": False,
}

Definition at line 54 of file sqlitedb.py.

Referenced by searx.sqlitedb.SQLiteAppl.connect().

◆ SQLITE_JOURNAL_MODE

str searx.sqlitedb.SQLiteAppl.SQLITE_JOURNAL_MODE = "WAL"
static

Definition at line 53 of file sqlitedb.py.

◆ SQLITE_THREADING_MODE

dict searx.sqlitedb.SQLiteAppl.SQLITE_THREADING_MODE
static
Initial value:
= {
0: "single-thread",
1: "multi-thread",
3: "serialized"}[sqlite3.threadsafety]

Definition at line 38 of file sqlitedb.py.

Referenced by searx.sqlitedb.SQLiteAppl._compatibility().

◆ thread_local

searx.sqlitedb.SQLiteAppl.thread_local = threading.local()

Definition at line 92 of file sqlitedb.py.

Referenced by searx.sqlitedb.SQLiteAppl.DB().


The documentation for this class was generated from the following file: