database-wrapper-sqlite 0.2.38__tar.gz → 0.3.147__tar.gz

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.
Files changed (20) hide show
  1. database_wrapper_sqlite-0.3.147/LICENSE +21 -0
  2. database_wrapper_sqlite-0.3.147/PKG-INFO +101 -0
  3. database_wrapper_sqlite-0.3.147/README.md +63 -0
  4. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite/__init__.py +16 -2
  5. database_wrapper_sqlite-0.3.147/database_wrapper_sqlite/connector.py +391 -0
  6. database_wrapper_sqlite-0.3.147/database_wrapper_sqlite/db_wrapper_sqlite_async.py +77 -0
  7. database_wrapper_sqlite-0.3.147/database_wrapper_sqlite.egg-info/PKG-INFO +101 -0
  8. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite.egg-info/SOURCES.txt +2 -0
  9. database_wrapper_sqlite-0.3.147/database_wrapper_sqlite.egg-info/requires.txt +2 -0
  10. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/pyproject.toml +12 -10
  11. database_wrapper_sqlite-0.2.38/PKG-INFO +0 -91
  12. database_wrapper_sqlite-0.2.38/README.md +0 -55
  13. database_wrapper_sqlite-0.2.38/database_wrapper_sqlite/connector.py +0 -118
  14. database_wrapper_sqlite-0.2.38/database_wrapper_sqlite.egg-info/PKG-INFO +0 -91
  15. database_wrapper_sqlite-0.2.38/database_wrapper_sqlite.egg-info/requires.txt +0 -1
  16. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite/db_wrapper_sqlite.py +0 -0
  17. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite/py.typed +0 -0
  18. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite.egg-info/dependency_links.txt +0 -0
  19. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/database_wrapper_sqlite.egg-info/top_level.txt +0 -0
  20. {database_wrapper_sqlite-0.2.38 → database_wrapper_sqlite-0.3.147}/setup.cfg +0 -0
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Gints Murāns
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: database_wrapper_sqlite
3
+ Version: 0.3.147
4
+ Summary: database_wrapper for SQLite database
5
+ Author-email: Gints Murans <gm@gm.lv>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/4Apps/py_database_wrapper
8
+ Project-URL: Documentation, https://github.com/4Apps/py_database_wrapper
9
+ Project-URL: Changes, https://github.com/4Apps/py_database_wrapper
10
+ Project-URL: Code, https://github.com/4Apps/py_database_wrapper
11
+ Project-URL: Issue Tracker, https://github.com/4Apps/py_database_wrapper/issues
12
+ Project-URL: Download, https://pypi.org/project/database_wrapper/
13
+ Keywords: database,wrapper,python,sqlite
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Programming Language :: Python :: Implementation :: CPython
27
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
28
+ Classifier: Topic :: Database
29
+ Classifier: Topic :: Database :: Front-Ends
30
+ Classifier: Topic :: Software Development
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Requires-Python: >=3.8
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: database_wrapper==0.3.147
36
+ Requires-Dist: aiosqlite
37
+ Dynamic: license-file
38
+
39
+ # database_wrapper_sqlite
40
+
41
+ _Part of the `database_wrapper` package._
42
+
43
+ This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install database_wrapper[sqlite]
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ ```python
54
+ from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
55
+
56
+ db = Sqlite({"database": "my_database.db"})
57
+ db.open()
58
+ db_wrapper = DBWrapperSqlite(db_cursor=db.cursor)
59
+
60
+ res = db_wrapper.get_by_key(MyModel(), "id", 3005)
61
+ if res:
62
+ print(f"get_by_key: {res.to_dict()}")
63
+
64
+ db.close()
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,63 @@
1
+ # database_wrapper_sqlite
2
+
3
+ _Part of the `database_wrapper` package._
4
+
5
+ This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install database_wrapper[sqlite]
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
17
+
18
+ db = Sqlite({"database": "my_database.db"})
19
+ db.open()
20
+ db_wrapper = DBWrapperSqlite(db_cursor=db.cursor)
21
+
22
+ res = db_wrapper.get_by_key(MyModel(), "id", 3005)
23
+ if res:
24
+ print(f"get_by_key: {res.to_dict()}")
25
+
26
+ db.close()
27
+ ```
28
+
29
+ ### Async
30
+
31
+ `SqliteWithPoolingAsync` has the shape of `PgsqlWithPoolingAsync`: `async with pool as
32
+ (connection, cursor)`, so code written against one runs on the other as long as its SQL does.
33
+ It opens a fresh aiosqlite connection per context rather than reusing them.
34
+
35
+ ```python
36
+ from database_wrapper_sqlite import SqliteWithPoolingAsync, DBWrapperSqliteAsync
37
+
38
+ pool = SqliteWithPoolingAsync({"database": "/srv/app/data/app.sqlite3"})
39
+ await pool.open_pool()
40
+
41
+ async with pool as (connection, cursor):
42
+ db_wrapper = DBWrapperSqliteAsync(cursor)
43
+
44
+ async with connection.transaction():
45
+ await db_wrapper.insert(MyModel(name="x"))
46
+
47
+ res = db_wrapper.get_all(MyModel(), custom_query="SELECT * FROM my_table WHERE active = 1")
48
+ async for record in res:
49
+ print(record.to_dict())
50
+ ```
51
+
52
+ Async connections differ from the sync `Sqlite` on purpose:
53
+
54
+ - Autocommit: every statement commits on its own outside `connection.transaction()`, as on a
55
+ pooled PostgreSQL connection. `isolation_level` is ignored.
56
+ - `transaction()` starts with `BEGIN IMMEDIATE`, taking the write lock up front, so a
57
+ transaction that reads before it writes cannot fail with `SQLITE_BUSY` at the write.
58
+ Nested calls are savepoints.
59
+ - `PRAGMA foreign_keys = ON` on every connection, and WAL for a file database.
60
+ - Rows are dicts; `DBWrapperSqliteAsync` uses `?` placeholders and reads inserted ids from
61
+ `lastrowid`.
62
+
63
+ `SqliteAsync` is the single-connection form, like `PgsqlAsync`.
@@ -4,13 +4,22 @@ database_wrapper_sqlite package - Sqlite database wrapper
4
4
  Part of the database_wrapper package
