postgreslite 0.1.3__tar.gz → 0.2.0__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.
@@ -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,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,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ PostgresLite.egg-info/PKG-INFO
5
+ PostgresLite.egg-info/SOURCES.txt
6
+ PostgresLite.egg-info/dependency_links.txt
7
+ PostgresLite.egg-info/requires.txt
8
+ PostgresLite.egg-info/top_level.txt
9
+ postgreslite/__init__.py
10
+ postgreslite/handler.py
11
+ postgreslite/pool.py
12
+ tests/test_file.py
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pyright>=1.1.401
4
+ ruff>=0.11.13
5
+ toml>=0.10.2
@@ -0,0 +1,5 @@
1
+ # ruff: noqa: F403
2
+ from .handler import *
3
+ from .pool import *
4
+
5
+ __version__ = "0.2.0"
@@ -2,7 +2,7 @@ import sqlite3
2
2
  import asyncio
3
3
 
4
4
  from .pool import PoolConnection, AsyncPoolConnection
5
- from datetime import datetime, date
5
+ from datetime import datetime, date, UTC
6
6
 
7
7
  __all__ = (
8
8
  "PostgresLite",
@@ -10,12 +10,12 @@ __all__ = (
10
10
 
11
11
 
12
12
  class CustomCursor(sqlite3.Cursor):
13
- def __init__(self, *args, **kwargs):
13
+ def __init__(self, *args, **kwargs): # noqa: ANN002
14
14
  super().__init__(*args, **kwargs)
15
15
 
16
16
 
17
17
  def dict_factory(cursor: sqlite3.Cursor, row: list) -> dict:
18
- """ Convert SQLite3 data to dict """
18
+ """ Convert SQLite3 data to dict. """
19
19
  d = {}
20
20
  for index, col in enumerate(cursor.description):
21
21
  d[col[0]] = row[index]
@@ -26,19 +26,18 @@ class PostgresLite:
26
26
  def __init__(
27
27
  self,
28
28
  filename: str = "storage.db",
29
- loop: asyncio.AbstractEventLoop = None
29
+ loop: asyncio.AbstractEventLoop | None = None
30
30
  ):
31
31
  self._prepare_settings()
32
32
  self._filename = filename
33
33
 
34
- if filename != ":memory:":
35
- if not filename.endswith(".db"):
36
- raise ValueError("Database filename must end with '.db'")
34
+ if filename != ":memory:" and not filename.endswith(".db"):
35
+ raise ValueError("Database filename must end with '.db'")
37
36
 
38
37
  self.loop = loop or asyncio.get_event_loop()
39
38
 
40
39
  def connect(self) -> PoolConnection:
41
- """ Makes a connection to the database and returns the pool (sync) """
40
+ """ Makes a connection to the database and returns the pool (sync). """
42
41
  conn = sqlite3.connect(
43
42
  self._filename,
44
43
  isolation_level=None,
@@ -49,8 +48,8 @@ class PostgresLite:
49
48
  db = conn.cursor()
50
49
  return PoolConnection(db)
51
50
 
52
- async def connect_async(self) -> AsyncPoolConnection:
53
- """ Makes a connection to the database and returns the pool (async) """
51
+ def connect_async(self) -> AsyncPoolConnection:
52
+ """ Makes a connection to the database and returns the pool (async). """
54
53
  conn = sqlite3.connect(
55
54
  self._filename,
56
55
  isolation_level=None,
@@ -60,36 +59,33 @@ class PostgresLite:
60
59
 
61
60
  conn.row_factory = dict_factory
62
61
  db = conn.cursor()
63
- pool = AsyncPoolConnection(db, self.loop)
64
- pool._task = self.loop.create_task(pool._queue_manager())
65
-
66
- return pool
62
+ return AsyncPoolConnection(db, self.loop)
67
63
 
68
64
  def _prepare_settings(self) -> None:
69
- """ Prepare SQLite settings for better experience """
65
+ """ Prepare SQLite settings for better experience. """
70
66
 
71
- def adapt_date_iso(val) -> str:
67
+ def adapt_date_iso(val: date) -> str:
72
68
  """Adapt datetime.date to ISO 8601 date."""
73
69
  return val.isoformat()
74
70
 
75
- def adapt_datetime_iso(val) -> str:
71
+ def adapt_datetime_iso(val: datetime) -> str:
76
72
  """Adapt datetime.datetime to timezone-naive ISO 8601 date."""
77
73
  return val.isoformat()
78
74
 
79
75
  sqlite3.register_adapter(date, adapt_date_iso)
80
76
  sqlite3.register_adapter(datetime, adapt_datetime_iso)
81
77
 
82
- def convert_date(val) -> date:
78
+ def convert_date(val: bytes) -> date:
83
79
  """Convert ISO 8601 date to datetime.date object."""
84
80
  return date.fromisoformat(val.decode())
85
81
 
86
- def convert_datetime(val) -> datetime:
82
+ def convert_datetime(val: bytes) -> datetime:
87
83
  """Convert ISO 8601 datetime to datetime.datetime object."""
88
84
  return datetime.fromisoformat(val.decode())
89
85
 
90
- def convert_timestamp(val) -> datetime:
86
+ def convert_timestamp(val: bytes) -> datetime:
91
87
  """Convert Unix epoch timestamp to datetime.datetime object."""
92
- return datetime.fromtimestamp(int(val))
88
+ return datetime.fromtimestamp(int(val), tz=UTC)
93
89
 
94
90
  sqlite3.register_converter("date", convert_date)
95
91
  sqlite3.register_converter("datetime", convert_datetime)
@@ -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,171 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.pdm.source]
6
+ name = "public"
7
+ url = "https://github.com/AlexFlipnote/PostgresLite"
8
+
9
+ [project]
10
+ name = "PostgresLite"
11
+ description = "Python SQLite combined with syntax compared to asyncpg progject."
12
+ requires-python = ">=3.11.0"
13
+ license = "MIT"
14
+
15
+ dynamic = ["version"]
16
+ readme = "README.md"
17
+ keywords = ["asyncpg", "sqlite", "postgres", "lite", "database", "sql"]
18
+ authors = [{name = "AlexFlipnote", email = "root@alexflipnote.dev"}]
19
+
20
+ dependencies = []
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/AlexFlipnote/PostgresLite"
24
+ Repository = "https://github.com/AlexFlipnote/PostgresLite"
25
+
26
+ [project.optional-dependencies]
27
+ dev = [
28
+ "pyright>=1.1.401",
29
+ "ruff>=0.11.13",
30
+ "toml>=0.10.2",
31
+ ]
32
+
33
+ [tool.setuptools]
34
+ packages = [
35
+ "postgreslite",
36
+ ]
37
+
38
+ [tool.setuptools.dynamic]
39
+ version = {attr = "postgreslite.__version__"}
40
+ readme = {file = ["README.md"]}
41
+
42
+ [tool.ruff]
43
+ target-version = "py311"
44
+ indent-width = 4
45
+ line-length = 256 # Debating to change this.. not sure yet
46
+ output-format = "concise"
47
+
48
+ # Files to include/exclude
49
+ include = [
50
+ "postgreslite/*.py",
51
+ ]
52
+
53
+ exclude = [
54
+ "**/__pycache__",
55
+ "**/*.pyc",
56
+ "*.egg-info",
57
+ ".venv",
58
+ "build",
59
+ "docs",
60
+ "dist",
61
+ "examples",
62
+ "tests",
63
+ ]
64
+
65
+ [tool.ruff.lint]
66
+ select = [
67
+ "A", # flake8-builtins
68
+ "ANN", # Annotations
69
+ "ARG", # flake8-unused-arguments
70
+ "B", # flake8-bugbear
71
+ "D", # pydocstyle
72
+ "DTZ", # flake8-datetimez
73
+ "E", # Error
74
+ "ERA", # eradicate
75
+ "F", # Pyflakes
76
+ "FIX", # flake8-fixme
77
+ "FLY", # flynt
78
+ "FURB", # refurb
79
+ "ICN", # flake8-import-conventions
80
+ "ISC", # flake8-implicit-str-concat
81
+ "N", # pep8-naming
82
+ "PIE", # flake8-pie
83
+ "PLE", # Pylint Errors
84
+ "PLW", # Pylint Warnings
85
+ "Q", # flake8-quotes
86
+ "RET", # flake8-return
87
+ "RUF", # Ruff-specific rules
88
+ "SIM", # flake8-simplify
89
+ "T", # flake8-print
90
+ "TC", # type-checking
91
+ "UP", # pyupgrade
92
+ "W", # Warning
93
+ ]
94
+
95
+ extend-select = ["W", "E"]
96
+ preview = true
97
+
98
+ ignore = [
99
+ # Docstring: function
100
+ "D100", # docstring in public module
101
+ "D104", # Missing docstring in public package
102
+ "D203", # 1 blank line required before class docstring
103
+ "D204", # 1 blank line required after class docstring
104
+ "D210", # No whitespaces surrounding docstring text
105
+ "D212", # Multi-line docstring start at first line
106
+ "D400", # Strictly must end with a period
107
+ "D401", # First line should be in imperative mood
108
+ "D413", # Missing blank line after last section
109
+ "D416", # Section name should end with a colon
110
+
111
+ # Annotations
112
+ "ANN003", # Missing type annotation for **kwargs
113
+ "ANN204", # Missing for __init__ method
114
+
115
+ # Type-checking
116
+ "TC001", "TC002", "TC003", "TC004", # Moving imports
117
+
118
+ # Docstring: Missing docs
119
+ "D101", # class
120
+ "D105", # magic method docstring required (__str__, __int__, etc)
121
+ "D107", # __init__ docstring required
122
+
123
+ # Except cases
124
+ "B904", # raise in except
125
+
126
+ # Simplify
127
+ "SIM105", # Use contextlib.suppress
128
+ "SIM114", # Merge if-else to one-liner
129
+
130
+ # Refurb
131
+ "FURB101", # read-whole-file
132
+ "FURB103", # write-whole-file
133
+
134
+ # Pylint Warnings
135
+ "PLW2901", # Overwrite loop control variable
136
+
137
+ # Type hints
138
+ "UP037", # type hints with quotes
139
+
140
+ # Variable shadowing
141
+ "A005", # Files
142
+ ]
143
+
144
+ [tool.ruff.format]
145
+ quote-style = "double"
146
+ indent-style = "space"
147
+ line-ending = "auto"
148
+
149
+ [tool.pyright]
150
+ reportOptionalOperand = "none"
151
+ reportOptionalSubscript = "none"
152
+ reportOptionalMemberAccess = "none"
153
+ reportUnnecessaryTypeIgnoreComment = "warning"
154
+ typeCheckingMode = "basic"
155
+ pythonVersion = "3.11"
156
+
157
+ include = [
158
+ "postgreslite",
159
+ ]
160
+
161
+ exclude = [
162
+ "**/__pycache__",
163
+ "**/*.pyc",
164
+ "*.egg-info",
165
+ ".venv",
166
+ "build",
167
+ "docs",
168
+ "dist",
169
+ "examples",
170
+ "tests",
171
+ ]
@@ -0,0 +1,9 @@
1
+ from postgreslite import PostgresLite
2
+
3
+ pool = PostgresLite("./test_file.db").connect()
4
+
5
+ test = pool.run_sql("./test_file.sql")
6
+ print(test)
7
+
8
+ pool.execute("INSERT INTO users (name) VALUES (?)", "AlexFlipnote")
9
+ print(pool.fetch("SELECT * FROM users"))
@@ -1,6 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: postgreslite
3
- Version: 0.1.3
4
- Summary: Python SQLite combined with syntax compared to asyncpg progject.
5
- Author: AlexFlipnote
6
- License-File: LICENSE
@@ -1,5 +0,0 @@
1
- # flake8: noqa
2
- from .handler import *
3
- from .pool import *
4
-
5
- __version__ = "0.1.3"
@@ -1,149 +0,0 @@
1
- import sqlite3
2
- import asyncio
3
-
4
- from typing import Any
5
-
6
- __all__ = (
7
- "PoolConnection",
8
- "AsyncPoolConnection",
9
- "SQLStatements",
10
- )
11
-
12
-
13
- class SQLStatements:
14
- def __init__(self, *args: Any):
15
- self._args = args
16
-
17
- @property
18
- def prepared(self) -> tuple:
19
- """ Prepare statements for SQLite with *args provided from earlier """
20
- arg_len = len(self._args)
21
-
22
- if arg_len <= 0:
23
- return ()
24
- return self._args
25
-
26
-
27
- class PoolConnection:
28
- def __init__(
29
- self,
30
- pool: sqlite3.Connection
31
- ):
32
- self._pool = pool
33
-
34
- def _init_executor(self, query: str, *args: Any) -> sqlite3.Cursor:
35
- """ Initialize SQL executor with args for 'Prepared Statements' """
36
- prep = SQLStatements(*args)
37
- data = self._pool.execute(query, prep.prepared)
38
- return data
39
-
40
- def execute(self, query: str, *args: Any) -> str:
41
- """ Execute SQL command with args for 'Prepared Statements' """
42
- data = self._init_executor(query, *args)
43
-
44
- status_word = query.strip().split(" ")[0].upper()
45
- status_code = data.rowcount if data.rowcount > 0 else 0
46
- if status_word == "SELECT":
47
- status_code = len(data.fetchall())
48
-
49
- return f"{status_word} {status_code}"
50
-
51
- def fetch(self, query: str, *args: Any) -> list:
52
- """ Fetch DB data with args for 'Prepared Statements' """
53
- return self._init_executor(query, *args).fetchall()
54
-
55
- def fetchrow(self, query: str, *args: Any) -> dict:
56
- """ Fetch DB row (one row only) with args for 'Prepared Statements' """
57
- return self._init_executor(query, *args).fetchone()
58
-
59
-
60
- class AsyncPoolConnection(PoolConnection):
61
- def __init__(
62
- self,
63
- pool: sqlite3.Connection,
64
- loop: asyncio.AbstractEventLoop
65
- ):
66
- super().__init__(pool)
67
- self.loop = loop
68
-
69
- self._queue = asyncio.Queue()
70
- self._task: asyncio.Task = None
71
-
72
- async def _queue_manager(self):
73
- while True:
74
- query, args, future = await self._queue.get()
75
-
76
- try:
77
- await self._background_task(query, *args, future=future)
78
- except Exception:
79
- pass
80
-
81
- self._queue.task_done()
82
-
83
- async def _background_task(self, query: str, *args: Any, future: asyncio.Future) -> None:
84
- prep = SQLStatements(*args)
85
-
86
- try:
87
- cursor: sqlite3.Cursor = await self.loop.run_in_executor(
88
- None,
89
- self._pool.execute,
90
- query,
91
- prep.prepared
92
- )
93
-
94
- future.set_result(cursor)
95
- except Exception as e:
96
- future.set_exception(e)
97
-
98
- async def _init_executor(self, query: str, *args: Any) -> sqlite3.Cursor:
99
- """ Initialize SQL executor with args for 'Prepared Statements' """
100
- future = self.loop.create_future()
101
- await self._queue.put((query, args, future))
102
-
103
- try:
104
- return await future
105
- except Exception:
106
- raise future.exception()
107
-
108
- @property
109
- def queue_size(self) -> int:
110
- """ Get the size of the queue """
111
- return self._queue.qsize()
112
-
113
- async def close(self) -> None:
114
- """ Close the connection """
115
- await self._queue.join()
116
- self._task.cancel()
117
- self._pool.close()
118
-
119
- async def execute(self, query: str, *args: Any) -> str:
120
- """ Execute SQL command with args for 'Prepared Statements' """
121
- try:
122
- data = await self._init_executor(query, *args)
123
- except Exception as e:
124
- raise e
125
-
126
- status_word = query.strip().split(" ")[0].upper()
127
- status_code = data.rowcount if data.rowcount > 0 else 0
128
- if status_word == "SELECT":
129
- status_code = len(data.fetchall())
130
-
131
- return f"{status_word} {status_code}"
132
-
133
- async def fetch(self, query: str, *args: Any) -> list:
134
- """ Fetch DB data with args for 'Prepared Statements' """
135
- try:
136
- data = await self._init_executor(query, *args)
137
- except Exception as e:
138
- raise e
139
-
140
- return data.fetchall()
141
-
142
- async def fetchrow(self, query: str, *args: Any) -> dict:
143
- """ Fetch DB row (one row only) with args for 'Prepared Statements' """
144
- try:
145
- data = await self._init_executor(query, *args)
146
- except Exception as e:
147
- raise e
148
-
149
- return data.fetchone()
@@ -1,6 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: postgreslite
3
- Version: 0.1.3
4
- Summary: Python SQLite combined with syntax compared to asyncpg progject.
5
- Author: AlexFlipnote
6
- License-File: LICENSE
@@ -1,10 +0,0 @@
1
- LICENSE
2
- README.md
3
- setup.py
4
- postgreslite/__init__.py
5
- postgreslite/handler.py
6
- postgreslite/pool.py
7
- postgreslite.egg-info/PKG-INFO
8
- postgreslite.egg-info/SOURCES.txt
9
- postgreslite.egg-info/dependency_links.txt
10
- postgreslite.egg-info/top_level.txt
@@ -1,18 +0,0 @@
1
- import re
2
-
3
- from setuptools import setup
4
-
5
-
6
- version = ""
7
- with open("postgreslite/__init__.py") as f:
8
- version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
9
-
10
-
11
- setup(
12
- name="postgreslite",
13
- author="AlexFlipnote",
14
- version=version,
15
- packages=["postgreslite"],
16
- description="Python SQLite combined with syntax compared to asyncpg progject.",
17
- include_package_data=True
18
- )
File without changes
File without changes
File without changes