.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
sqlite.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""SQLite is a small, fast and reliable SQL database engine. It does not require
3any extra dependency.
4
5Example
6=======
7
8.. _MediathekView: https://mediathekview.de/
9
10To demonstrate the power of database engines, here is a more complex example
11which reads from a MediathekView_ (DE) movie database. For this example of the
12SQLite engine download the database:
13
14- https://liste.mediathekview.de/filmliste-v2.db.bz2
15
16and unpack into ``searx/data/filmliste-v2.db``. To search the database use e.g
17Query to test: ``!mediathekview concert``
18
19.. code:: yaml
20
21 - name: mediathekview
22 engine: sqlite
23 disabled: False
24 categories: general
25 result_template: default.html
26 database: searx/data/filmliste-v2.db
27 query_str: >-
28 SELECT title || ' (' || time(duration, 'unixepoch') || ')' AS title,
29 COALESCE( NULLIF(url_video_hd,''), NULLIF(url_video_sd,''), url_video) AS url,
30 description AS content
31 FROM film
32 WHERE title LIKE :wildcard OR description LIKE :wildcard
33 ORDER BY duration DESC
34
35Implementations
36===============
37
38"""
39
40import sqlite3
41import contextlib
42
43engine_type = 'offline'
44database = ""
45query_str = ""
46limit = 10
47paging = True
48result_template = 'key-value.html'
49
50
51def init(engine_settings):
52 if 'query_str' not in engine_settings:
53 raise ValueError('query_str cannot be empty')
54
55 if not engine_settings['query_str'].lower().startswith('select '):
56 raise ValueError('only SELECT query is supported')
57
58
59@contextlib.contextmanager
61 """Implements a :py:obj:`Context Manager <contextlib.contextmanager>` for a
62 :py:obj:`sqlite3.Cursor`.
63
64 Open database in read only mode: if the database doesn't exist. The default
65 mode creates an empty file on the file system. See:
66
67 * https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
68 * https://www.sqlite.org/uri.html
69
70 """
71 uri = 'file:' + database + '?mode=ro'
72 with contextlib.closing(sqlite3.connect(uri, uri=True)) as connect:
73 connect.row_factory = sqlite3.Row
74 with contextlib.closing(connect.cursor()) as cursor:
75 yield cursor
76
77
78def search(query, params):
79 results = []
80
81 query_params = {
82 'query': query,
83 'wildcard': r'%' + query.replace(' ', r'%') + r'%',
84 'limit': limit,
85 'offset': (params['pageno'] - 1) * limit,
86 }
87 query_to_run = query_str + ' LIMIT :limit OFFSET :offset'
88
89 with sqlite_cursor() as cur:
90
91 cur.execute(query_to_run, query_params)
92 col_names = [cn[0] for cn in cur.description]
93
94 for row in cur.fetchall():
95 item = dict(zip(col_names, map(str, row)))
96 item['template'] = result_template
97 logger.debug("append result --> %s", item)
98 results.append(item)
99
100 return results
init(engine_settings)
Definition sqlite.py:51