5
5
  """
6
6
 
7
- # Copyright 2024 Gints Murans
7
+ # Copyright 2024 Gints Murāns
8
8
 
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
  ]
@@ -0,0 +1,391 @@
1
+ import sqlite3
2
+ from collections.abc import AsyncIterator, Iterable
3
+ from contextlib import asynccontextmanager
4
+ from typing import Any, NotRequired, TypedDict, cast
5
+
6
+ import aiosqlite
7
+
8
+ from database_wrapper import DatabaseBackend
9
+
10
+
11
+ def dict_factory(cursor: sqlite3.Cursor, row: tuple) -> dict[str, Any]:
12
+ fields = [col[0] for col in cursor.description]
13
+ return dict(zip(fields, row, strict=False))
14
+
15
+
16
+ class SqliteConfig(TypedDict):
17
+ database: str
18
+ timeout: NotRequired[float]
19
+ isolation_level: NotRequired[str | None]
20
+ kwargs: NotRequired[dict[str, Any]]
21
+
22
+
23
+ class SqliteTypedDictCursor(sqlite3.Cursor):
24
+ """
25
+ Type hint wrapper only. At runtime, this is just a sqlite3.Cursor
26
+ that happens to produce dicts because of the row_factory.
27
+ """
28
+
29
+ def fetchone(self) -> dict[str, Any] | None:
30
+ return super().fetchone() # type: ignore
31
+
32
+ def fetchall(self) -> list[dict[str, Any]]:
33
+ return super().fetchall() # type: ignore
34
+
35
+ def __iter__(self) -> "SqliteTypedDictCursor":
36
+ return self
37
+
38
+ def __next__(self) -> dict[str, Any]:
39
+ return super().__next__() # type: ignore
40
+
41
+
42
+ class Sqlite(DatabaseBackend):
43
+ """
44
+ SQLite database backend
45
+
46
+ :param config: Configuration for SQLite
47
+ :type config: SqliteConfig
48
+ """
49
+
50
+ config: SqliteConfig
51
+ connection: sqlite3.Connection
52
+ cursor: SqliteTypedDictCursor
53
+
54
+ ##################
55
+ ### Connection ###
56
+ ##################
57
+
58
+ def open(self) -> None:
59
+ # Free resources
60
+ if hasattr(self, "connection") and self.connection:
61
+ self.close()
62
+
63
+ self.logger.debug("Connecting to DB")
64
+
65
+ if "kwargs" not in self.config:
66
+ self.config["kwargs"] = {}
67
+
68
+ # Default timeout to 5.0 seconds if not specified
69
+ timeout = self.config.get("timeout", 5.0)
70
+
71
+ # sqlite3's standard default is "" (deferred transactions); None would mean
72
+ # autocommit, silently turning commit()/rollback() into no-ops
73
+ isolation_level = self.config.get("isolation_level", "")
74
+
75
+ self.connection = sqlite3.connect(
76
+ self.config["database"],
77
+ timeout=timeout,
78
+ isolation_level=isolation_level,
79
+ **self.config["kwargs"],
80
+ )
81
+
82
+ # Set row factory to return dicts
83
+ self.connection.row_factory = dict_factory
84
+
85
+ # Create cursor
86
+ self.cursor = cast(SqliteTypedDictCursor, self.connection.cursor())
87
+
88
+ def ping(self) -> bool:
89
+ try:
90
+ self.cursor.execute("SELECT 1")
91
+ self.cursor.fetchone()
92
+ except Exception as e:
93
+ self.logger.debug(f"Error while pinging the database: {e}")
94
+ return False
95
+
96
+ return True
97
+
98
+ ############
99
+ ### Data ###
100
+ ############
101
+
102
+ def last_insert_id(self) -> int:
103
+ assert self.cursor, "Cursor is not initialized"
104
+ return self.cursor.lastrowid or 0
105
+
106
+ def affected_rows(self) -> int:
107
+ assert self.cursor, "Cursor is not initialized"
108
+ return self.cursor.rowcount
109
+
110
+ def commit(self) -> None:
111
+ """Commit DB queries"""
112
+ assert self.connection, "Connection is not initialized"
113
+
114
+ self.logger.debug("Commit DB queries")
115
+ self.connection.commit()
116
+
117
+ def rollback(self) -> None:
118
+ """Rollback DB queries"""
119
+ assert self.connection, "Connection is not initialized"
120
+
121
+ self.logger.debug("Rollback DB queries")
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}")
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: database_wrapper_sqlite
3
+ Version: 0.3.147
4
+ Summary: database_wrapper for SQLite database
5
+ Author-email: Gints Murans <gm@gm.lv>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/4Apps/py_database_wrapper
8
+ Project-URL: Documentation, https://github.com/4Apps/py_database_wrapper
9
+ Project-URL: Changes, https://github.com/4Apps/py_database_wrapper
10
+ Project-URL: Code, https://github.com/4Apps/py_database_wrapper
11
+ Project-URL: Issue Tracker, https://github.com/4Apps/py_database_wrapper/issues
12
+ Project-URL: Download, https://pypi.org/project/database_wrapper/
13
+ Keywords: database,wrapper,python,sqlite
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Programming Language :: Python :: Implementation :: CPython
27
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
28
+ Classifier: Topic :: Database
29
+ Classifier: Topic :: Database :: Front-Ends
30
+ Classifier: Topic :: Software Development
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Requires-Python: >=3.8
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: database_wrapper==0.3.147
36
+ Requires-Dist: aiosqlite
37
+ Dynamic: license-file
38
+
39
+ # database_wrapper_sqlite
40
+
41
+ _Part of the `database_wrapper` package._
42
+
43
+ This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install database_wrapper[sqlite]
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ ```python
54
+ from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
55
+
56
+ db = Sqlite({"database": "my_database.db"})
57
+ db.open()
58
+ db_wrapper = DBWrapperSqlite(db_cursor=db.cursor)
59
+
60
+ res = db_wrapper.get_by_key(MyModel(), "id", 3005)
61
+ if res:
62
+ print(f"get_by_key: {res.to_dict()}")
63
+
64
+ db.close()
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`.
@@ -1,8 +1,10 @@
1
+ LICENSE
1
2
  README.md
2
3
  pyproject.toml
3
4
  database_wrapper_sqlite/__init__.py
4
5
  database_wrapper_sqlite/connector.py
5
6
  database_wrapper_sqlite/db_wrapper_sqlite.py
7
+ database_wrapper_sqlite/db_wrapper_sqlite_async.py
6
8
  database_wrapper_sqlite/py.typed
7
9
  database_wrapper_sqlite.egg-info/PKG-INFO
8
10
  database_wrapper_sqlite.egg-info/SOURCES.txt
@@ -0,0 +1,2 @@
1
+ database_wrapper==0.3.147
2
+ aiosqlite
@@ -1,19 +1,21 @@
1
1
  [build-system]
2
- requires = ["setuptools >= 61.0.0"]
2
+ requires = ["setuptools >= 77.0.0"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "database_wrapper_sqlite"
7
- version = "0.2.38"
7
+ # Major.minor only; the patch is the git commit count, stamped at build time by
8
+ # scripts/set_version.bash. See scripts/version.bash for what the next release is.
9
+ version = "0.3.147"
8
10
  description = "database_wrapper for SQLite database"
9
11
  readme = "README.md"
10
12
  requires-python = ">=3.8"
11
- license = { text = "GNU General Public License v3.0 (GPL-3.0)" }
13
+ license = "MIT"
14
+ license-files = ["LICENSE"]
12
15
  authors = [{ name = "Gints Murans", email = "gm@gm.lv" }]
13
16
  classifiers = [
14
17
  "Development Status :: 4 - Beta",
15
18
  "Intended Audience :: Developers",
16
- "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
17
19
  "Operating System :: MacOS :: MacOS X",
18
20
  "Operating System :: Microsoft :: Windows",
19
21
  "Operating System :: POSIX",
@@ -32,14 +34,14 @@ classifiers = [
32
34
  "Topic :: Software Development :: Libraries :: Python Modules",
33
35
  ]
34
36
  keywords = ["database", "wrapper", "python", "sqlite"]
35
- dependencies = ["database_wrapper == 0.2.38"]
37
+ dependencies = ["database_wrapper == 0.3.147", "aiosqlite"]
36
38
 
37
39
  [project.urls]
38
- Homepage = "https://github.com/gintsmurans/py_database_wrapper"
39
- Documentation = "https://github.com/gintsmurans/py_database_wrapper"
40
- Changes = "https://github.com/gintsmurans/py_database_wrapper"
41
- Code = "https://github.com/gintsmurans/py_database_wrapper"
42
- "Issue Tracker" = "https://github.com/gintsmurans/py_database_wrapper/issues"
40
+ Homepage = "https://github.com/4Apps/py_database_wrapper"
41
+ Documentation = "https://github.com/4Apps/py_database_wrapper"
42
+ Changes = "https://github.com/4Apps/py_database_wrapper"
43
+ Code = "https://github.com/4Apps/py_database_wrapper"
44
+ "Issue Tracker" = "https://github.com/4Apps/py_database_wrapper/issues"
43
45
  Download = "https://pypi.org/project/database_wrapper/"
44
46
 
45
47
  [tool.setuptools.package-data]
@@ -1,91 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: database_wrapper_sqlite
3
- Version: 0.2.38
4
- Summary: database_wrapper for SQLite database
5
- Author-email: Gints Murans <gm@gm.lv>
6
- License: GNU General Public License v3.0 (GPL-3.0)
7
- Project-URL: Homepage, https://github.com/gintsmurans/py_database_wrapper
8
- Project-URL: Documentation, https://github.com/gintsmurans/py_database_wrapper
9
- Project-URL: Changes, https://github.com/gintsmurans/py_database_wrapper
10
- Project-URL: Code, https://github.com/gintsmurans/py_database_wrapper
11
- Project-URL: Issue Tracker, https://github.com/gintsmurans/py_database_wrapper/issues
12
- Project-URL: Download, https://pypi.org/project/database_wrapper/
13
- Keywords: database,wrapper,python,sqlite
14
- Classifier: Development Status :: 4 - Beta
15
- Classifier: Intended Audience :: Developers
16
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
- Classifier: Operating System :: MacOS :: MacOS X
18
- Classifier: Operating System :: Microsoft :: Windows
19
- Classifier: Operating System :: POSIX
20
- Classifier: Programming Language :: Python :: 3
21
- Classifier: Programming Language :: Python :: 3.8
22
- Classifier: Programming Language :: Python :: 3.9
23
- Classifier: Programming Language :: Python :: 3.10
24
- Classifier: Programming Language :: Python :: 3.11
25
- Classifier: Programming Language :: Python :: 3.12
26
- Classifier: Programming Language :: Python :: 3.13
27
- Classifier: Programming Language :: Python :: Implementation :: CPython
28
- Classifier: Programming Language :: Python :: Implementation :: PyPy
29
- Classifier: Topic :: Database
30
- Classifier: Topic :: Database :: Front-Ends
31
- Classifier: Topic :: Software Development
32
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
- Requires-Python: >=3.8
34
- Description-Content-Type: text/markdown
35
- Requires-Dist: database_wrapper==0.2.38
36
-
37
- # database_wrapper_sqlite
38
-
39
- _Part of the `database_wrapper` package._
40
-
41
- This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
42
-
43
- ## !!! IMPORTANT !!!
44
-
45
- This package is not yet implemented. The README is a placeholder for future implementation.
46
-
47
- ## Installation
48
-
49
- ```bash
50
- pip install database_wrapper[sqlite]
51
- ```
52
-
53
- ## Usage
54
-
55
- ```python
56
- from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
57
-
58
- db = Sqlite({
59
- "database": "my_database.db",
60
- })
61
- db.open()
62
- dbWrapper = DBWrapperSqlite(dbCursor=db.cursor)
63
-
64
- # Simple query
65
- aModel = MyModel()
66
- res = await dbWrapper.getByKey(
67
- aModel,
68
- "id",
69
- 3005,
70
- )
71
- if res:
72
- print(f"getByKey: {res.toDict()}")
73
- else:
74
- print("No results")
75
-
76
- # Raw query
77
- res = await dbWrapper.getAll(
78
- aModel,
79
- customQuery="""
80
- SELECT t1.*, t2.name AS other_name
81
- FROM my_table AS t1
82
- LEFT JOIN other_table AS t2 ON t1.other_id = t2.id
83
- """
84
- )
85
- async for record in res:
86
- print(f"getAll: {record.toDict()}")
87
- else:
88
- print("No results")
89
-
90
- db.close()
91
- ```
@@ -1,55 +0,0 @@
1
- # database_wrapper_sqlite
2
-
3
- _Part of the `database_wrapper` package._
4
-
5
- This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
6
-
7
- ## !!! IMPORTANT !!!
8
-
9
- This package is not yet implemented. The README is a placeholder for future implementation.
10
-
11
- ## Installation
12
-
13
- ```bash
14
- pip install database_wrapper[sqlite]
15
- ```
16
-
17
- ## Usage
18
-
19
- ```python
20
- from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
21
-
22
- db = Sqlite({
23
- "database": "my_database.db",
24
- })
25
- db.open()
26
- dbWrapper = DBWrapperSqlite(dbCursor=db.cursor)
27
-
28
- # Simple query
29
- aModel = MyModel()
30
- res = await dbWrapper.getByKey(
31
- aModel,
32
- "id",
33
- 3005,
34
- )
35
- if res:
36
- print(f"getByKey: {res.toDict()}")
37
- else:
38
- print("No results")
39
-
40
- # Raw query
41
- res = await dbWrapper.getAll(
42
- aModel,
43
- customQuery="""
44
- SELECT t1.*, t2.name AS other_name
45
- FROM my_table AS t1
46
- LEFT JOIN other_table AS t2 ON t1.other_id = t2.id
47
- """
48
- )
49
- async for record in res:
50
- print(f"getAll: {record.toDict()}")
51
- else:
52
- print("No results")
53
-
54
- db.close()
55
- ```
@@ -1,118 +0,0 @@
1
- import sqlite3
2
- from typing import Any, NotRequired, TypedDict, cast
3
-
4
- from database_wrapper import DatabaseBackend
5
-
6
-
7
- def dict_factory(cursor: sqlite3.Cursor, row: tuple) -> dict[str, Any]:
8
- fields = [col[0] for col in cursor.description]
9
- return dict(zip(fields, row, strict=False))
10
-
11
-
12
- class SqliteConfig(TypedDict):
13
- database: str
14
- timeout: NotRequired[float]
15
- isolation_level: NotRequired[str | None]
16
- kwargs: NotRequired[dict[str, Any]]
17
-
18
-
19
- class SqliteTypedDictCursor(sqlite3.Cursor):
20
- """
21
- Type hint wrapper only. At runtime, this is just a sqlite3.Cursor
22
- that happens to produce dicts because of the row_factory.
23
- """
24
-
25
- def fetchone(self) -> dict[str, Any] | None:
26
- return super().fetchone() # type: ignore
27
-
28
- def fetchall(self) -> list[dict[str, Any]]:
29
- return super().fetchall() # type: ignore
30
-
31
- def __iter__(self) -> "SqliteTypedDictCursor":
32
- return self
33
-
34
- def __next__(self) -> dict[str, Any]:
35
- return super().__next__() # type: ignore
36
-
37
-
38
- class Sqlite(DatabaseBackend):
39
- """
40
- SQLite database backend
41
-
42
- :param config: Configuration for SQLite
43
- :type config: SqliteConfig
44
- """
45
-
46
- config: SqliteConfig
47
- connection: sqlite3.Connection
48
- cursor: SqliteTypedDictCursor
49
-
50
- ##################
51
- ### Connection ###
52
- ##################
53
-
54
- def open(self) -> None:
55
- # Free resources
56
- if hasattr(self, "connection") and self.connection:
57
- self.close()
58
-
59
- self.logger.debug("Connecting to DB")
60
-
61
- if "kwargs" not in self.config:
62
- self.config["kwargs"] = {}
63
-
64
- # Default timeout to 5.0 seconds if not specified
65
- timeout = self.config.get("timeout", 5.0)
66
-
67
- # sqlite3's standard default is "" (deferred transactions); None would mean
68
- # autocommit, silently turning commit()/rollback() into no-ops
69
- isolation_level = self.config.get("isolation_level", "")
70
-
71
- self.connection = sqlite3.connect(
72
- self.config["database"],
73
- timeout=timeout,
74
- isolation_level=isolation_level,
75
- **self.config["kwargs"],
76
- )
77
-
78
- # Set row factory to return dicts
79
- self.connection.row_factory = dict_factory
80
-
81
- # Create cursor
82
- self.cursor = cast(SqliteTypedDictCursor, self.connection.cursor())
83
-
84
- def ping(self) -> bool:
85
- try:
86
- self.cursor.execute("SELECT 1")
87
- self.cursor.fetchone()
88
- except Exception as e:
89
- self.logger.debug(f"Error while pinging the database: {e}")
90
- return False
91
-
92
- return True
93
-
94
- ############
95
- ### Data ###
96
- ############
97
-
98
- def last_insert_id(self) -> int:
99
- assert self.cursor, "Cursor is not initialized"
100
- return self.cursor.lastrowid or 0
101
-
102
- def affected_rows(self) -> int:
103
- assert self.cursor, "Cursor is not initialized"
104
- return self.cursor.rowcount
105
-
106
- def commit(self) -> None:
107
- """Commit DB queries"""
108
- assert self.connection, "Connection is not initialized"
109
-
110
- self.logger.debug("Commit DB queries")
111
- self.connection.commit()
112
-
113
- def rollback(self) -> None:
114
- """Rollback DB queries"""
115
- assert self.connection, "Connection is not initialized"
116
-
117
- self.logger.debug("Rollback DB queries")
118
- self.connection.rollback()
@@ -1,91 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: database_wrapper_sqlite
3
- Version: 0.2.38
4
- Summary: database_wrapper for SQLite database
5
- Author-email: Gints Murans <gm@gm.lv>
6
- License: GNU General Public License v3.0 (GPL-3.0)
7
- Project-URL: Homepage, https://github.com/gintsmurans/py_database_wrapper
8
- Project-URL: Documentation, https://github.com/gintsmurans/py_database_wrapper
9
- Project-URL: Changes, https://github.com/gintsmurans/py_database_wrapper
10
- Project-URL: Code, https://github.com/gintsmurans/py_database_wrapper
11
- Project-URL: Issue Tracker, https://github.com/gintsmurans/py_database_wrapper/issues
12
- Project-URL: Download, https://pypi.org/project/database_wrapper/
13
- Keywords: database,wrapper,python,sqlite
14
- Classifier: Development Status :: 4 - Beta
15
- Classifier: Intended Audience :: Developers
16
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
- Classifier: Operating System :: MacOS :: MacOS X
18
- Classifier: Operating System :: Microsoft :: Windows
19
- Classifier: Operating System :: POSIX
20
- Classifier: Programming Language :: Python :: 3
21
- Classifier: Programming Language :: Python :: 3.8
22
- Classifier: Programming Language :: Python :: 3.9
23
- Classifier: Programming Language :: Python :: 3.10
24
- Classifier: Programming Language :: Python :: 3.11
25
- Classifier: Programming Language :: Python :: 3.12
26
- Classifier: Programming Language :: Python :: 3.13
27
- Classifier: Programming Language :: Python :: Implementation :: CPython
28
- Classifier: Programming Language :: Python :: Implementation :: PyPy
29
- Classifier: Topic :: Database
30
- Classifier: Topic :: Database :: Front-Ends
31
- Classifier: Topic :: Software Development
32
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
- Requires-Python: >=3.8
34
- Description-Content-Type: text/markdown
35
- Requires-Dist: database_wrapper==0.2.38
36
-
37
- # database_wrapper_sqlite
38
-
39
- _Part of the `database_wrapper` package._
40
-
41
- This python package is a database wrapper for [sqlite](https://www.sqlite.org/) database.
42
-
43
- ## !!! IMPORTANT !!!
44
-
45
- This package is not yet implemented. The README is a placeholder for future implementation.
46
-
47
- ## Installation
48
-
49
- ```bash
50
- pip install database_wrapper[sqlite]
51
- ```
52
-
53
- ## Usage
54
-
55
- ```python
56
- from database_wrapper_sqlite import Sqlite, DBWrapperSqlite
57
-
58
- db = Sqlite({
59
- "database": "my_database.db",
60
- })
61
- db.open()
62
- dbWrapper = DBWrapperSqlite(dbCursor=db.cursor)
63
-
64
- # Simple query
65
- aModel = MyModel()
66
- res = await dbWrapper.getByKey(
67
- aModel,
68
- "id",
69
- 3005,
70
- )
71
- if res:
72
- print(f"getByKey: {res.toDict()}")
73
- else:
74
- print("No results")
75
-
76
- # Raw query
77
- res = await dbWrapper.getAll(
78
- aModel,
79
- customQuery="""
80
- SELECT t1.*, t2.name AS other_name
81
- FROM my_table AS t1
82
- LEFT JOIN other_table AS t2 ON t1.other_id = t2.id
83
- """
84
- )
85
- async for record in res:
86
- print(f"getAll: {record.toDict()}")
87
- else:
88
- print("No results")
89
-
90
- db.close()
91
- ```
@@ -1 +0,0 @@
1
- database_wrapper==0.2.38