database-wrapper-sqlite 0.3.146__py3-none-any.whl → 0.3.147__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,8 +9,17 @@ Part of the database_wrapper package
9
9
  import logging
10
10
 
11
11
  # from .db_wrapper_sqlite import DBWrapperSqlite
12
- from .connector import Sqlite, SqliteConfig, SqliteTypedDictCursor
12
+ from .connector import (
13
+ Sqlite,
14
+ SqliteAsync,
15
+ SqliteConfig,
16
+ SqliteConnectionAsync,
17
+ SqliteTypedDictCursor,
18
+ SqliteTypedDictCursorAsync,
19
+ SqliteWithPoolingAsync,
20
+ )
13
21
  from .db_wrapper_sqlite import DBWrapperSqlite
22
+ from .db_wrapper_sqlite_async import DBWrapperSqliteAsync
14
23
 
15
24
  # Set the logger to a quiet default, can be enabled if needed
16
25
  logger = logging.getLogger("database_wrapper_sqlite")
@@ -21,10 +30,15 @@ if logger.level == logging.NOTSET:
21
30
  __all__ = [
22
31
  # Wrappers
23
32
  DBWrapperSqlite,
33
+ DBWrapperSqliteAsync,
24
34
  # Connectors
25
35
  Sqlite,
36
+ SqliteAsync,
37
+ SqliteWithPoolingAsync,
26
38
  # Connection and Cursor types
39
+ SqliteConnectionAsync,
27
40
  SqliteTypedDictCursor,
41
+ SqliteTypedDictCursorAsync,
28
42
  # Helpers
29
43
  SqliteConfig,
30
44
  ]
@@ -1,6 +1,10 @@
1
1
  import sqlite3
2
+ from collections.abc import AsyncIterator, Iterable
3
+ from contextlib import asynccontextmanager
2
4
  from typing import Any, NotRequired, TypedDict, cast
3
5
 
6
+ import aiosqlite
7
+
4
8
  from database_wrapper import DatabaseBackend
5
9
 
6
10
 
@@ -116,3 +120,272 @@ class Sqlite(DatabaseBackend):
116
120
 
117
121
  self.logger.debug("Rollback DB queries")
118
122
  self.connection.rollback()
