snake-orm 0.1.0b1__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.
- snake_orm-0.1.0b1.dist-info/METADATA +366 -0
- snake_orm-0.1.0b1.dist-info/RECORD +198 -0
- snake_orm-0.1.0b1.dist-info/WHEEL +4 -0
- snake_orm-0.1.0b1.dist-info/entry_points.txt +2 -0
- snake_orm-0.1.0b1.dist-info/licenses/LICENSE +21 -0
- snakeorm/__init__.py +214 -0
- snakeorm/advisor.py +109 -0
- snakeorm/cli/__init__.py +3 -0
- snakeorm/cli/app.py +992 -0
- snakeorm/cli/discovery.py +179 -0
- snakeorm/cli/hooks.py +86 -0
- snakeorm/compiler/__init__.py +3 -0
- snakeorm/compiler/compiler.py +330 -0
- snakeorm/connection.py +228 -0
- snakeorm/contrib/__init__.py +17 -0
- snakeorm/contrib/asgi.py +192 -0
- snakeorm/contrib/config.py +264 -0
- snakeorm/contrib/deliver.py +256 -0
- snakeorm/contrib/django.py +245 -0
- snakeorm/contrib/sidecar.py +44 -0
- snakeorm/contrib/wsgi.py +176 -0
- snakeorm/core/__init__.py +1 -0
- snakeorm/core/config.py +173 -0
- snakeorm/core/converters.py +172 -0
- snakeorm/core/exceptions.py +175 -0
- snakeorm/core/placement.py +15 -0
- snakeorm/core/sentinels.py +37 -0
- snakeorm/core/signals.py +114 -0
- snakeorm/debug/__init__.py +42 -0
- snakeorm/debug/assets/css/panel.css +616 -0
- snakeorm/debug/assets/css/snake_orm_app.css +293 -0
- snakeorm/debug/assets/img/icon.svg +5 -0
- snakeorm/debug/assets/js/history.js +425 -0
- snakeorm/debug/assets/js/language.js +283 -0
- snakeorm/debug/assets/js/panel.js +241 -0
- snakeorm/debug/assets/js/snake_orm_app.js +82 -0
- snakeorm/debug/assets/pages/cli.html +28 -0
- snakeorm/debug/assets/pages/config.html +34 -0
- snakeorm/debug/assets/pages/database_first.html +29 -0
- snakeorm/debug/assets/pages/help.html +21 -0
- snakeorm/debug/assets/pages/history.html +27 -0
- snakeorm/debug/capture.py +234 -0
- snakeorm/debug/channel.py +131 -0
- snakeorm/debug/collector.py +144 -0
- snakeorm/debug/config.py +149 -0
- snakeorm/debug/html.py +578 -0
- snakeorm/debug/matrix.py +60 -0
- snakeorm/debug/origin.py +42 -0
- snakeorm/debug/otel/__init__.py +68 -0
- snakeorm/debug/otel/context.py +43 -0
- snakeorm/debug/otel/exporter.py +277 -0
- snakeorm/debug/otel/payload.py +97 -0
- snakeorm/debug/otel/report.py +29 -0
- snakeorm/debug/otel/spans.py +393 -0
- snakeorm/debug/otel/summary.py +59 -0
- snakeorm/debug/record.py +54 -0
- snakeorm/debug/report.py +311 -0
- snakeorm/debug/testing.py +23 -0
- snakeorm/decorators/__init__.py +13 -0
- snakeorm/decorators/abstract.py +26 -0
- snakeorm/decorators/db_first.py +104 -0
- snakeorm/decorators/function.py +28 -0
- snakeorm/decorators/model.py +268 -0
- snakeorm/decorators/polymorphic.py +140 -0
- snakeorm/decorators/result.py +167 -0
- snakeorm/decorators/row.py +90 -0
- snakeorm/decorators/trigger.py +47 -0
- snakeorm/decorators/view.py +149 -0
- snakeorm/dialects/__init__.py +6 -0
- snakeorm/dialects/base.py +373 -0
- snakeorm/dialects/capabilities.py +571 -0
- snakeorm/dialects/literals.py +46 -0
- snakeorm/dialects/matrix.py +384 -0
- snakeorm/dialects/mysql.py +519 -0
- snakeorm/dialects/postgres.py +504 -0
- snakeorm/dialects/sqlite.py +417 -0
- snakeorm/drivers/__init__.py +18 -0
- snakeorm/drivers/asyncbase.py +73 -0
- snakeorm/drivers/asyncdecorators.py +244 -0
- snakeorm/drivers/asyncpool.py +228 -0
- snakeorm/drivers/asyncpsycopg.py +124 -0
- snakeorm/drivers/asyncpymysql.py +50 -0
- snakeorm/drivers/asyncsqlite.py +30 -0
- snakeorm/drivers/base.py +76 -0
- snakeorm/drivers/failures.py +181 -0
- snakeorm/drivers/logging.py +167 -0
- snakeorm/drivers/pool.py +352 -0
- snakeorm/drivers/psycopg.py +188 -0
- snakeorm/drivers/pymysql.py +176 -0
- snakeorm/drivers/savepoints.py +46 -0
- snakeorm/drivers/sqlite.py +170 -0
- snakeorm/drivers/threaded.py +143 -0
- snakeorm/drivers/timeout.py +87 -0
- snakeorm/dto/__init__.py +55 -0
- snakeorm/dto/read.py +231 -0
- snakeorm/dto/region.py +326 -0
- snakeorm/dto/resolve.py +354 -0
- snakeorm/dto/spec.py +201 -0
- snakeorm/expressions/__init__.py +88 -0
- snakeorm/expressions/conditional.py +178 -0
- snakeorm/expressions/expression.py +810 -0
- snakeorm/expressions/functions.py +71 -0
- snakeorm/expressions/keys.py +299 -0
- snakeorm/expressions/paths.py +43 -0
- snakeorm/expressions/scalar.py +293 -0
- snakeorm/expressions/window.py +248 -0
- snakeorm/fields/__init__.py +68 -0
- snakeorm/fields/check.py +79 -0
- snakeorm/fields/column.py +316 -0
- snakeorm/fields/enum.py +64 -0
- snakeorm/fields/index.py +46 -0
- snakeorm/fields/relationship.py +738 -0
- snakeorm/fields/typed.py +736 -0
- snakeorm/helpers/__init__.py +1 -0
- snakeorm/helpers/annotations.py +21 -0
- snakeorm/helpers/inheritance.py +41 -0
- snakeorm/helpers/pyliteral.py +52 -0
- snakeorm/helpers/pytype.py +50 -0
- snakeorm/introspection/__init__.py +13 -0
- snakeorm/introspection/base.py +30 -0
- snakeorm/introspection/drift.py +78 -0
- snakeorm/introspection/models.py +633 -0
- snakeorm/introspection/mysql.py +367 -0
- snakeorm/introspection/postgres.py +397 -0
- snakeorm/introspection/sqlite.py +217 -0
- snakeorm/introspection/unsupported.py +94 -0
- snakeorm/linker/__init__.py +3 -0
- snakeorm/linker/linker.py +521 -0
- snakeorm/metadata/__init__.py +41 -0
- snakeorm/metadata/check.py +37 -0
- snakeorm/metadata/column.py +201 -0
- snakeorm/metadata/enum_storage.py +33 -0
- snakeorm/metadata/fk_action.py +19 -0
- snakeorm/metadata/foreign_key.py +26 -0
- snakeorm/metadata/index.py +43 -0
- snakeorm/metadata/index_method.py +19 -0
- snakeorm/metadata/int_size.py +20 -0
- snakeorm/metadata/json_storage.py +21 -0
- snakeorm/metadata/polymorphic.py +30 -0
- snakeorm/metadata/primary_key.py +23 -0
- snakeorm/metadata/relationship.py +60 -0
- snakeorm/metadata/relationship_kind.py +43 -0
- snakeorm/metadata/routine.py +26 -0
- snakeorm/metadata/server_default.py +20 -0
- snakeorm/metadata/table.py +97 -0
- snakeorm/metadata/table_kind.py +23 -0
- snakeorm/metadata/trigger.py +62 -0
- snakeorm/metadata/type_params.py +348 -0
- snakeorm/migration/__init__.py +88 -0
- snakeorm/migration/asyncrunner.py +168 -0
- snakeorm/migration/autodetect.py +96 -0
- snakeorm/migration/ddl.py +1172 -0
- snakeorm/migration/diff.py +701 -0
- snakeorm/migration/loader.py +77 -0
- snakeorm/migration/operations.py +952 -0
- snakeorm/migration/planner.py +78 -0
- snakeorm/migration/realize.py +420 -0
- snakeorm/migration/renames.py +153 -0
- snakeorm/migration/render.py +1095 -0
- snakeorm/migration/runner.py +314 -0
- snakeorm/migration/squash.py +60 -0
- snakeorm/migration/state.py +107 -0
- snakeorm/model.py +162 -0
- snakeorm/py.typed +0 -0
- snakeorm/query/__init__.py +9 -0
- snakeorm/query/compound.py +288 -0
- snakeorm/query/join_kind.py +19 -0
- snakeorm/query/joined.py +143 -0
- snakeorm/query/query.py +1001 -0
- snakeorm/query/recursive.py +244 -0
- snakeorm/registry/__init__.py +5 -0
- snakeorm/registry/by_module.py +163 -0
- snakeorm/registry/registry.py +166 -0
- snakeorm/session/__init__.py +8 -0
- snakeorm/session/asyncsession.py +638 -0
- snakeorm/session/coercion.py +306 -0
- snakeorm/session/factory.py +29 -0
- snakeorm/session/guards.py +269 -0
- snakeorm/session/isolation.py +23 -0
- snakeorm/session/mapper.py +213 -0
- snakeorm/session/planning.py +815 -0
- snakeorm/session/retry.py +96 -0
- snakeorm/session/session.py +871 -0
- snakeorm/session/shared.py +355 -0
- snakeorm/sql/__init__.py +18 -0
- snakeorm/sql/adapt.py +104 -0
- snakeorm/sql/aggregate.py +232 -0
- snakeorm/sql/condition.py +359 -0
- snakeorm/sql/delete.py +46 -0
- snakeorm/sql/insert.py +149 -0
- snakeorm/sql/joins.py +158 -0
- snakeorm/sql/pk_subquery.py +54 -0
- snakeorm/sql/refs.py +19 -0
- snakeorm/sql/resolver.py +28 -0
- snakeorm/sql/select.py +175 -0
- snakeorm/sql/update.py +82 -0
- snakeorm/sql/value.py +552 -0
- snakeorm/times.py +276 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Decorators for the ASYNCHRONOUS driver: logging and timeout. Mirror of
|
|
2
|
+
`LoggingDriver`/`TimeoutDriver`.
|
|
3
|
+
|
|
4
|
+
There is no `AsyncPooledDriver` on purpose: in async, psycopg 3 ships its own
|
|
5
|
+
`AsyncConnectionPool`; reimplementing it would be competing to deliver less. Theirs is used and the
|
|
6
|
+
connection is handed to the driver.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import AsyncIterator, Callable, Sequence
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
|
|
15
|
+
from snakeorm.core.exceptions import SnakeDialectError
|
|
16
|
+
from snakeorm.dialects.base import SnakeDialect
|
|
17
|
+
from snakeorm.drivers.asyncbase import AsyncDriver
|
|
18
|
+
from snakeorm.drivers.logging import render_params
|
|
19
|
+
|
|
20
|
+
Writer = Callable[[str], None]
|
|
21
|
+
"""Where each line goes. It is injected: the ORM does not decide whether it is `print`, `logging` or a list."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _silent(_line: str) -> None:
|
|
25
|
+
"""Throws the line away: the default is to print nothing."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@asynccontextmanager
|
|
29
|
+
async def _logged(write: Writer, head: str) -> AsyncIterator[list[str]]:
|
|
30
|
+
"""Writes ONE line for the statement, worked or not, with how long it took either way.
|
|
31
|
+
|
|
32
|
+
Same reasoning as the synchronous twin, plus one of its own: the failing case is where the
|
|
33
|
+
elapsed time is MOST interesting —a statement that took four seconds and then died— and it was
|
|
34
|
+
the one case that never got written.
|
|
35
|
+
"""
|
|
36
|
+
started = time.monotonic()
|
|
37
|
+
outcome: list[str] = []
|
|
38
|
+
try:
|
|
39
|
+
yield outcome
|
|
40
|
+
except BaseException as error:
|
|
41
|
+
elapsed = (time.monotonic() - started) * 1000
|
|
42
|
+
write(f"{head} -> FAILED: {type(error).__name__}: {error} in {elapsed:.1f} ms")
|
|
43
|
+
raise
|
|
44
|
+
if not outcome:
|
|
45
|
+
# A transaction boundary counts no rows, so a duration would be noise on a line that is
|
|
46
|
+
# already complete. `COMMIT` stays `COMMIT`, byte for byte, which is what the tests that
|
|
47
|
+
# compare the log element by element are entitled to.
|
|
48
|
+
write(head)
|
|
49
|
+
return
|
|
50
|
+
elapsed = (time.monotonic() - started) * 1000
|
|
51
|
+
write(f"{head} -> {outcome[0]} in {elapsed:.1f} ms")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class AsyncLoggingDriver:
|
|
55
|
+
"""Wraps an `AsyncDriver` and logs every statement with its params and its duration.
|
|
56
|
+
In async the order of the coroutines is not the order of the code, so the log is sometimes the only way to know it.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
__slots__ = ("_inner", "_parameter_keys", "_write")
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
inner: AsyncDriver,
|
|
64
|
+
write: Writer = _silent,
|
|
65
|
+
*,
|
|
66
|
+
parameter_keys: frozenset[str] = frozenset(),
|
|
67
|
+
) -> None:
|
|
68
|
+
"""The same contract as `LoggingDriver`: the VALUES are opt-in, named by 0-based index.
|
|
69
|
+
|
|
70
|
+
Spelled out here rather than inherited because the two colours are separate classes, and
|
|
71
|
+
this is the half the fix originally missed — the synchronous one stopped writing user
|
|
72
|
+
values and this one carried on doing it, which is the drift the whole seam suffers from.
|
|
73
|
+
"""
|
|
74
|
+
self._inner = inner
|
|
75
|
+
self._write = write
|
|
76
|
+
self._parameter_keys = parameter_keys
|
|
77
|
+
|
|
78
|
+
def _params(self, params: Sequence[object]) -> str:
|
|
79
|
+
"""The parameters as its synchronous twin renders them: named ones shown, rest hidden."""
|
|
80
|
+
return render_params(params, self._parameter_keys)
|
|
81
|
+
|
|
82
|
+
async def fetch_all(
|
|
83
|
+
self, sql: str, params: Sequence[object]
|
|
84
|
+
) -> list[tuple[object, ...]]:
|
|
85
|
+
"""Queries, logging how many rows came back and how long it took."""
|
|
86
|
+
async with _logged(
|
|
87
|
+
self._write, f"{sql} -- params={self._params(params)}"
|
|
88
|
+
) as outcome:
|
|
89
|
+
rows = await self._inner.fetch_all(sql, params)
|
|
90
|
+
outcome.append(f"{len(rows)} row(s)")
|
|
91
|
+
return rows
|
|
92
|
+
|
|
93
|
+
async def fetch_iter(
|
|
94
|
+
self, sql: str, params: Sequence[object], *, chunk: int = 1000
|
|
95
|
+
) -> AsyncIterator[tuple[object, ...]]:
|
|
96
|
+
"""Yields the rows, logging how many were CONSUMED and how long it lasted.
|
|
97
|
+
|
|
98
|
+
It is written down at the end, as in the synchronous logging: counting beforehand would
|
|
99
|
+
require materialising, which is exactly what this path avoids, and in streaming what
|
|
100
|
+
matters is what was really walked (a `break` at the tenth row out of a million counts ten).
|
|
101
|
+
"""
|
|
102
|
+
started = time.monotonic()
|
|
103
|
+
consumed = 0
|
|
104
|
+
try:
|
|
105
|
+
async for row in self._inner.fetch_iter(sql, params, chunk=chunk):
|
|
106
|
+
consumed += 1
|
|
107
|
+
yield row
|
|
108
|
+
finally:
|
|
109
|
+
elapsed = (time.monotonic() - started) * 1000
|
|
110
|
+
self._write(
|
|
111
|
+
f"{sql} -- params={tuple(params)!r} -> {consumed} row(s) streamed "
|
|
112
|
+
f"in {elapsed:.1f} ms"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
async def execute(self, sql: str, params: Sequence[object]) -> int:
|
|
116
|
+
"""Runs the statement, logging how many rows it affected and how long it took."""
|
|
117
|
+
async with _logged(
|
|
118
|
+
self._write, f"{sql} -- params={self._params(params)}"
|
|
119
|
+
) as outcome:
|
|
120
|
+
affected = await self._inner.execute(sql, params)
|
|
121
|
+
outcome.append(f"{affected} row(s)")
|
|
122
|
+
return affected
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def last_insert_id(self) -> int:
|
|
126
|
+
"""Delegates the id of the last INSERT: a decorator does not invent, it passes through."""
|
|
127
|
+
return self._inner.last_insert_id
|
|
128
|
+
|
|
129
|
+
async def commit(self) -> None:
|
|
130
|
+
"""Commits, leaving a record of it."""
|
|
131
|
+
async with _logged(self._write, "COMMIT"):
|
|
132
|
+
await self._inner.commit()
|
|
133
|
+
|
|
134
|
+
async def rollback(self) -> None:
|
|
135
|
+
"""Rolls back, leaving a record of it."""
|
|
136
|
+
async with _logged(self._write, "ROLLBACK"):
|
|
137
|
+
await self._inner.rollback()
|
|
138
|
+
|
|
139
|
+
async def savepoint(self, name: str) -> None:
|
|
140
|
+
"""Marks a savepoint and writes it down.
|
|
141
|
+
|
|
142
|
+
It wrote NOTHING before. The class docstring of its synchronous twin says that without the
|
|
143
|
+
transaction boundaries "the log lies by omission", and this colour omitted three of them.
|
|
144
|
+
"""
|
|
145
|
+
async with _logged(self._write, f"SAVEPOINT {name}"):
|
|
146
|
+
await self._inner.savepoint(name)
|
|
147
|
+
|
|
148
|
+
async def release_savepoint(self, name: str) -> None:
|
|
149
|
+
"""Releases a savepoint and writes it down."""
|
|
150
|
+
async with _logged(self._write, f"RELEASE SAVEPOINT {name}"):
|
|
151
|
+
await self._inner.release_savepoint(name)
|
|
152
|
+
|
|
153
|
+
async def rollback_to_savepoint(self, name: str) -> None:
|
|
154
|
+
"""Rolls back to a savepoint and writes it down."""
|
|
155
|
+
async with _logged(self._write, f"ROLLBACK TO SAVEPOINT {name}"):
|
|
156
|
+
await self._inner.rollback_to_savepoint(name)
|
|
157
|
+
|
|
158
|
+
async def close(self) -> None:
|
|
159
|
+
"""Closes the driver inside."""
|
|
160
|
+
await self._inner.close()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class AsyncTimeoutDriver:
|
|
164
|
+
"""Wraps an `AsyncDriver`, pinning the connection's `statement_timeout`.
|
|
165
|
+
It is applied with `apply_to`, not in the constructor: in async you cannot await inside `__init__`.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
__slots__ = ("_inner", "_timeout_ms")
|
|
169
|
+
|
|
170
|
+
def __init__(self, inner: AsyncDriver, *, statement_timeout_ms: int) -> None:
|
|
171
|
+
self._inner = inner
|
|
172
|
+
self._timeout_ms = statement_timeout_ms
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
async def apply_to(
|
|
176
|
+
cls, inner: AsyncDriver, dialect: SnakeDialect, *, statement_timeout_ms: int
|
|
177
|
+
) -> AsyncTimeoutDriver:
|
|
178
|
+
"""Creates the decorator and LEAVES the timeout APPLIED on the connection.
|
|
179
|
+
|
|
180
|
+
Both halves of this came from copying the synchronous driver's SHAPE without its reasons.
|
|
181
|
+
The `<= 0` guard was missing — on Postgres `statement_timeout = 0` means NO LIMIT, so
|
|
182
|
+
accepting a zero does the exact opposite of what was asked — and the statement was written
|
|
183
|
+
out as Postgres SQL, which MySQL and SQLite reject.
|
|
184
|
+
"""
|
|
185
|
+
if statement_timeout_ms <= 0:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
"statement_timeout_ms has to be greater than zero: in Postgres 0 means NO limit, "
|
|
188
|
+
"so asking for 0 would switch the timeout off instead of tightening it."
|
|
189
|
+
)
|
|
190
|
+
statement = dialect.statement_timeout_sql(statement_timeout_ms)
|
|
191
|
+
if statement is None:
|
|
192
|
+
raise SnakeDialectError(
|
|
193
|
+
f"{type(dialect).__name__} has no server-side statement timeout, so this driver "
|
|
194
|
+
f"cannot cap anything on it."
|
|
195
|
+
)
|
|
196
|
+
driver = cls(inner, statement_timeout_ms=statement_timeout_ms)
|
|
197
|
+
await inner.execute(statement, ())
|
|
198
|
+
return driver
|
|
199
|
+
|
|
200
|
+
async def fetch_all(
|
|
201
|
+
self, sql: str, params: Sequence[object]
|
|
202
|
+
) -> list[tuple[object, ...]]:
|
|
203
|
+
"""Delegates the query; the limit is already set on the connection."""
|
|
204
|
+
return await self._inner.fetch_all(sql, params)
|
|
205
|
+
|
|
206
|
+
async def fetch_iter(
|
|
207
|
+
self, sql: str, params: Sequence[object], *, chunk: int = 1000
|
|
208
|
+
) -> AsyncIterator[tuple[object, ...]]:
|
|
209
|
+
"""Delegates the streaming; the limit is already set on the connection."""
|
|
210
|
+
async for row in self._inner.fetch_iter(sql, params, chunk=chunk):
|
|
211
|
+
yield row
|
|
212
|
+
|
|
213
|
+
async def execute(self, sql: str, params: Sequence[object]) -> int:
|
|
214
|
+
"""Delegates the statement."""
|
|
215
|
+
return await self._inner.execute(sql, params)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def last_insert_id(self) -> int:
|
|
219
|
+
"""Delegates the id of the last INSERT: a decorator does not invent, it passes through."""
|
|
220
|
+
return self._inner.last_insert_id
|
|
221
|
+
|
|
222
|
+
async def commit(self) -> None:
|
|
223
|
+
"""Delegates the commit."""
|
|
224
|
+
await self._inner.commit()
|
|
225
|
+
|
|
226
|
+
async def rollback(self) -> None:
|
|
227
|
+
"""Delegates the rollback."""
|
|
228
|
+
await self._inner.rollback()
|
|
229
|
+
|
|
230
|
+
async def savepoint(self, name: str) -> None:
|
|
231
|
+
"""Delegates the savepoint."""
|
|
232
|
+
await self._inner.savepoint(name)
|
|
233
|
+
|
|
234
|
+
async def release_savepoint(self, name: str) -> None:
|
|
235
|
+
"""Delegates the release of the savepoint."""
|
|
236
|
+
await self._inner.release_savepoint(name)
|
|
237
|
+
|
|
238
|
+
async def rollback_to_savepoint(self, name: str) -> None:
|
|
239
|
+
"""Delegates the return to the savepoint."""
|
|
240
|
+
await self._inner.rollback_to_savepoint(name)
|
|
241
|
+
|
|
242
|
+
async def close(self) -> None:
|
|
243
|
+
"""Closes the driver inside."""
|
|
244
|
+
await self._inner.close()
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""`AsyncSnakePool`: the async mirror of `SnakePool`, with the same three safeguards.
|
|
2
|
+
|
|
3
|
+
A server with a hundred concurrent tasks opens a hundred connections if nobody hands them out, and a
|
|
4
|
+
Postgres connection costs memory on the server even when it is doing nothing.
|
|
5
|
+
|
|
6
|
+
The three rules are the same as in the synchronous sibling:
|
|
7
|
+
|
|
8
|
+
- **`pre_ping`** — a failover or a server restart leaves dead connections IN the pool. Without
|
|
9
|
+
checking the pulse, the next request takes one and fails for something that is not its fault.
|
|
10
|
+
- **`recycle_seconds`** — many servers cut idle connections on their own. Recycling by age throws
|
|
11
|
+
them away BEFORE the server does, which is the difference between a discard and an error in
|
|
12
|
+
production.
|
|
13
|
+
- **`timeout_seconds`** — with the pool drained, `psycopg2` does not block: it raises instantly. The
|
|
14
|
+
timeout is there to WAIT for one to be freed.
|
|
15
|
+
|
|
16
|
+
And the discard cap, which is not a knob but a fuse: without it, a downed database turns this into
|
|
17
|
+
an infinite loop throwing connections away and asking for another —process alive, no errors, no
|
|
18
|
+
progress—, a failure no alert ever notices.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
|
25
|
+
from contextlib import asynccontextmanager
|
|
26
|
+
from time import monotonic
|
|
27
|
+
|
|
28
|
+
from snakeorm.core.exceptions import SnakePoolTimeout
|
|
29
|
+
from snakeorm.drivers.asyncbase import AsyncDriver
|
|
30
|
+
|
|
31
|
+
AsyncBorrow = Callable[[], Awaitable[AsyncDriver]]
|
|
32
|
+
AsyncGiveBack = Callable[[AsyncDriver], Awaitable[None]]
|
|
33
|
+
AsyncCloseAll = Callable[[], Awaitable[None]]
|
|
34
|
+
AsyncDiscard = Callable[[AsyncDriver], Awaitable[None]]
|
|
35
|
+
Clock = Callable[[], float]
|
|
36
|
+
|
|
37
|
+
_MAX_DISCARDS = 3
|
|
38
|
+
"""Dead connections in a row before giving up on retrying. Three are not bad luck: it is the database."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _AsyncPooledDriver:
|
|
42
|
+
"""Wraps the lent connection so that `close()` RETURNS it instead of closing it.
|
|
43
|
+
|
|
44
|
+
It is the piece that makes the pool work without anybody upstream noticing: an `AsyncSession`
|
|
45
|
+
closes its driver when it is done, as always, and the connection goes back into the queue.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, inner: AsyncDriver, give_back: AsyncGiveBack) -> None:
|
|
49
|
+
self._inner = inner
|
|
50
|
+
self._give_back = give_back
|
|
51
|
+
self._returned = False
|
|
52
|
+
|
|
53
|
+
async def fetch_all(
|
|
54
|
+
self, sql: str, params: Sequence[object]
|
|
55
|
+
) -> list[tuple[object, ...]]:
|
|
56
|
+
"""Delegates the read."""
|
|
57
|
+
return await self._inner.fetch_all(sql, params)
|
|
58
|
+
|
|
59
|
+
def fetch_iter(
|
|
60
|
+
self, sql: str, params: Sequence[object], *, chunk: int = 1000
|
|
61
|
+
) -> AsyncIterator[tuple[object, ...]]:
|
|
62
|
+
"""Delegates the streaming. NOT an `async def`: it returns the iterator, just like the Protocol."""
|
|
63
|
+
return self._inner.fetch_iter(sql, params, chunk=chunk)
|
|
64
|
+
|
|
65
|
+
async def execute(self, sql: str, params: Sequence[object]) -> int:
|
|
66
|
+
"""Delegates the write."""
|
|
67
|
+
return await self._inner.execute(sql, params)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def last_insert_id(self) -> int:
|
|
71
|
+
"""Delegates the id of the last INSERT."""
|
|
72
|
+
return self._inner.last_insert_id
|
|
73
|
+
|
|
74
|
+
async def commit(self) -> None:
|
|
75
|
+
"""Delegates the commit."""
|
|
76
|
+
await self._inner.commit()
|
|
77
|
+
|
|
78
|
+
async def rollback(self) -> None:
|
|
79
|
+
"""Delegates the rollback."""
|
|
80
|
+
await self._inner.rollback()
|
|
81
|
+
|
|
82
|
+
async def savepoint(self, name: str) -> None:
|
|
83
|
+
"""Delegates the savepoint."""
|
|
84
|
+
await self._inner.savepoint(name)
|
|
85
|
+
|
|
86
|
+
async def release_savepoint(self, name: str) -> None:
|
|
87
|
+
"""Delegates the release."""
|
|
88
|
+
await self._inner.release_savepoint(name)
|
|
89
|
+
|
|
90
|
+
async def rollback_to_savepoint(self, name: str) -> None:
|
|
91
|
+
"""Delegates the return to the savepoint."""
|
|
92
|
+
await self._inner.rollback_to_savepoint(name)
|
|
93
|
+
|
|
94
|
+
async def close(self) -> None:
|
|
95
|
+
"""RETURNS the connection to the pool instead of closing it, ROLLED BACK. Idempotent.
|
|
96
|
+
|
|
97
|
+
The rollback is the pool's contract and not a courtesy: `give_back` is supplied entirely by
|
|
98
|
+
the caller —the three demos in `frameworks/` file the connection into a queue and do nothing
|
|
99
|
+
else— so nothing else performs it. Task A does `await session.insert(...)`, blows up before
|
|
100
|
+
the commit, its `finally: await session.close()` files the connection away WITH the
|
|
101
|
+
transaction open and the INSERT inside it. Task B takes that connection, runs its SELECT
|
|
102
|
+
inside a stranger's unit of work, and its own `commit()` confirms the INSERT that A
|
|
103
|
+
abandoned. A savepoint is the sharpest case: the name still resolves, so
|
|
104
|
+
`rollback_to_savepoint` on a stranger's mark raises nothing and quietly undoes work.
|
|
105
|
+
|
|
106
|
+
The `finally` is the other half: the RETURN is not optional, the CLEAN-UP is what may fail.
|
|
107
|
+
A rollback that raises on a dead socket must not cost the pool a connection for ever.
|
|
108
|
+
|
|
109
|
+
Idempotency is kept: a repeated `close()` —the session's plus one from an outer `finally`—
|
|
110
|
+
would return the SAME connection twice, and from then on two tasks would each believe they
|
|
111
|
+
had their own.
|
|
112
|
+
"""
|
|
113
|
+
if self._returned:
|
|
114
|
+
return
|
|
115
|
+
self._returned = True
|
|
116
|
+
try:
|
|
117
|
+
await self._inner.rollback()
|
|
118
|
+
finally:
|
|
119
|
+
await self._give_back(self._inner)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class AsyncSnakePool:
|
|
123
|
+
"""Hands out async connections and takes them back. Engine-agnostic, like its sibling."""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
borrow: AsyncBorrow,
|
|
128
|
+
give_back: AsyncGiveBack,
|
|
129
|
+
close_all: AsyncCloseAll,
|
|
130
|
+
*,
|
|
131
|
+
discard: AsyncDiscard | None = None,
|
|
132
|
+
pre_ping: bool = False,
|
|
133
|
+
recycle_seconds: float | None = None,
|
|
134
|
+
timeout_seconds: float | None = None,
|
|
135
|
+
retry_interval: float = 0.05,
|
|
136
|
+
clock: Clock = monotonic,
|
|
137
|
+
) -> None:
|
|
138
|
+
self._borrow = borrow
|
|
139
|
+
self._give_back = give_back
|
|
140
|
+
self._close_all = close_all
|
|
141
|
+
self._discard = discard
|
|
142
|
+
self._pre_ping = pre_ping
|
|
143
|
+
self._recycle = recycle_seconds
|
|
144
|
+
self._timeout = timeout_seconds
|
|
145
|
+
self._retry_interval = retry_interval
|
|
146
|
+
self._clock = clock
|
|
147
|
+
# Per object and not per reused `id()`: `id()`s get recycled once the object dies, and the
|
|
148
|
+
# pool would end up measuring the neighbour's age.
|
|
149
|
+
self._born: dict[int, float] = {}
|
|
150
|
+
|
|
151
|
+
async def acquire(self) -> AsyncDriver:
|
|
152
|
+
"""Lends a HEALTHY connection, wrapped: closing it sends it back to the pool.
|
|
153
|
+
|
|
154
|
+
While it waits for one to be freed, it hands control of the loop back (`asyncio.sleep`)
|
|
155
|
+
instead of blocking the thread. That is the only real difference from the synchronous
|
|
156
|
+
sibling, and it is what keeps one task waiting for a connection from stopping the other
|
|
157
|
+
ninety-nine.
|
|
158
|
+
"""
|
|
159
|
+
deadline = None if self._timeout is None else self._clock() + self._timeout
|
|
160
|
+
discarded = 0
|
|
161
|
+
while True:
|
|
162
|
+
try:
|
|
163
|
+
inner = await self._borrow()
|
|
164
|
+
except Exception:
|
|
165
|
+
if deadline is None or self._clock() >= deadline:
|
|
166
|
+
if deadline is None:
|
|
167
|
+
raise
|
|
168
|
+
raise SnakePoolTimeout(
|
|
169
|
+
f"No connection came free in {self._timeout} s. The pool is "
|
|
170
|
+
f"exhausted for longer than you are willing to wait: either there is too "
|
|
171
|
+
f"much load or too little pool (or somebody is not giving their "
|
|
172
|
+
f"connections back)."
|
|
173
|
+
) from None
|
|
174
|
+
await asyncio.sleep(self._retry_interval)
|
|
175
|
+
continue
|
|
176
|
+
if await self._usable(inner):
|
|
177
|
+
self._born.setdefault(id(inner), self._clock())
|
|
178
|
+
return _AsyncPooledDriver(inner, self._give_back)
|
|
179
|
+
await self._throw_away(inner)
|
|
180
|
+
discarded += 1
|
|
181
|
+
if discarded >= _MAX_DISCARDS:
|
|
182
|
+
raise SnakePoolTimeout(
|
|
183
|
+
f"The last {discarded} connections in the pool were dead. This is not one "
|
|
184
|
+
f"connection being unlucky: the database is not answering (restart, failover, "
|
|
185
|
+
f"network?). The pool has already thrown them away; retry when it comes back."
|
|
186
|
+
)
|
|
187
|
+
if deadline is not None and self._clock() >= deadline:
|
|
188
|
+
raise SnakePoolTimeout(
|
|
189
|
+
f"No connection in the pool answered in {self._timeout} s."
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
async def _usable(self, inner: AsyncDriver) -> bool:
|
|
193
|
+
"""Any good? It looks at the AGE first (free) and then the pulse (costs a trip to the database)."""
|
|
194
|
+
if self._recycle is not None:
|
|
195
|
+
born_at = self._born.get(id(inner))
|
|
196
|
+
if born_at is not None and self._clock() - born_at >= self._recycle:
|
|
197
|
+
return False
|
|
198
|
+
if not self._pre_ping:
|
|
199
|
+
return True
|
|
200
|
+
try:
|
|
201
|
+
await inner.execute("SELECT 1", ())
|
|
202
|
+
except Exception:
|
|
203
|
+
# Any exception: the connection is broken and it does not matter why. Telling the
|
|
204
|
+
# reasons apart here would be putting one engine's jargon into the very piece that
|
|
205
|
+
# exists so as not to have it.
|
|
206
|
+
return False
|
|
207
|
+
return True
|
|
208
|
+
|
|
209
|
+
async def _throw_away(self, inner: AsyncDriver) -> None:
|
|
210
|
+
"""Takes the connection out of the pool for good. Without `discard`, it at least closes it."""
|
|
211
|
+
self._born.pop(id(inner), None)
|
|
212
|
+
if self._discard is not None:
|
|
213
|
+
await self._discard(inner)
|
|
214
|
+
else:
|
|
215
|
+
await inner.close()
|
|
216
|
+
|
|
217
|
+
@asynccontextmanager
|
|
218
|
+
async def connection(self) -> AsyncIterator[AsyncDriver]:
|
|
219
|
+
"""Lends a connection and ALWAYS returns it, even if the block blows up."""
|
|
220
|
+
driver = await self.acquire()
|
|
221
|
+
try:
|
|
222
|
+
yield driver
|
|
223
|
+
finally:
|
|
224
|
+
await driver.close()
|
|
225
|
+
|
|
226
|
+
async def close(self) -> None:
|
|
227
|
+
"""Closes every connection in the pool."""
|
|
228
|
+
await self._close_all()
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""ASYNCHRONOUS PostgreSQL driver over psycopg 3 (psycopg2 has no native async). An OPTIONAL
|
|
2
|
+
dependency (`snakeorm[async]`). The placeholder is still `%s`, so `PostgresDialect` works as it is.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import AsyncIterator, Sequence
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from snakeorm.drivers.failures import async_translating
|
|
11
|
+
from snakeorm.drivers.savepoints import quote_savepoint
|
|
12
|
+
|
|
13
|
+
from snakeorm.sql.adapt import adapt_params
|
|
14
|
+
|
|
15
|
+
_QUOTE = '"'
|
|
16
|
+
"""The character THIS engine quotes an identifier with.
|
|
17
|
+
|
|
18
|
+
MySQL and MariaDB reject a double-quoted identifier unless `ANSI_QUOTES` is on, so a shared helper
|
|
19
|
+
that always wrote a double quote turned every `SAVEPOINT` into `ERROR 1064` here. The RULE about
|
|
20
|
+
what a valid name is, is shared; the quoting character is the engine's own grammar.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AsyncPsycopgDriver:
|
|
25
|
+
"""An asynchronous connection to PostgreSQL with psycopg 3."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, connection: Any) -> None:
|
|
28
|
+
self._connection = connection
|
|
29
|
+
# Named-cursor counter: two alive at once with the same name would collide.
|
|
30
|
+
self._cursor_seq = 0
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
async def connect(cls, dsn: str) -> AsyncPsycopgDriver:
|
|
34
|
+
"""Opens the connection. Requires `snakeorm[async]` (psycopg 3) to be installed."""
|
|
35
|
+
try:
|
|
36
|
+
import psycopg
|
|
37
|
+
except (
|
|
38
|
+
ModuleNotFoundError
|
|
39
|
+
) as error: # pragma: no cover - depends on the environment
|
|
40
|
+
raise ModuleNotFoundError(
|
|
41
|
+
"The asynchronous driver needs psycopg 3: install `snakeorm[async]`. psycopg2 "
|
|
42
|
+
"has no native async, so it is no use for this."
|
|
43
|
+
) from error
|
|
44
|
+
|
|
45
|
+
# `autocommit=False`: the session drives the transactions, as in the synchronous driver.
|
|
46
|
+
return cls(await psycopg.AsyncConnection.connect(dsn, autocommit=False))
|
|
47
|
+
|
|
48
|
+
@async_translating
|
|
49
|
+
async def fetch_all(
|
|
50
|
+
self, sql: str, params: Sequence[object]
|
|
51
|
+
) -> list[tuple[object, ...]]:
|
|
52
|
+
"""Runs the query and returns every row as tuples, closing the cursor."""
|
|
53
|
+
async with self._connection.cursor() as cursor:
|
|
54
|
+
await cursor.execute(
|
|
55
|
+
sql, adapt_params(params, native_arrays=True, percent_formatting=True)
|
|
56
|
+
)
|
|
57
|
+
return [tuple(row) for row in await cursor.fetchall()]
|
|
58
|
+
|
|
59
|
+
async def fetch_iter(
|
|
60
|
+
self, sql: str, params: Sequence[object], *, chunk: int = 1000
|
|
61
|
+
) -> AsyncIterator[tuple[object, ...]]:
|
|
62
|
+
"""Yields the rows in chunks with a NAMED cursor (server-side).
|
|
63
|
+
|
|
64
|
+
On psycopg3, just as on psycopg2, the name is what makes the result stay on Postgres
|
|
65
|
+
instead of travelling to the client whole. Without it, `fetchmany` would be slicing
|
|
66
|
+
something that is already in memory and the streaming would be decorative.
|
|
67
|
+
"""
|
|
68
|
+
self._cursor_seq += 1
|
|
69
|
+
async with self._connection.cursor(
|
|
70
|
+
name=f"snake_stream_{self._cursor_seq}"
|
|
71
|
+
) as cursor:
|
|
72
|
+
cursor.itersize = chunk
|
|
73
|
+
await cursor.execute(
|
|
74
|
+
sql, adapt_params(params, native_arrays=True, percent_formatting=True)
|
|
75
|
+
)
|
|
76
|
+
while True:
|
|
77
|
+
rows = await cursor.fetchmany(chunk)
|
|
78
|
+
if not rows:
|
|
79
|
+
return
|
|
80
|
+
for row in rows:
|
|
81
|
+
yield tuple(row)
|
|
82
|
+
|
|
83
|
+
@async_translating
|
|
84
|
+
async def execute(self, sql: str, params: Sequence[object]) -> int:
|
|
85
|
+
"""Runs a statement fetching no rows and returns how many it affected."""
|
|
86
|
+
async with self._connection.cursor() as cursor:
|
|
87
|
+
await cursor.execute(
|
|
88
|
+
sql, adapt_params(params, native_arrays=True, percent_formatting=True)
|
|
89
|
+
)
|
|
90
|
+
return int(cursor.rowcount)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def last_insert_id(self) -> int:
|
|
94
|
+
"""The id of the last INSERT (see the Protocol). Unused: Postgres returns the PK through RETURNING."""
|
|
95
|
+
return 0 # Postgres returns the PK through RETURNING; this value is not used
|
|
96
|
+
|
|
97
|
+
@async_translating
|
|
98
|
+
async def commit(self) -> None:
|
|
99
|
+
"""Commits the transaction in progress."""
|
|
100
|
+
await self._connection.commit()
|
|
101
|
+
|
|
102
|
+
async def rollback(self) -> None:
|
|
103
|
+
"""Rolls back the transaction in progress."""
|
|
104
|
+
await self._connection.rollback()
|
|
105
|
+
|
|
106
|
+
async def savepoint(self, name: str) -> None:
|
|
107
|
+
"""Opens a named savepoint."""
|
|
108
|
+
await self.execute(f"SAVEPOINT {quote_savepoint(name, quote=_QUOTE)}", ())
|
|
109
|
+
|
|
110
|
+
async def release_savepoint(self, name: str) -> None:
|
|
111
|
+
"""Commits the savepoint."""
|
|
112
|
+
await self.execute(
|
|
113
|
+
f"RELEASE SAVEPOINT {quote_savepoint(name, quote=_QUOTE)}", ()
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
async def rollback_to_savepoint(self, name: str) -> None:
|
|
117
|
+
"""Goes back to the savepoint, undoing what was done since it was opened."""
|
|
118
|
+
await self.execute(
|
|
119
|
+
f"ROLLBACK TO SAVEPOINT {quote_savepoint(name, quote=_QUOTE)}", ()
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
async def close(self) -> None:
|
|
123
|
+
"""Closes the connection."""
|
|
124
|
+
await self._connection.close()
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""`AsyncPyMySQLDriver`: MySQL served as an `AsyncDriver`, on the adapter's own thread.
|
|
2
|
+
|
|
3
|
+
Unlike SQLite, here a native alternative DOES exist (`aiomysql`), and it would be better under
|
|
4
|
+
heavy concurrency: this path takes up one OS thread per connection, and the native one does not.
|
|
5
|
+
The adapter is chosen because it adds no per-engine dependency and because the concurrency it
|
|
6
|
+
gives is real —Python releases the GIL while the socket waits, so two queries from two tasks
|
|
7
|
+
really do overlap—.
|
|
8
|
+
|
|
9
|
+
Stated here so nobody has to work it out: the day the native one is wanted, it comes in as
|
|
10
|
+
another implementation of the same Protocol and nothing upstream changes. That is exactly the
|
|
11
|
+
seam this project has been defending from the start.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any, cast
|
|
17
|
+
|
|
18
|
+
from snakeorm.drivers.pymysql import PyMySQLDriver
|
|
19
|
+
from snakeorm.drivers.threaded import ThreadedAsyncDriver
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncPyMySQLDriver(ThreadedAsyncDriver):
|
|
23
|
+
"""The MySQL driver wearing the `AsyncDriver` surface.
|
|
24
|
+
|
|
25
|
+
It is the engine where `last_insert_id` really matters: MySQL has no `RETURNING` (MariaDB
|
|
26
|
+
does), so there an INSERT's autoincrement PK comes from it. The async Protocol not declaring
|
|
27
|
+
it was a time bomb waiting for precisely this file.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
async def connect(cls, **kwargs: Any) -> AsyncPyMySQLDriver:
|
|
32
|
+
"""Opens the connection with PyMySQL's kwargs (host, user, password, database, port...).
|
|
33
|
+
|
|
34
|
+
The connection is opened INSIDE the adapter's thread, just like on SQLite. PyMySQL does
|
|
35
|
+
not demand it —it only asks that two threads do not use it at once—, but opening it where
|
|
36
|
+
it is going to be used leaves ONE rule for both engines instead of an exception somebody
|
|
37
|
+
will have to remember.
|
|
38
|
+
|
|
39
|
+
And `connect` really does block (it opens a socket and negotiates): doing it on the thread
|
|
40
|
+
avoids stalling the event loop right at startup, which is when the most tasks are waiting.
|
|
41
|
+
"""
|
|
42
|
+
return await cls.open(lambda: PyMySQLDriver.connect(**kwargs))
|
|
43
|
+
|
|
44
|
+
async def server_version(self) -> str:
|
|
45
|
+
"""What the server calls itself, for the dialect to tell MariaDB from MySQL.
|
|
46
|
+
|
|
47
|
+
It goes to the thread because it is a query: the wrapped driver already knows how to ask.
|
|
48
|
+
"""
|
|
49
|
+
inner = cast("PyMySQLDriver", self._inner)
|
|
50
|
+
return await self._run(inner.server_version)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""`AsyncSQLiteDriver`: SQLite served as an `AsyncDriver`, on the adapter's own thread.
|
|
2
|
+
|
|
3
|
+
SQLite has no network protocol and its standard library is synchronous, so a "native asyncio"
|
|
4
|
+
driver does not exist: `aiosqlite`, which is the usual option, does exactly this on the inside —
|
|
5
|
+
serve the same old `sqlite3` from a thread. It is implemented here instead of depending on it
|
|
6
|
+
because the adapter was already needed for MySQL and this is five lines.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from snakeorm.drivers.sqlite import SQLiteDriver
|
|
12
|
+
from snakeorm.drivers.threaded import ThreadedAsyncDriver
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AsyncSQLiteDriver(ThreadedAsyncDriver):
|
|
16
|
+
"""The SQLite driver wearing the `AsyncDriver` surface."""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
async def connect(cls, path: str) -> AsyncSQLiteDriver:
|
|
20
|
+
"""Opens the database (a file or `:memory:`) and wraps it.
|
|
21
|
+
|
|
22
|
+
It is `async` even though opening a file waits for nobody: the opening contract has to be
|
|
23
|
+
the same as the one for networked engines, or `SnakeConnectionConfig.open_async()` would
|
|
24
|
+
need a path per engine and we would be back to two ways of doing the same thing.
|
|
25
|
+
|
|
26
|
+
The connection is opened INSIDE the adapter's thread: `sqlite3` ties every connection to
|
|
27
|
+
its creating thread, so opening it here and using it over there blew up on the first
|
|
28
|
+
`close()`.
|
|
29
|
+
"""
|
|
30
|
+
return await cls.open(lambda: SQLiteDriver.connect(path))
|