dappyr 0.1.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.
- dappyr/__init__.py +9 -0
- dappyr/asyncpg.py +130 -0
- dappyr/caching.py +87 -0
- dappyr/dappyr.py +415 -0
- dappyr/errors.py +68 -0
- dappyr/psycopg.py +112 -0
- dappyr/specifications.py +207 -0
- dappyr/sqlite3.py +131 -0
- dappyr-0.1.0.dist-info/METADATA +301 -0
- dappyr-0.1.0.dist-info/RECORD +12 -0
- dappyr-0.1.0.dist-info/WHEEL +4 -0
- dappyr-0.1.0.dist-info/licenses/LICENSE +18 -0
dappyr/__init__.py
ADDED
dappyr/asyncpg.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""The asyncpg bindings for Dappyr.
|
|
2
|
+
|
|
3
|
+
Copyright 2026 by curtissimo, llc.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import AsyncGenerator, Sequence
|
|
9
|
+
from string.templatelib import Interpolation, Template
|
|
10
|
+
from typing import Any, override
|
|
11
|
+
|
|
12
|
+
from asyncpg import Connection
|
|
13
|
+
from asyncpg.prepared_stmt import PreparedStatement
|
|
14
|
+
|
|
15
|
+
from .dappyr import Queryable as _Queryable
|
|
16
|
+
from .dappyr import QueryAsyncContextManager
|
|
17
|
+
from .dappyr import RecordAsyncIterable as _RecordAsyncIterable
|
|
18
|
+
from .errors import NoResultSqlError, StatementParametersMismatchError
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def use(connection: Connection) -> QueryAsyncContextManager:
|
|
22
|
+
"""Use an asyncpg.Connection to create a queryable context.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
A QueryAsyncContextManager.
|
|
26
|
+
|
|
27
|
+
"""
|
|
28
|
+
queryable = Queryable(connection)
|
|
29
|
+
return QueryAsyncContextManager(queryable)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def template_to_sql_and_parameters(template: Template) -> tuple[str, list[Any]]: # pyright: ignore[reportExplicitAny]
|
|
33
|
+
"""Convert a Template into a SQL string and associated SQL parameters.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
A SQL string
|
|
37
|
+
A list of associated parameters.
|
|
38
|
+
|
|
39
|
+
"""
|
|
40
|
+
sql: list[str] = []
|
|
41
|
+
parameters: list[Any] = [] # pyright: ignore[reportExplicitAny]
|
|
42
|
+
|
|
43
|
+
for part in template:
|
|
44
|
+
if isinstance(part, Interpolation):
|
|
45
|
+
parameters.append(part.value) # pyright: ignore[reportAny]
|
|
46
|
+
sql.append(f"${len(parameters)}")
|
|
47
|
+
else:
|
|
48
|
+
sql.append(part)
|
|
49
|
+
|
|
50
|
+
return "".join(sql), parameters
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Queryable(_Queryable):
|
|
54
|
+
"""A Queryable based on an asyncpg.Connection."""
|
|
55
|
+
|
|
56
|
+
connection: Connection
|
|
57
|
+
|
|
58
|
+
def __init__(self, connection: Connection) -> None:
|
|
59
|
+
"""Create an instance of the Queryable class.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
TypeError: If connection is not a Connection.
|
|
63
|
+
|
|
64
|
+
"""
|
|
65
|
+
if not isinstance(connection, Connection): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
66
|
+
message = "dappyr.asyncpg.Queryable() requires Connection object"
|
|
67
|
+
raise TypeError(message) # pyright: ignore[reportUnreachable]
|
|
68
|
+
self.connection = connection
|
|
69
|
+
|
|
70
|
+
@override
|
|
71
|
+
async def close(self) -> None:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
@override
|
|
75
|
+
async def query(self, sql: Template) -> RecordAsyncIterable:
|
|
76
|
+
query, parameters = template_to_sql_and_parameters(sql)
|
|
77
|
+
statement = await self.connection.prepare(query)
|
|
78
|
+
return RecordAsyncIterable(statement, parameters)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class RecordAsyncIterable(_RecordAsyncIterable):
|
|
82
|
+
"""An async iterable that uses an asyncpg.PreparedStatement to execute."""
|
|
83
|
+
|
|
84
|
+
parameters: Sequence[Any] # pyright: ignore[reportExplicitAny]
|
|
85
|
+
statement: PreparedStatement
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
statement: PreparedStatement,
|
|
90
|
+
parameters: Sequence[Any], # pyright: ignore[reportExplicitAny]
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Create an instance of RecordAsyncIterable for the statement and parameters.
|
|
93
|
+
|
|
94
|
+
Raises:
|
|
95
|
+
TypeError: If statement is not an asyncpg.PreparedStatement
|
|
96
|
+
TypeError: If parameters is not a sequence of Any values.
|
|
97
|
+
StatementParametersMismatchError: If the length of parameters does not match the expectations of statement.
|
|
98
|
+
|
|
99
|
+
"""
|
|
100
|
+
if not isinstance(statement, PreparedStatement): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
101
|
+
message = "dappyr.asyncpg.RecordAsyncIterable() requires PreparedStatement statement object"
|
|
102
|
+
raise TypeError(message) # pyright: ignore[reportUnreachable]
|
|
103
|
+
if not isinstance(parameters, Sequence): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
104
|
+
message = "dappyr.asy cpg.RecordAsyncIterable() requires Sequence parameters object"
|
|
105
|
+
raise TypeError(message) # pyright: ignore[reportUnreachable]
|
|
106
|
+
if len(parameters) != len(statement.get_parameters()):
|
|
107
|
+
raise StatementParametersMismatchError(
|
|
108
|
+
len(statement.get_parameters()),
|
|
109
|
+
len(parameters),
|
|
110
|
+
)
|
|
111
|
+
self.parameters = parameters
|
|
112
|
+
self.statement = statement
|
|
113
|
+
|
|
114
|
+
@override
|
|
115
|
+
async def column_names(self) -> list[str]:
|
|
116
|
+
query_attributes = self.statement.get_attributes()
|
|
117
|
+
if len(query_attributes) == 0:
|
|
118
|
+
raise NoResultSqlError(self.text)
|
|
119
|
+
return [attr.name for attr in query_attributes]
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def text(self) -> str:
|
|
123
|
+
"""The text of the SQL statement."""
|
|
124
|
+
return self.statement.get_query()
|
|
125
|
+
|
|
126
|
+
@override
|
|
127
|
+
async def __aiter__(self) -> AsyncGenerator[tuple[Any, ...]]: # pyright: ignore[reportExplicitAny]
|
|
128
|
+
records = await self.statement.fetch(*self.parameters) # pyright: ignore[reportAny]
|
|
129
|
+
for record in records:
|
|
130
|
+
yield tuple(record.values())
|
dappyr/caching.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Caching utilities for Dappyr.
|
|
2
|
+
|
|
3
|
+
Copyright 2026 by curtissimo, llc.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from string import whitespace
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Protocol, cast
|
|
8
|
+
|
|
9
|
+
from .errors import CacheKeyDoesNotExistInRecordError
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Callable, Hashable
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cache[T](handler: Callable[..., T], key_name: str = "id") -> Cacheable[T]:
|
|
16
|
+
"""Get a cacheable object for the provided handler.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
handler: A Callable that creates a value from named arguments.
|
|
20
|
+
key_name: The name of the property on the value to use as a key value in the cache.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
A Cacheable value.
|
|
24
|
+
|
|
25
|
+
"""
|
|
26
|
+
return Cache(key_name, handler)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Cache[T]:
|
|
30
|
+
"""Provides a caching mechanism when creating objects from records."""
|
|
31
|
+
|
|
32
|
+
handler: Callable[..., T]
|
|
33
|
+
key_name: str
|
|
34
|
+
lookup: dict[Hashable, T]
|
|
35
|
+
|
|
36
|
+
def __init__(self, key_name: str, handler: Callable[..., T]) -> None:
|
|
37
|
+
"""Create an instance of the cache object.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
TypeError: If key is not a string.
|
|
41
|
+
|
|
42
|
+
"""
|
|
43
|
+
if not isinstance(key_name, str): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
44
|
+
msg = "Cache requires a string key" # pyright: ignore[reportUnreachable]
|
|
45
|
+
raise TypeError(msg)
|
|
46
|
+
if len(key_name.strip(whitespace)) == 0:
|
|
47
|
+
msg = "Cache requires a non-empty string key"
|
|
48
|
+
raise TypeError(msg)
|
|
49
|
+
if not callable(handler):
|
|
50
|
+
msg = "Cache requires a callable handler" # pyright: ignore[reportUnreachable]
|
|
51
|
+
raise TypeError(msg)
|
|
52
|
+
self.key_name = key_name
|
|
53
|
+
self.handler = handler
|
|
54
|
+
self.lookup = {}
|
|
55
|
+
|
|
56
|
+
def __call__(self, **kwargs: Any) -> T: # pyright: ignore[reportExplicitAny, reportAny] # ruff: ignore[any-type]
|
|
57
|
+
"""Get or create a value in the cache.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
An instance of T either stored in the cache or created by the handler.
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
CacheKeyDoesNotExistInRecordError: Raised when kwargs does not contain key.
|
|
64
|
+
TypeError: Raised if the value for key name in kwargs is not hashable.
|
|
65
|
+
|
|
66
|
+
""" # ruff: ignore[docstring-extraneous-exception]
|
|
67
|
+
if self.key_name not in kwargs:
|
|
68
|
+
raise CacheKeyDoesNotExistInRecordError(self.key_name, kwargs)
|
|
69
|
+
|
|
70
|
+
if kwargs[self.key_name] in self.lookup:
|
|
71
|
+
return self.lookup[kwargs[self.key_name]]
|
|
72
|
+
|
|
73
|
+
item = self.handler(**kwargs)
|
|
74
|
+
self.set(cast("Hashable", kwargs[self.key_name]), item)
|
|
75
|
+
return item
|
|
76
|
+
|
|
77
|
+
def set(self, key: Hashable, value: T) -> None:
|
|
78
|
+
"""Set the value in the cache for the provided key."""
|
|
79
|
+
self.lookup[key] = value
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Cacheable[T](Protocol):
|
|
83
|
+
"""The cacheable protocol."""
|
|
84
|
+
|
|
85
|
+
def __call__(self, **kwargs: Any) -> T: # pyright: ignore[reportExplicitAny, reportAny] # ruff: ignore[any-type]
|
|
86
|
+
"""Call to get a value."""
|
|
87
|
+
...
|
dappyr/dappyr.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
"""The public API for using Dappyr.
|
|
2
|
+
|
|
3
|
+
Copyright 2026 by curtissimo, llc.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from functools import partial
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from .errors import UnknownDependencyError
|
|
13
|
+
from .specifications import CallableOrSpec, Specification
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from collections.abc import (
|
|
17
|
+
AsyncGenerator,
|
|
18
|
+
Awaitable,
|
|
19
|
+
Callable,
|
|
20
|
+
Sequence,
|
|
21
|
+
)
|
|
22
|
+
from string.templatelib import Template
|
|
23
|
+
from types import TracebackType
|
|
24
|
+
|
|
25
|
+
type SpecsArgs[T, T1, T2, T3, T4] = (
|
|
26
|
+
Callable[..., T]
|
|
27
|
+
| tuple[
|
|
28
|
+
CallableOrSpec[T1],
|
|
29
|
+
CallableOrSpec[T2],
|
|
30
|
+
Callable[[T1 | None, T2 | None], T],
|
|
31
|
+
]
|
|
32
|
+
| tuple[
|
|
33
|
+
CallableOrSpec[T1],
|
|
34
|
+
CallableOrSpec[T2],
|
|
35
|
+
CallableOrSpec[T3],
|
|
36
|
+
Callable[[T1 | None, T2 | None, T3 | None], T],
|
|
37
|
+
]
|
|
38
|
+
| tuple[
|
|
39
|
+
CallableOrSpec[T1],
|
|
40
|
+
CallableOrSpec[T2],
|
|
41
|
+
CallableOrSpec[T3],
|
|
42
|
+
CallableOrSpec[T4],
|
|
43
|
+
Callable[[T1 | None, T2 | None, T3 | None, T4 | None], T],
|
|
44
|
+
]
|
|
45
|
+
)
|
|
46
|
+
type FinalSpecsArgs[T, T1, T2, T3, T4] = (
|
|
47
|
+
tuple[Callable[..., T]]
|
|
48
|
+
| tuple[
|
|
49
|
+
Callable[[T1 | None, T2 | None], T],
|
|
50
|
+
Specification[T1],
|
|
51
|
+
Specification[T2],
|
|
52
|
+
]
|
|
53
|
+
| tuple[
|
|
54
|
+
Callable[[T1 | None, T2 | None, T3 | None], T],
|
|
55
|
+
Specification[T1],
|
|
56
|
+
Specification[T2],
|
|
57
|
+
Specification[T3],
|
|
58
|
+
]
|
|
59
|
+
| tuple[
|
|
60
|
+
Callable[[T1 | None, T2 | None, T3 | None, T4 | None], T],
|
|
61
|
+
Specification[T1],
|
|
62
|
+
Specification[T2],
|
|
63
|
+
Specification[T3],
|
|
64
|
+
Specification[T4],
|
|
65
|
+
]
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ObjectAsyncIterable[T]:
|
|
70
|
+
"""Converts data from the record async iterable to the expected object graph."""
|
|
71
|
+
|
|
72
|
+
handler: Callable[..., T]
|
|
73
|
+
record_async_iterable: RecordAsyncIterable
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
record_async_iterable: RecordAsyncIterable,
|
|
78
|
+
handler: Callable[..., T],
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Create an instance of ObjectAsyncIterable with the given iterable and handler.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
TypeError: Raised when record_async_iterable is not a RecordAsyncIterable
|
|
84
|
+
|
|
85
|
+
"""
|
|
86
|
+
if not isinstance(record_async_iterable, RecordAsyncIterable): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
87
|
+
msg = "ObjectAsyncIterable() requires RecordAsyncIterable" # pyright: ignore[reportUnreachable]
|
|
88
|
+
raise TypeError(msg)
|
|
89
|
+
if not callable(handler):
|
|
90
|
+
msg = "ObjectAsyncIterable() requires a callable handler" # pyright: ignore[reportUnreachable]
|
|
91
|
+
raise TypeError(msg)
|
|
92
|
+
self.handler = handler
|
|
93
|
+
self.record_async_iterable = record_async_iterable
|
|
94
|
+
|
|
95
|
+
async def __aiter__(self) -> AsyncGenerator[T]:
|
|
96
|
+
"""Get the objects for the query.
|
|
97
|
+
|
|
98
|
+
Yields:
|
|
99
|
+
Generates each object for the query.
|
|
100
|
+
|
|
101
|
+
"""
|
|
102
|
+
previous = None
|
|
103
|
+
async for record in self.record_async_iterable:
|
|
104
|
+
current = self.handler(*record)
|
|
105
|
+
if previous is not None and id(current) != id(previous):
|
|
106
|
+
yield previous
|
|
107
|
+
previous = current
|
|
108
|
+
if previous is not None:
|
|
109
|
+
yield previous
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Query:
|
|
113
|
+
"""Callable to create an ObjectAsyncIterable."""
|
|
114
|
+
|
|
115
|
+
queryable: Queryable
|
|
116
|
+
|
|
117
|
+
def __init__(self, queryable: Queryable) -> None:
|
|
118
|
+
"""Create an instance of the Query."""
|
|
119
|
+
self.queryable = queryable
|
|
120
|
+
|
|
121
|
+
async def collect[T, T1, T2, T3, T4](
|
|
122
|
+
self,
|
|
123
|
+
sql: Template,
|
|
124
|
+
specs: SpecsArgs[T, T1, T2, T3, T4],
|
|
125
|
+
) -> Sequence[T]:
|
|
126
|
+
"""Create and execute an ObjectAsyncIterable collecting and returning the return values.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
sql: The SQL to execute.
|
|
130
|
+
specs: The callables to map data to objects.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
A sequence of hydrated values.
|
|
134
|
+
|
|
135
|
+
"""
|
|
136
|
+
return [o async for o in await self._run(sql, specs)]
|
|
137
|
+
|
|
138
|
+
async def execute[T, T1, T2, T3, T4](
|
|
139
|
+
self,
|
|
140
|
+
sql: Template,
|
|
141
|
+
specs: SpecsArgs[T, T1, T2, T3, T4],
|
|
142
|
+
) -> None:
|
|
143
|
+
"""Create and execute an ObjectAsyncIterable ignoring the return values.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
sql: The SQL to execute.
|
|
147
|
+
specs: The callables to map data to objects.
|
|
148
|
+
|
|
149
|
+
"""
|
|
150
|
+
_ = [_ async for _ in await self._run(sql, specs)]
|
|
151
|
+
|
|
152
|
+
async def __call__[T, T1, T2, T3, T4](
|
|
153
|
+
self,
|
|
154
|
+
sql: Template,
|
|
155
|
+
specs: SpecsArgs[T, T1, T2, T3, T4],
|
|
156
|
+
) -> ObjectAsyncIterable[T]:
|
|
157
|
+
"""Create an ObjectAsyncIterable from the parameters.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
sql: The SQL to execute.
|
|
161
|
+
specs: The callables to map data to objects.
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
An async iterator that gives you access to the hydrated objects.
|
|
165
|
+
|
|
166
|
+
"""
|
|
167
|
+
return await self._run(sql, specs)
|
|
168
|
+
|
|
169
|
+
async def _run[T, T1, T2, T3, T4]( # ruff: ignore[too-many-branches]
|
|
170
|
+
self,
|
|
171
|
+
sql: Template,
|
|
172
|
+
specs: SpecsArgs[T, T1, T2, T3, T4],
|
|
173
|
+
) -> ObjectAsyncIterable[T]:
|
|
174
|
+
"""Create an ObjectAsyncIterable from the parameters.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
An object to iterate over for hydrated objects.
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
UnknownDependencyError: Raised if a dependency is specified that is not named in previous specs.
|
|
181
|
+
ValueError: If the values passed are not as typed.
|
|
182
|
+
|
|
183
|
+
"""
|
|
184
|
+
final_specs: FinalSpecsArgs[T, T1, T2, T3, T4]
|
|
185
|
+
if not isinstance(specs, tuple):
|
|
186
|
+
final_specs = (specs,)
|
|
187
|
+
elif len(specs) == 3: # ruff: ignore[magic-value-comparison]
|
|
188
|
+
final_specs = (
|
|
189
|
+
specs[2],
|
|
190
|
+
Specification.ensure(specs[0]),
|
|
191
|
+
Specification.ensure(specs[1]),
|
|
192
|
+
)
|
|
193
|
+
elif len(specs) == 4: # ruff: ignore[magic-value-comparison]
|
|
194
|
+
final_specs = (
|
|
195
|
+
specs[3],
|
|
196
|
+
Specification.ensure(specs[0]),
|
|
197
|
+
Specification.ensure(specs[1]),
|
|
198
|
+
Specification.ensure(specs[2]),
|
|
199
|
+
)
|
|
200
|
+
elif len(specs) == 5: # ruff: ignore[magic-value-comparison]
|
|
201
|
+
final_specs = (
|
|
202
|
+
specs[4],
|
|
203
|
+
Specification.ensure(specs[0]),
|
|
204
|
+
Specification.ensure(specs[1]),
|
|
205
|
+
Specification.ensure(specs[2]),
|
|
206
|
+
Specification.ensure(specs[3]),
|
|
207
|
+
)
|
|
208
|
+
else:
|
|
209
|
+
raise ValueError # pyright: ignore[reportUnreachable]
|
|
210
|
+
|
|
211
|
+
names: list[str] = []
|
|
212
|
+
for spec in final_specs[1:]:
|
|
213
|
+
for dep in spec.dependencies_:
|
|
214
|
+
if dep not in names:
|
|
215
|
+
raise UnknownDependencyError(dep, names)
|
|
216
|
+
if spec.name_ is not None:
|
|
217
|
+
names.append(spec.name_)
|
|
218
|
+
|
|
219
|
+
record_async_iterable = await self.queryable.query(sql)
|
|
220
|
+
column_names = await record_async_iterable.column_names()
|
|
221
|
+
column_name_groups = Query._split_column_names(
|
|
222
|
+
len(final_specs) - 1,
|
|
223
|
+
column_names,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
if len(final_specs) == 1:
|
|
227
|
+
handler = partial(
|
|
228
|
+
Query._handler_1,
|
|
229
|
+
column_name_groups[0],
|
|
230
|
+
final_specs[0],
|
|
231
|
+
)
|
|
232
|
+
elif len(final_specs) == 3 and len(column_name_groups) == 2: # ruff: ignore[magic-value-comparison]
|
|
233
|
+
handler = partial(
|
|
234
|
+
Query._handler_2,
|
|
235
|
+
column_name_groups,
|
|
236
|
+
final_specs[1:],
|
|
237
|
+
final_specs[0],
|
|
238
|
+
)
|
|
239
|
+
elif len(final_specs) == 4 and len(column_name_groups) == 3: # ruff: ignore[magic-value-comparison]
|
|
240
|
+
handler = partial(
|
|
241
|
+
Query._handler_3,
|
|
242
|
+
column_name_groups,
|
|
243
|
+
final_specs[1:],
|
|
244
|
+
final_specs[0],
|
|
245
|
+
)
|
|
246
|
+
elif len(final_specs) == 5 and len(column_name_groups) == 4: # ruff: ignore[magic-value-comparison]
|
|
247
|
+
handler = partial(
|
|
248
|
+
Query._handler_4,
|
|
249
|
+
column_name_groups,
|
|
250
|
+
final_specs[1:],
|
|
251
|
+
final_specs[0],
|
|
252
|
+
)
|
|
253
|
+
else:
|
|
254
|
+
raise ValueError
|
|
255
|
+
|
|
256
|
+
return ObjectAsyncIterable(record_async_iterable, handler)
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def _handler_1[T](
|
|
260
|
+
column_names: list[str],
|
|
261
|
+
spec: Callable[..., T],
|
|
262
|
+
*args: Any, # ruff: ignore[any-type] # pyright: ignore[reportExplicitAny, reportAny]
|
|
263
|
+
) -> T:
|
|
264
|
+
kwargs = dict(zip(column_names, args, strict=True))
|
|
265
|
+
return spec(**kwargs)
|
|
266
|
+
|
|
267
|
+
@staticmethod
|
|
268
|
+
def _handler_2[T, T1, T2](
|
|
269
|
+
column_names_lists: tuple[list[str], list[str]],
|
|
270
|
+
specs: tuple[Specification[T1], Specification[T2]],
|
|
271
|
+
aggregator: Callable[[T1 | None, T2 | None], T],
|
|
272
|
+
*args: Any, # ruff: ignore[any-type] # pyright: ignore[reportAny, reportExplicitAny]
|
|
273
|
+
) -> T:
|
|
274
|
+
u_kwargs, v_kwargs = Query._args_to_kwargs(column_names_lists, args)
|
|
275
|
+
u, spec_kwargs = specs[0].process(u_kwargs, {})
|
|
276
|
+
v, _ = specs[1].process(v_kwargs, spec_kwargs)
|
|
277
|
+
return aggregator(u, v)
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def _handler_3[T, T1, T2, T3](
|
|
281
|
+
column_names_lists: tuple[list[str], list[str], list[str]],
|
|
282
|
+
specs: tuple[Specification[T1], Specification[T2], Specification[T3]],
|
|
283
|
+
aggregator: Callable[[T1 | None, T2 | None, T3 | None], T],
|
|
284
|
+
*args: Any, # ruff: ignore[any-type] # pyright: ignore[reportAny, reportExplicitAny]
|
|
285
|
+
) -> T:
|
|
286
|
+
u_kwargs, v_kwargs, w_kwargs = Query._args_to_kwargs(
|
|
287
|
+
column_names_lists, args
|
|
288
|
+
)
|
|
289
|
+
u, spec_kwargs = specs[0].process(u_kwargs, {})
|
|
290
|
+
v, spec_kwargs = specs[1].process(v_kwargs, spec_kwargs)
|
|
291
|
+
w, _ = specs[2].process(w_kwargs, spec_kwargs)
|
|
292
|
+
return aggregator(u, v, w)
|
|
293
|
+
|
|
294
|
+
@staticmethod
|
|
295
|
+
def _handler_4[T, T1, T2, T3, T4](
|
|
296
|
+
column_names_lists: tuple[list[str], list[str], list[str], list[str]],
|
|
297
|
+
specs: tuple[
|
|
298
|
+
Specification[T1],
|
|
299
|
+
Specification[T2],
|
|
300
|
+
Specification[T3],
|
|
301
|
+
Specification[T4],
|
|
302
|
+
],
|
|
303
|
+
aggregator: Callable[[T1 | None, T2 | None, T3 | None, T4 | None], T],
|
|
304
|
+
*args: Any, # ruff: ignore[any-type] # pyright: ignore[reportAny, reportExplicitAny]
|
|
305
|
+
) -> T:
|
|
306
|
+
u_kwargs, v_kwargs, w_kwargs, x_kwargs = Query._args_to_kwargs(
|
|
307
|
+
column_names_lists, args
|
|
308
|
+
)
|
|
309
|
+
u, spec_kwargs = specs[0].process(u_kwargs, {})
|
|
310
|
+
v, spec_kwargs = specs[1].process(v_kwargs, spec_kwargs)
|
|
311
|
+
w, spec_kwargs = specs[2].process(w_kwargs, spec_kwargs)
|
|
312
|
+
x, _ = specs[3].process(x_kwargs, spec_kwargs)
|
|
313
|
+
return aggregator(u, v, w, x)
|
|
314
|
+
|
|
315
|
+
@staticmethod
|
|
316
|
+
def _split_column_names(
|
|
317
|
+
num_split: int,
|
|
318
|
+
column_names: list[str],
|
|
319
|
+
) -> tuple[list[str], ...]:
|
|
320
|
+
"""Split a list of column names num_split times.
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
A tuple of lists of arg names.
|
|
324
|
+
|
|
325
|
+
"""
|
|
326
|
+
lower = 0
|
|
327
|
+
column_names_split: list[list[str]] = []
|
|
328
|
+
while len(column_names_split) < num_split - 1:
|
|
329
|
+
upper = column_names.index("id", lower + 1)
|
|
330
|
+
column_names_split.append(column_names[lower:upper])
|
|
331
|
+
lower = upper
|
|
332
|
+
column_names_split.append(column_names[lower:])
|
|
333
|
+
return tuple(column_names_split)
|
|
334
|
+
|
|
335
|
+
@staticmethod
|
|
336
|
+
def _args_to_kwargs(
|
|
337
|
+
column_names_lists: tuple[list[str], ...],
|
|
338
|
+
args: tuple[Any, ...], # pyright: ignore[reportExplicitAny]
|
|
339
|
+
) -> list[dict[str, Any]]: # pyright: ignore[reportExplicitAny]
|
|
340
|
+
"""Create a list of kwargs based on the provided column_names_lists and args.
|
|
341
|
+
|
|
342
|
+
Returns:
|
|
343
|
+
A list of kwargs dictionaries.
|
|
344
|
+
|
|
345
|
+
"""
|
|
346
|
+
all_kwargs: list[dict[str, Any]] = [] # pyright: ignore[reportExplicitAny]
|
|
347
|
+
lower = 0
|
|
348
|
+
for column_names in column_names_lists:
|
|
349
|
+
upper = lower + len(column_names)
|
|
350
|
+
args_slice = args[lower:upper]
|
|
351
|
+
kwargs = dict(zip(column_names, args_slice, strict=True))
|
|
352
|
+
all_kwargs.append(kwargs)
|
|
353
|
+
lower = upper
|
|
354
|
+
return all_kwargs
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
class Queryable(ABC):
|
|
358
|
+
"""Database-agnostic wrapper to make queries."""
|
|
359
|
+
|
|
360
|
+
@abstractmethod
|
|
361
|
+
def query(self, sql: Template) -> Awaitable[RecordAsyncIterable]:
|
|
362
|
+
"""Create an awaitable iterable based on the content of the SQL query."""
|
|
363
|
+
|
|
364
|
+
@abstractmethod
|
|
365
|
+
async def close(self) -> None:
|
|
366
|
+
"""Close the Queryable's connection to the database."""
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class QueryAsyncContextManager:
|
|
370
|
+
"""Closes underlying Queryable cursors when the context exits."""
|
|
371
|
+
|
|
372
|
+
queryable: Queryable
|
|
373
|
+
|
|
374
|
+
def __init__(self, queryable: Queryable) -> None:
|
|
375
|
+
"""Create an instance of QueryAsyncContextManager.
|
|
376
|
+
|
|
377
|
+
Raises:
|
|
378
|
+
TypeError: If queryable is not a Queryable
|
|
379
|
+
|
|
380
|
+
"""
|
|
381
|
+
|
|
382
|
+
if not isinstance(queryable, Queryable): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
383
|
+
message = "QueryAsyncContextManager() requires Queryable"
|
|
384
|
+
raise TypeError(message) # pyright: ignore[reportUnreachable]
|
|
385
|
+
self.queryable = queryable
|
|
386
|
+
|
|
387
|
+
async def __aenter__(self) -> Query:
|
|
388
|
+
"""Create a Query for use in the context.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
Query: A Query to use in the context.
|
|
392
|
+
|
|
393
|
+
"""
|
|
394
|
+
return Query(self.queryable)
|
|
395
|
+
|
|
396
|
+
async def __aexit__(
|
|
397
|
+
self,
|
|
398
|
+
exc_type: type[BaseException] | None,
|
|
399
|
+
exc: BaseException | None,
|
|
400
|
+
traceback: TracebackType | None,
|
|
401
|
+
) -> None:
|
|
402
|
+
"""Close the Queryable used to create this QueryAsyncContextManager."""
|
|
403
|
+
await self.queryable.close()
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class RecordAsyncIterable(ABC):
|
|
407
|
+
"""Manages the list of column names and iterates over records."""
|
|
408
|
+
|
|
409
|
+
@abstractmethod
|
|
410
|
+
def column_names(self) -> Awaitable[list[str]]:
|
|
411
|
+
"""Get the list of column names for the result set represented by this iterable."""
|
|
412
|
+
|
|
413
|
+
@abstractmethod
|
|
414
|
+
def __aiter__(self) -> AsyncGenerator[tuple[Any, ...]]: # pyright: ignore[reportExplicitAny]
|
|
415
|
+
"""Asynchronous iteration over the iterable."""
|