123
+
124
+
125
+ class SqliteTypedDictCursorAsync(aiosqlite.Cursor):
126
+ """
127
+ Type hint wrapper only. At runtime, this is just an aiosqlite.Cursor
128
+ that happens to produce dicts because of the row_factory.
129
+ """
130
+
131
+ async def fetchone(self) -> dict[str, Any] | None: # type: ignore[override]
132
+ return await super().fetchone() # type: ignore
133
+
134
+ async def fetchall(self) -> list[dict[str, Any]]: # type: ignore[override]
135
+ return await super().fetchall() # type: ignore
136
+
137
+
138
+ class SqliteConnectionAsync:
139
+ """
140
+ An aiosqlite connection in autocommit mode with psycopg's `transaction()`.
141
+ Outside a transaction every statement commits on its own, as on a pooled
142
+ PostgreSQL connection.
143
+ """
144
+
145
+ raw: aiosqlite.Connection
146
+ """ The underlying aiosqlite connection """
147
+
148
+ database: str
149
+ """ Database path, as configured """
150
+
151
+ def __init__(self, raw: aiosqlite.Connection, database: str) -> None:
152
+ self.raw = raw
153
+ self.database = database
154
+ self._depth = 0
155
+
156
+ @property
157
+ def in_transaction(self) -> bool:
158
+ return self.raw.in_transaction
159
+
160
+ async def cursor(self) -> SqliteTypedDictCursorAsync:
161
+ return cast(SqliteTypedDictCursorAsync, await self.raw.cursor())
162
+
163
+ async def execute(self, statement: str, parameters: Iterable[Any] | None = None) -> SqliteTypedDictCursorAsync:
164
+ return cast(SqliteTypedDictCursorAsync, await self.raw.execute(statement, parameters))
165
+
166
+ async def close(self) -> None:
167
+ await self.raw.close()
168
+
169
+ @asynccontextmanager
170
+ async def transaction(self) -> AsyncIterator[None]:
171
+ """
172
+ BEGIN IMMEDIATE takes the write lock up front: a deferred transaction that reads
173
+ first gets SQLITE_BUSY at its first write, without waiting out the timeout.
174
+ Nested calls are savepoints.
175
+ """
176
+ depth = self._depth
177
+ savepoint = f"sp_{depth}"
178
+ await self.raw.execute("BEGIN IMMEDIATE" if depth == 0 else f"SAVEPOINT {savepoint}")
179
+ self._depth = depth + 1
180
+ try:
181
+ yield
182
+ except BaseException:
183
+ # Some errors make SQLite roll back by itself; a second ROLLBACK would then
184
+ # raise and hide the error that caused it.
185
+ if self.raw.in_transaction:
186
+ if depth == 0:
187
+ await self.raw.execute("ROLLBACK")
188
+ else:
189
+ await self.raw.execute(f"ROLLBACK TO {savepoint}")
190
+ await self.raw.execute(f"RELEASE {savepoint}")
191
+ raise
192
+ else:
193
+ await self.raw.execute("COMMIT" if depth == 0 else f"RELEASE {savepoint}")
194
+ finally:
195
+ self._depth = depth
196
+
197
+
198
+ def is_memory_database(database: str) -> bool:
199
+ return database in ("", ":memory:")
200
+
201
+
202
+ async def connect_async(config: SqliteConfig) -> SqliteConnectionAsync:
203
+ """
204
+ Opens an autocommit connection with dict rows, foreign keys on and WAL.
205
+ `isolation_level` is ignored: transactions come from `transaction()`.
206
+ """
207
+ database = str(config["database"])
208
+ raw = await aiosqlite.connect(
209
+ database,
210
+ isolation_level=None,
211
+ timeout=config.get("timeout", 5.0),
212
+ **config.get("kwargs", {}),
213
+ )
214
+ try:
215
+ raw.row_factory = dict_factory # type: ignore[assignment]
216
+ # foreign_keys is per connection and off by default. WAL is stored in the file,
217
+ # so after the first connection this is a no-op.
218
+ await raw.execute("PRAGMA foreign_keys = ON")
219
+ if not is_memory_database(database):
220
+ await raw.execute("PRAGMA journal_mode = WAL")
221
+ except BaseException:
222
+ await raw.close()
223
+ raise
224
+
225
+ return SqliteConnectionAsync(raw, database)
226
+
227
+
228
+ class SqliteAsync(DatabaseBackend):
229
+ """
230
+ SQLite database async implementation, on aiosqlite.
231
+
232
+ Instance is created without actually connecting to the database.
233
+ When you are ready to connect, call await open() method.
234
+
235
+ ! Note: Close is not called automatically when class is destroyed.
236
+ ! You need to call it manually in async environment.
237
+
238
+ :param config: Configuration for SQLite
239
+ :type config: SqliteConfig
240
+ """
241
+
242
+ config: SqliteConfig
243
+
244
+ connection: SqliteConnectionAsync | None
245
+ cursor: SqliteTypedDictCursorAsync | None
246
+
247
+ def __del__(self) -> None:
248
+ """Destructor"""
249
+
250
+ # Just to be sure as async does not have __del__
251
+ if hasattr(self, "cursor"):
252
+ del self.cursor
253
+
254
+ if hasattr(self, "connection"):
255
+ del self.connection
256
+
257
+ async def open(self) -> None:
258
+ # Free resources
259
+ if hasattr(self, "connection") and self.connection:
260
+ await self.close()
261
+
262
+ self.logger.debug("Connecting to DB")
263
+ self.connection = await connect_async(self.config)
264
+ self.cursor = await self.connection.cursor()
265
+
266
+ async def close(self) -> Any:
267
+ """Close connections"""
268
+ try:
269
+ if hasattr(self, "cursor") and self.cursor:
270
+ self.logger.debug("Closing cursor")
271
+ await self.cursor.close()
272
+ except Exception as e:
273
+ self.logger.debug(f"Error while closing cursor: {e}")
274
+ finally:
275
+ self.cursor = None
276
+
277
+ try:
278
+ if hasattr(self, "connection") and self.connection:
279
+ self.logger.debug("Closing connection")
280
+ await self.connection.close()
281
+ except Exception as e:
282
+ self.logger.debug(f"Error while closing connection: {e}")
283
+ finally:
284
+ self.connection = None
285
+
286
+ async def ping(self) -> bool:
287
+ try:
288
+ assert self.cursor, "Cursor is not initialized"
289
+ await self.cursor.execute("SELECT 1")
290
+ await self.cursor.fetchone()
291
+ except Exception as e:
292
+ self.logger.debug(f"Error while pinging the database: {e}")
293
+ return False
294
+
295
+ return True
296
+
297
+ ####################
298
+ ### Transactions ###
299
+ ####################
300
+
301
+ @asynccontextmanager
302
+ async def transaction(self, db_conn: SqliteConnectionAsync | None = None) -> AsyncIterator[None]:
303
+ """Transaction context manager"""
304
+ connection = db_conn or self.connection
305
+ assert connection, "Connection is not initialized"
306
+ async with connection.transaction():
307
+ yield
308
+
309
+ ############
310
+ ### Data ###
311
+ ############
312
+
313
+ def last_insert_id(self) -> int:
314
+ assert self.cursor, "Cursor is not initialized"
315
+ return self.cursor.lastrowid or 0
316
+
317
+ def affected_rows(self) -> int:
318
+ assert self.cursor, "Cursor is not initialized"
319
+ return self.cursor.rowcount
320
+
321
+
322
+ class SqliteWithPoolingAsync(DatabaseBackend):
323
+ """
324
+ `async with pool as (connection, cursor)` over SQLite, the same shape as
325
+ PgsqlWithPoolingAsync, so code written against one runs on the other.
326
+
327
+ Connections are not reused: opening one is cheap, and a fresh one per context
328
+ means a transaction left open by one user cannot reach the next.
329
+
330
+ pool = SqliteWithPoolingAsync(config)
331
+ await pool.open_pool()
332
+ async with pool as (connection, cursor):
333
+ await cursor.execute("SELECT 1")
334
+
335
+ :param config: Configuration for SQLite
336
+ :type config: SqliteConfig
337
+ """
338
+
339
+ config: SqliteConfig
340
+
341
+ def __del__(self) -> None:
342
+ """Nothing to release: connections live only inside their contexts"""
343
+
344
+ async def open_pool(self) -> None:
345
+ """Connects once, so a wrong path or an unwritable directory fails here"""
346
+ connection = await connect_async(self.config)
347
+ await connection.close()
348
+
349
+ async def close_pool(self) -> None:
350
+ """Nothing is pooled, so nothing to close"""
351
+ self.shutdown_requested.set()
352
+
353
+ async def new_connection(self) -> tuple[SqliteConnectionAsync, SqliteTypedDictCursorAsync]:
354
+ self.logger.debug("Opening connection")
355
+ connection = await connect_async(self.config)
356
+ try:
357
+ cursor = await connection.cursor()
358
+ except BaseException:
359
+ await connection.close()
360
+ raise
361
+
362
+ return (connection, cursor)
363
+
364
+ async def return_connection(self, connection: SqliteConnectionAsync) -> None:
365
+ self.logger.debug("Closing connection")
366
+ await connection.close()
367
+
368
+ ###############
369
+ ### Context ###
370
+ ###############
371
+
372
+ async def __aenter__(self) -> tuple[SqliteConnectionAsync, SqliteTypedDictCursorAsync]:
373
+ """Context manager"""
374
+ # Kept per context, so concurrent tasks sharing this instance each close their own.
375
+ res = await self.new_connection()
376
+ stack = self.context_connection_async.get() or ()
377
+ self.context_connection_async.set(stack + (res,))
378
+ return res
379
+
380
+ async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
381
+ """Context manager"""
382
+ stack = self.context_connection_async.get() or ()
383
+ if not stack:
384
+ return
385
+
386
+ (connection, cursor) = stack[-1]
387
+ self.context_connection_async.set(stack[:-1])
388
+ try:
389
+ await cursor.close()
390
+ finally:
391
+ await self.return_connection(connection)
@@ -0,0 +1,77 @@
1
+ import logging
2
+ from typing import Any
3
+
4
+ from database_wrapper import DBWrapperAsync
5
+
6
+ from .connector import SqliteTypedDictCursorAsync
7
+
8
+
9
+ class DBWrapperSqliteAsync(DBWrapperAsync):
10
+ """
11
+ Async database wrapper for SQLite
12
+
13
+ This is meant to be used in async environments.
14
+ """
15
+
16
+ db_cursor: SqliteTypedDictCursorAsync | None
17
+ """ Async SQLite cursor object """
18
+
19
+ placeholder = "?"
20
+ """ sqlite3 uses qmark paramstyle """
21
+
22
+ insert_returning = False
23
+ """ The id comes back from lastrowid """
24
+
25
+ #######################
26
+ ### Class lifecycle ###
27
+ #######################
28
+
29
+ # Meta methods
30
+ # We are overriding the __init__ method for the type hinting
31
+ def __init__(
32
+ self,
33
+ db_cursor: SqliteTypedDictCursorAsync | None = None,
34
+ logger: logging.Logger | None = None,
35
+ ):
36
+ """
37
+ Initializes a new instance of the DBWrapper class.
38
+
39
+ Args:
40
+ db_cursor (SqliteTypedDictCursorAsync): The async SQLite cursor object.
41
+ logger (logging.Logger, optional): The logger object. Defaults to None.
42
+ """
43
+ super().__init__(db_cursor, logger)
44
+
45
+ ###############
46
+ ### Setters ###
47
+ ###############
48
+
49
+ def set_db_cursor(self, db_cursor: SqliteTypedDictCursorAsync | None) -> None:
50
+ """
51
+ Updates the database cursor object.
52
+
53
+ Args:
54
+ db_cursor (SqliteTypedDictCursorAsync): The new database cursor object.
55
+ """
56
+ super().set_db_cursor(db_cursor)
57
+
58
+ ######################
59
+ ### Helper methods ###
60
+ ######################
61
+
62
+ def log_query(
63
+ self,
64
+ cursor: SqliteTypedDictCursorAsync,
65
+ query: Any,
66
+ params: tuple[Any, ...],
67
+ ) -> None:
68
+ """
69
+ Logs the given query and parameters.
70
+
71
+ Args:
72
+ cursor (SqliteTypedDictCursorAsync): The cursor used to execute the query.
73
+ query (Any): The query to log.
74
+ params (tuple[Any, ...]): The parameters to log.
75
+ """
76
+ # sqlite3 does not support mogrify, so we just log query and params
77
+ logging.getLogger().debug(f"Query: {query} with params: {params}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: database_wrapper_sqlite
3
- Version: 0.3.146
3
+ Version: 0.3.147
4
4
  Summary: database_wrapper for SQLite database
5
5
  Author-email: Gints Murans <gm@gm.lv>
6
6
  License-Expression: MIT
@@ -32,7 +32,8 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
32
  Requires-Python: >=3.8
33
33
  Description-Content-Type: text/markdown
34
34
  License-File: LICENSE
35
- Requires-Dist: database_wrapper==0.3.146
35
+ Requires-Dist: database_wrapper==0.3.147
36
+ Requires-Dist: aiosqlite
36
37
  Dynamic: license-file
37
38
 
38
39
  # database_wrapper_sqlite
@@ -41,10 +42,6 @@ _Part of the `database_wrapper` package._
41
42
 
42
43
  This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
43
44
 
44
- ## !!! IMPORTANT !!!
45
-
46
- This package is not yet implemented. The README is a placeholder for future implementation.
47
-
48
45
  ## Installation
49
46
 
50
47
  ```bash
@@ -56,37 +53,49 @@ pip install database_wrapper[sqlite]
56
53
  ```python
57
54
  from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
58
55
 
59
- db = Sqlite({
60
- "database": "my_database.db",
61
- })
56
+ db = Sqlite({"database": "my_database.db"})
62
57
  db.open()
63
- dbWrapper = DBWrapperSqlite(dbCursor=db.cursor)
64
-
65
- # Simple query
66
- aModel = MyModel()
67
- res = await dbWrapper.getByKey(
68
- aModel,
69
- "id",
70
- 3005,
71
- )
58
+ db_wrapper = DBWrapperSqlite(db_cursor=db.cursor)
59
+
60
+ res = db_wrapper.get_by_key(MyModel(), "id", 3005)
72
61
  if res:
73
- print(f"getByKey: {res.toDict()}")
74
- else:
75
- print("No results")
76
-
77
- # Raw query
78
- res = await dbWrapper.getAll(
79
- aModel,
80
- customQuery="""
81
- SELECT t1.*, t2.name AS other_name
82
- FROM my_table AS t1
83
- LEFT JOIN other_table AS t2 ON t1.other_id = t2.id
84
- """
85
- )
86
- async for record in res:
87
- print(f"getAll: {record.toDict()}")
88
- else:
89
- print("No results")
62
+ print(f"get_by_key: {res.to_dict()}")
90
63
 
91
64
  db.close()
92
65
  ```
66
+
67
+ ### Async
68
+
69
+ `SqliteWithPoolingAsync` has the shape of `PgsqlWithPoolingAsync`: `async with pool as
70
+ (connection, cursor)`, so code written against one runs on the other as long as its SQL does.
71
+ It opens a fresh aiosqlite connection per context rather than reusing them.
72
+
73
+ ```python
74
+ from database_wrapper_sqlite import SqliteWithPoolingAsync, DBWrapperSqliteAsync
75
+
76
+ pool = SqliteWithPoolingAsync({"database": "/srv/app/data/app.sqlite3"})
77
+ await pool.open_pool()
78
+
79
+ async with pool as (connection, cursor):
80
+ db_wrapper = DBWrapperSqliteAsync(cursor)
81
+
82
+ async with connection.transaction():
83
+ await db_wrapper.insert(MyModel(name="x"))
84
+
85
+ res = db_wrapper.get_all(MyModel(), custom_query="SELECT * FROM my_table WHERE active = 1")
86
+ async for record in res:
87
+ print(record.to_dict())
88
+ ```
89
+
90
+ Async connections differ from the sync `Sqlite` on purpose:
91
+
92
+ - Autocommit: every statement commits on its own outside `connection.transaction()`, as on a
93
+ pooled PostgreSQL connection. `isolation_level` is ignored.
94
+ - `transaction()` starts with `BEGIN IMMEDIATE`, taking the write lock up front, so a
95
+ transaction that reads before it writes cannot fail with `SQLITE_BUSY` at the write.
96
+ Nested calls are savepoints.
97
+ - `PRAGMA foreign_keys = ON` on every connection, and WAL for a file database.
98
+ - Rows are dicts; `DBWrapperSqliteAsync` uses `?` placeholders and reads inserted ids from
99
+ `lastrowid`.
100
+
101
+ `SqliteAsync` is the single-connection form, like `PgsqlAsync`.
@@ -0,0 +1,10 @@
1
+ database_wrapper_sqlite/__init__.py,sha256=KbJ2jytZVQqkVH3COhI7VPjt2Tys4mGa8PSDmJoa19Q,988
2
+ database_wrapper_sqlite/connector.py,sha256=Mi-ss-0BYh_C4KTf3NH8MlsfbRrd4IM2xvK_oLt3VNM,12585
3
+ database_wrapper_sqlite/db_wrapper_sqlite.py,sha256=ZWHYPuH_SAF7zjvFY2THl6ycpjIWmJFrXKdgLwIegZA,2307
4
+ database_wrapper_sqlite/db_wrapper_sqlite_async.py,sha256=1rXmQLfjoDpqfXOMO39VFKqNqy-A6jx3CiTE7mBPZgE,2149
5
+ database_wrapper_sqlite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ database_wrapper_sqlite-0.3.147.dist-info/licenses/LICENSE,sha256=7P9Q3qmdxgm5mcSHNP7uQ1f0qH9voGXDwLWxjGjtVqM,1080
7
+ database_wrapper_sqlite-0.3.147.dist-info/METADATA,sha256=PwSylbzy0F_tYbqqW3sLWWmiaOFawva8C-jzrKXRj08,3722
8
+ database_wrapper_sqlite-0.3.147.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ database_wrapper_sqlite-0.3.147.dist-info/top_level.txt,sha256=53mm8n6modSF012UMCHllRLbCLajpC0uDwHE0WU1Lxo,24
10
+ database_wrapper_sqlite-0.3.147.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (83.0.0)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,9 +0,0 @@
1
- database_wrapper_sqlite/__init__.py,sha256=kum2GLgvrgaq-BwlU6u99Zz5gzGOINr2z5f-KhnVr-A,679
2
- database_wrapper_sqlite/connector.py,sha256=5NCSCLrSLq1aXI8guHwP_B_GPmGE5W6YEGde47hZXwU,3337
3
- database_wrapper_sqlite/db_wrapper_sqlite.py,sha256=ZWHYPuH_SAF7zjvFY2THl6ycpjIWmJFrXKdgLwIegZA,2307
4
- database_wrapper_sqlite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
- database_wrapper_sqlite-0.3.146.dist-info/licenses/LICENSE,sha256=7P9Q3qmdxgm5mcSHNP7uQ1f0qH9voGXDwLWxjGjtVqM,1080
6
- database_wrapper_sqlite-0.3.146.dist-info/METADATA,sha256=cVQF0y1qsNa-JZ-mtouBRxaPw0UNslw0LzOo29bLrfU,2731
7
- database_wrapper_sqlite-0.3.146.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
8
- database_wrapper_sqlite-0.3.146.dist-info/top_level.txt,sha256=53mm8n6modSF012UMCHllRLbCLajpC0uDwHE0WU1Lxo,24
9
- database_wrapper_sqlite-0.3.146.dist-info/RECORD,,