postgreslite 0.2.0__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.
@@ -0,0 +1,5 @@
1
+ # ruff: noqa: F403
2
+ from .handler import *
3
+ from .pool import *
4
+
5
+ __version__ = "0.2.0"
@@ -0,0 +1,92 @@
1
+ import sqlite3
2
+ import asyncio
3
+
4
+ from .pool import PoolConnection, AsyncPoolConnection
5
+ from datetime import datetime, date, UTC
6
+
7
+ __all__ = (
8
+ "PostgresLite",
9
+ )
10
+
11
+
12
+ class CustomCursor(sqlite3.Cursor):
13
+ def __init__(self, *args, **kwargs): # noqa: ANN002
14
+ super().__init__(*args, **kwargs)
15
+
16
+
17
+ def dict_factory(cursor: sqlite3.Cursor, row: list) -> dict:
18
+ """ Convert SQLite3 data to dict. """
19
+ d = {}
20
+ for index, col in enumerate(cursor.description):
21
+ d[col[0]] = row[index]
22
+ return d
23
+
24
+
25
+ class PostgresLite:
26
+ def __init__(
27
+ self,
28
+ filename: str = "storage.db",
29
+ loop: asyncio.AbstractEventLoop | None = None
30
+ ):
31
+ self._prepare_settings()
32
+ self._filename = filename
33
+
34
+ if filename != ":memory:" and not filename.endswith(".db"):
35
+ raise ValueError("Database filename must end with '.db'")
36
+
37
+ self.loop = loop or asyncio.get_event_loop()
38
+
39
+ def connect(self) -> PoolConnection:
40
+ """ Makes a connection to the database and returns the pool (sync). """
41
+ conn = sqlite3.connect(
42
+ self._filename,
43
+ isolation_level=None,
44
+ detect_types=sqlite3.PARSE_DECLTYPES
45
+ )
46
+
47
+ conn.row_factory = dict_factory
48
+ db = conn.cursor()
49
+ return PoolConnection(db)
50
+
51
+ def connect_async(self) -> AsyncPoolConnection:
52
+ """ Makes a connection to the database and returns the pool (async). """
53
+ conn = sqlite3.connect(
54
+ self._filename,
55
+ isolation_level=None,
56
+ check_same_thread=False,
57
+ detect_types=sqlite3.PARSE_DECLTYPES
58
+ )
59
+
60
+ conn.row_factory = dict_factory
61
+ db = conn.cursor()
62
+ return AsyncPoolConnection(db, self.loop)
63
+
64
+ def _prepare_settings(self) -> None:
65
+ """ Prepare SQLite settings for better experience. """
66
+
67
+ def adapt_date_iso(val: date) -> str:
68
+ """Adapt datetime.date to ISO 8601 date."""
69
+ return val.isoformat()
70
+
71
+ def adapt_datetime_iso(val: datetime) -> str:
72
+ """Adapt datetime.datetime to timezone-naive ISO 8601 date."""
73
+ return val.isoformat()
74
+
75
+ sqlite3.register_adapter(date, adapt_date_iso)
76
+ sqlite3.register_adapter(datetime, adapt_datetime_iso)
77
+
78
+ def convert_date(val: bytes) -> date:
79
+ """Convert ISO 8601 date to datetime.date object."""
80
+ return date.fromisoformat(val.decode())
81
+
82
+ def convert_datetime(val: bytes) -> datetime:
83
+ """Convert ISO 8601 datetime to datetime.datetime object."""
84
+ return datetime.fromisoformat(val.decode())
85
+
86
+ def convert_timestamp(val: bytes) -> datetime:
87
+ """Convert Unix epoch timestamp to datetime.datetime object."""
88
+ return datetime.fromtimestamp(int(val), tz=UTC)
89
+
90
+ sqlite3.register_converter("date", convert_date)
91
+ sqlite3.register_converter("datetime", convert_datetime)
92
+ sqlite3.register_converter("timestamp", convert_timestamp)
postgreslite/pool.py ADDED
@@ -0,0 +1,281 @@
1
+ import sqlite3
2
+ import re
3
+ import asyncio
4
+
5
+ from typing import Any
6
+
7
+ __all__ = (
8
+ "AsyncPoolConnection",
9
+ "PoolConnection",
10
+ "SQLStatements",
11
+ )
12
+
13
+ re_asyncpg_arg = re.compile(r"\$(\d+)")
14
+
15
+
16
+ class SQLStatements:
17
+ def __init__(self, query: str, *args: Any): # noqa: ANN401
18
+ self._raw_query = query
19
+ self._args = args
20
+
21
+ def is_asyncpg(self) -> bool:
22
+ """ Check if the query is prepared for asyncpg. """
23
+ return re_asyncpg_arg.search(self._raw_query) is not None
24
+
25
+ @property
26
+ def query(self) -> str:
27
+ """ Returns the query, and replaces asyncpg placeholders with SQLite placeholders. """
28
+ return re_asyncpg_arg.sub(r"?", self._raw_query)
29
+
30
+ @property
31
+ def prepared(self) -> tuple:
32
+ """ Prepare statements for SQLite with *args provided from earlier. """
33
+ arg_len = len(self._args)
34
+
35
+ if arg_len <= 0:
36
+ return ()
37
+
38
+ if self.is_asyncpg():
39
+ args = self._args
40
+ return tuple(
41
+ args[int(match.group(1)) - 1]
42
+ for match in re_asyncpg_arg.finditer(self._raw_query)
43
+ )
44
+
45
+ return self._args
46
+
47
+
48
+ class PoolConnection:
49
+ def __init__(
50
+ self,
51
+ pool: sqlite3.Cursor
52
+ ):
53
+ self._pool = pool
54
+
55
+ def _init_executor(self, query: str, *args: Any) -> sqlite3.Cursor: # noqa: ANN401
56
+ """ Initialize SQL executor with args for 'Prepared Statements'. """
57
+ prep = SQLStatements(query, *args)
58
+ return self._pool.execute(prep.query, prep.prepared)
59
+
60
+ def execute(self, query: str, *args: Any) -> str: # noqa: ANN401
61
+ """
62
+ Execute SQL command with args for 'Prepared Statements'.
63
+
64
+ Parameters
65
+ ----------
66
+ query
67
+ The query to execute.
68
+ *args
69
+ The arguments to pass to the query.
70
+
71
+ Returns
72
+ -------
73
+ str
74
+ The status of the query.
75
+ """
76
+ data = self._init_executor(query, *args)
77
+
78
+ status_word = query.strip().split(" ")[0].upper()
79
+ status_code = max(0, data.rowcount)
80
+ if status_word == "SELECT":
81
+ status_code = len(data.fetchall())
82
+
83
+ return f"{status_word} {status_code}"
84
+
85
+ def fetch(self, query: str, *args: Any) -> list[dict]: # noqa: ANN401
86
+ """
87
+ Fetch DB data with args for 'Prepared Statements'.
88
+
89
+ Parameters
90
+ ----------
91
+ query
92
+ The query to execute.
93
+ *args
94
+ The arguments to pass to the query.
95
+
96
+ Returns
97
+ -------
98
+ list[dict]
99
+ The data from the query.
100
+ """
101
+ return self._init_executor(query, *args).fetchall()
102
+
103
+ def fetchrow(self, query: str, *args: Any) -> dict: # noqa: ANN401
104
+ """
105
+ Fetch DB row (one row only) with args for 'Prepared Statements'.
106
+
107
+ Parameters
108
+ ----------
109
+ query
110
+ The query to execute.
111
+ *args
112
+ The arguments to pass to the query.
113
+
114
+ Returns
115
+ -------
116
+ dict
117
+ The data from the query.
118
+ """
119
+ return self._init_executor(query, *args).fetchone()
120
+
121
+ def run_sql(self, filename: str, *args: Any) -> str: # noqa: ANN401
122
+ """
123
+ Run SQL file with args for 'Prepared Statements'.
124
+
125
+ Parameters
126
+ ----------
127
+ filename
128
+ The filename of the SQL file to execute.
129
+ *args
130
+ The arguments to pass to the query.
131
+
132
+ Returns
133
+ -------
134
+ str
135
+ The status of the query.
136
+ """
137
+ with open(filename, encoding="utf-8") as f:
138
+ query = f.read()
139
+ return self.execute(query, *args)
140
+
141
+
142
+ class AsyncPoolConnection(PoolConnection):
143
+ def __init__(
144
+ self,
145
+ pool: sqlite3.Cursor,
146
+ loop: asyncio.AbstractEventLoop
147
+ ):
148
+ super().__init__(pool)
149
+ self.loop = loop
150
+
151
+ self._queue = asyncio.Queue()
152
+ self._task: asyncio.Task = self.loop.create_task(
153
+ self._queue_manager()
154
+ )
155
+
156
+ async def _queue_manager(self) -> None:
157
+ while True:
158
+ query, args, future = await self._queue.get()
159
+
160
+ try:
161
+ await self._background_task(query, *args, future=future)
162
+ except Exception:
163
+ pass
164
+
165
+ self._queue.task_done()
166
+
167
+ async def _background_task(
168
+ self,
169
+ query: str,
170
+ *args: Any, # noqa: ANN401
171
+ future: asyncio.Future
172
+ ) -> None:
173
+ prep = SQLStatements(query, *args)
174
+
175
+ try:
176
+ cursor: sqlite3.Cursor = await self.loop.run_in_executor(
177
+ None,
178
+ self._pool.execute,
179
+ prep.query,
180
+ prep.prepared
181
+ )
182
+
183
+ future.set_result(cursor)
184
+ except Exception as e:
185
+ future.set_exception(e)
186
+
187
+ async def _init_executor(self, query: str, *args: Any) -> sqlite3.Cursor: # noqa: ANN401
188
+ """ Initialize SQL executor with args for 'Prepared Statements'. """
189
+ future = self.loop.create_future()
190
+ await self._queue.put((query, args, future))
191
+
192
+ try:
193
+ await future
194
+ return future.result()
195
+ except Exception as e:
196
+ raise e
197
+
198
+ @property
199
+ def queue_size(self) -> int:
200
+ """ Get the size of the queue. """
201
+ return self._queue.qsize()
202
+
203
+ async def close(self) -> None:
204
+ """ Close the connection. """
205
+ await self._queue.join()
206
+ self._task.cancel()
207
+ self._pool.close()
208
+
209
+ async def execute(self, query: str, *args: Any) -> str: # noqa: ANN401
210
+ """
211
+ Execute SQL command with args for 'Prepared Statements'.
212
+
213
+ Parameters
214
+ ----------
215
+ query
216
+ The query to execute.
217
+ *args
218
+ The arguments to pass to the query.
219
+
220
+ Returns
221
+ -------
222
+ str
223
+ The status of the query.
224
+ """
225
+ try:
226
+ data = await self._init_executor(query, *args)
227
+ except Exception as e:
228
+ raise e
229
+
230
+ status_word = query.strip().split(" ")[0].upper()
231
+ status_code = max(0, data.rowcount)
232
+ if status_word == "SELECT":
233
+ status_code = len(data.fetchall())
234
+
235
+ return f"{status_word} {status_code}"
236
+
237
+ async def fetch(self, query: str, *args: Any) -> list: # noqa: ANN401
238
+ """
239
+ Fetch DB data with args for 'Prepared Statements'.
240
+
241
+ Parameters
242
+ ----------
243
+ query
244
+ The query to execute.
245
+ *args
246
+ The arguments to pass to the query.
247
+
248
+ Returns
249
+ -------
250
+ list[dict]
251
+ The data from the query.
252
+ """
253
+ try:
254
+ data = await self._init_executor(query, *args)
255
+ except Exception as e:
256
+ raise e
257
+
258
+ return data.fetchall()
259
+
260
+ async def fetchrow(self, query: str, *args: Any) -> dict: # noqa: ANN401
261
+ """
262
+ Fetch DB row (one row only) with args for 'Prepared Statements'.
263
+
264
+ Parameters
265
+ ----------
266
+ query
267
+ The query to execute.
268
+ *args
269
+ The arguments to pass to the query.
270
+
271
+ Returns
272
+ -------
273
+ dict
274
+ The data from the query.
275
+ """
276
+ try:
277
+ data = await self._init_executor(query, *args)
278
+ except Exception as e:
279
+ raise e
280
+
281
+ return data.fetchone()
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: PostgresLite
3
+ Version: 0.2.0
4
+ Summary: Python SQLite combined with syntax compared to asyncpg progject.
5
+ Author-email: AlexFlipnote <root@alexflipnote.dev>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/AlexFlipnote/PostgresLite
8
+ Project-URL: Repository, https://github.com/AlexFlipnote/PostgresLite
9
+ Keywords: asyncpg,sqlite,postgres,lite,database,sql
10
+ Requires-Python: >=3.11.0
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: dev
14
+ Requires-Dist: pyright>=1.1.401; extra == "dev"
15
+ Requires-Dist: ruff>=0.11.13; extra == "dev"
16
+ Requires-Dist: toml>=0.10.2; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # PostgresLite
20
+ Python SQLite combined with syntax compared to asyncpg progject
21
+
22
+ This project is stillw in the early WIP ages, don't expect too much
23
+
24
+ # Install
25
+ pip install postgreslite
@@ -0,0 +1,8 @@
1
+ postgreslite/__init__.py,sha256=5C9x9AsyqfRrNoS2CpeMfMnYNkwECP-pVSEyECUcVsU,90
2
+ postgreslite/handler.py,sha256=_vP013afWxfgWxm8fAKofyKRza7BtbNktc18H6STVjo,3092
3
+ postgreslite/pool.py,sha256=8Fuzk5SaRGKuixK279D2UjnnCEB1wyWL1dAjy3bUAiI,7652
4
+ postgreslite-0.2.0.dist-info/licenses/LICENSE,sha256=sMvMRWyUL9JGAyCvEJw5lLOVRkdlCNRV3n31_JveOKE,1090
5
+ postgreslite-0.2.0.dist-info/METADATA,sha256=BIFXk16dJT2Y21v5bOv3uaTK_iUM134pJnVcQg0HvVQ,872
6
+ postgreslite-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ postgreslite-0.2.0.dist-info/top_level.txt,sha256=p7g3My1LaZ2YgpKACM6UemVN7TEVeTpQUwyJXn-IbgM,13
8
+ postgreslite-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 AlexFlipnote
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 @@
1
+ postgreslite