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/errors.py ADDED
@@ -0,0 +1,68 @@
1
+ """Errors created by Dappyr.
2
+
3
+ Copyright 2026 by curtissimo, llc.
4
+ """
5
+
6
+ from typing import Any, override
7
+
8
+
9
+ class CacheKeyDoesNotExistInRecordError(RuntimeError):
10
+ """Raised when a cache attempts to find an entry but the key does not exist in the record."""
11
+
12
+ key: str
13
+ record: dict[str, Any] # pyright: ignore[reportExplicitAny]
14
+
15
+ def __init__(self, key: str, record: dict[str, Any]) -> None: # pyright: ignore[reportExplicitAny]
16
+ """Create an instance of the CacheKeyDoesNotExistInRecordError."""
17
+ super().__init__(f"Did not find {key} in {record}")
18
+ self.key = key
19
+ self.record = record
20
+
21
+
22
+ class NoResultSqlError(RuntimeError):
23
+ """Raised when the SQL passed to Dappyr does not yield a result set."""
24
+
25
+
26
+ class NotEnoughIdColumnsInSqlResultError(RuntimeError):
27
+ """Raised when the column names list from a query does not have enough "id" columns to split on."""
28
+
29
+ num_ids_expected: int
30
+ column_names: list[str]
31
+
32
+ def __init__(self, num_ids_expected: int, column_names: list[str]) -> None:
33
+ """Create an instance of the Error."""
34
+ super().__init__(num_ids_expected, column_names)
35
+ self.num_ids_expected = num_ids_expected
36
+ self.column_names = column_names
37
+
38
+ @override
39
+ def __str__(self) -> str:
40
+ return f"Expected {self.num_ids_expected} id columns in {self.column_names}"
41
+
42
+
43
+ class StatementParametersMismatchError(RuntimeError):
44
+ """Raised if a prepared statement has an invalid number of parameters."""
45
+
46
+ def __init__(self, expected: int, received: int) -> None:
47
+ """Create an instance of StatementParametersMismatchError."""
48
+ message = f"Expected f{expected} parameters. Got only {received}."
49
+ super().__init__(message)
50
+
51
+
52
+ class UnknownDependencyError(KeyError):
53
+ """Raised when a dependency is specified that does not exist in the previous specs."""
54
+
55
+ dependency_name: str
56
+ available_names: list[str]
57
+
58
+ def __init__(
59
+ self,
60
+ dependency_name: str,
61
+ available_names: list[str],
62
+ ) -> None:
63
+ """Create an instance of UnknownDependencyError."""
64
+ super().__init__(
65
+ f"Cannot find dependency {dependency_name} in {available_names}"
66
+ )
67
+ self.dependency_name = dependency_name
68
+ self.available_names = available_names
dappyr/psycopg.py ADDED
@@ -0,0 +1,112 @@
1
+ """The psycopg bindings for Dappyr.
2
+
3
+ Copyright 2026 by curtissimo, llc.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from string.templatelib import Template
9
+ from typing import TYPE_CHECKING, Any, override
10
+
11
+ from psycopg import AsyncConnection, AsyncCursor
12
+
13
+ from .dappyr import Queryable as _Queryable
14
+ from .dappyr import QueryAsyncContextManager
15
+ from .dappyr import RecordAsyncIterable as _RecordAsyncIterable
16
+ from .errors import NoResultSqlError
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import AsyncGenerator
20
+
21
+
22
+ def use(connection: AsyncConnection) -> QueryAsyncContextManager:
23
+ """Use an asyncpg.Connection to create a queryable context.
24
+
25
+ Returns:
26
+ A QueryAsyncContextManager.
27
+
28
+ """
29
+ queryable = Queryable(connection)
30
+ return QueryAsyncContextManager(queryable)
31
+
32
+
33
+ class Queryable(_Queryable):
34
+ """A Queryable based on an psycopg.AsyncConnection."""
35
+
36
+ connection: AsyncConnection
37
+ cursors: list[AsyncCursor]
38
+
39
+ def __init__(self, connection: AsyncConnection) -> None:
40
+ """Create an instance of the Queryable class.
41
+
42
+ Raises:
43
+ TypeError: If connection is not a Connection.
44
+
45
+ """
46
+ if not isinstance(connection, AsyncConnection): # pyright: ignore[reportUnnecessaryIsInstance]
47
+ message = "PsycopgQueryable() requires an AsyncConnection"
48
+ raise TypeError(message) # pyright: ignore[reportUnreachable]
49
+ self.connection = connection
50
+ self.cursors = []
51
+
52
+ @override
53
+ async def query(self, sql: Template) -> RecordAsyncIterable:
54
+ cursor = self.connection.cursor()
55
+ self.cursors.append(cursor)
56
+ return RecordAsyncIterable(cursor, sql)
57
+
58
+ @override
59
+ async def close(self) -> None:
60
+ for cursor in self.cursors:
61
+ await cursor.close()
62
+
63
+
64
+ class RecordAsyncIterable(_RecordAsyncIterable):
65
+ """An async iterable that uses an psycopg.AsyncCursor to execute."""
66
+
67
+ cursor: AsyncCursor
68
+ sql: Template
69
+
70
+ def __init__(self, cursor: AsyncCursor, sql: Template) -> None:
71
+ """Create an instance of RecordAsyncIterable for the statement and parameters.
72
+
73
+ Raises:
74
+ TypeError: If statement is not an asyncpg.PreparedStatement
75
+ TypeError: If parameters is not a sequence of Any values.
76
+
77
+ """
78
+ if not isinstance(sql, Template): # pyright: ignore[reportUnnecessaryIsInstance]
79
+ message = "dappyr.psycopg.RecordAsyncIterable() requires a Template"
80
+ raise TypeError(message) # pyright: ignore[reportUnreachable]
81
+ if not isinstance(cursor, AsyncCursor): # pyright: ignore[reportUnnecessaryIsInstance]
82
+ message = (
83
+ "dappyr.psycopg.RecordAsyncIterable() requires an AsyncCursor"
84
+ )
85
+ raise TypeError(message) # pyright: ignore[reportUnreachable]
86
+ self.cursor = cursor
87
+ self.sql = sql
88
+
89
+ @override
90
+ async def column_names(self) -> list[str]:
91
+ await self.execute_cursor()
92
+ if self.cursor.description is None:
93
+ return []
94
+ return [column.name for column in self.cursor.description]
95
+
96
+ @override
97
+ async def __aiter__(self) -> AsyncGenerator[tuple[Any, ...]]: # pyright: ignore[reportExplicitAny]
98
+ await self.execute_cursor()
99
+ async for record in self.cursor:
100
+ yield record
101
+
102
+ async def execute_cursor(self) -> None:
103
+ """Execute the cursor if it has not yet been executed.
104
+
105
+ Raises:
106
+ NoResultSqlError: If the SQL statement does not return a result set.
107
+
108
+ """
109
+ if self.cursor.description is None:
110
+ _ = await self.cursor.execute(self.sql)
111
+ if self.cursor.description is None:
112
+ raise NoResultSqlError(self.sql)
@@ -0,0 +1,207 @@
1
+ """Specification classes used by Dappyr.
2
+
3
+ Copyright 2026 by curtissimo, llc.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, Any, overload, override
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Callable
11
+
12
+ type CallableOrSpec[T] = Callable[..., T] | Specification[T]
13
+
14
+
15
+ @overload
16
+ def specification[T](
17
+ spec: Callable[..., T],
18
+ *,
19
+ name: str,
20
+ ) -> Specification[T]: ...
21
+ @overload
22
+ def specification[T](
23
+ spec: Callable[..., T],
24
+ *,
25
+ deps: str | tuple[str, ...],
26
+ ) -> Specification[T]: ...
27
+ @overload
28
+ def specification[T](
29
+ spec: Callable[..., T],
30
+ *,
31
+ name: str,
32
+ deps: str | tuple[str, ...],
33
+ ) -> Specification[T]: ...
34
+
35
+
36
+ def specification[T](
37
+ spec: Callable[..., T],
38
+ *,
39
+ name: str | None = None,
40
+ deps: str | tuple[str, ...] | None = None,
41
+ ) -> Specification[T]:
42
+ """Create a named specification based on the provided name or deps.
43
+
44
+ Args:
45
+ spec: A `Callable` to create an object from data
46
+ name: The name for the result to be used in other spec dependencies
47
+ deps: The name or tuple of names of specs needed for the `Callable`
48
+
49
+ Returns:
50
+ A named specification.
51
+
52
+ """
53
+ deps_ = (deps,) if isinstance(deps, str) else deps
54
+
55
+ if name is not None and deps_ is not None:
56
+ return NamedDependentSpecification(
57
+ spec=spec,
58
+ name=name,
59
+ dependencies=deps_,
60
+ )
61
+
62
+ if name is not None:
63
+ return NamedSpecification(spec=spec, name=name)
64
+
65
+ if deps_ is not None:
66
+ return DependentSpecification(spec=spec, dependencies=deps_)
67
+
68
+ return Specification(spec=spec)
69
+
70
+
71
+ @dataclass(kw_only=True)
72
+ class Specification[T]:
73
+ """A specification for how Dappyr should create objects from records."""
74
+
75
+ spec: Callable[..., T]
76
+
77
+ def process(
78
+ self,
79
+ args: dict[str, Any | None], # pyright: ignore[reportExplicitAny]
80
+ spec_kwargs: dict[str, Any], # pyright: ignore[reportExplicitAny]
81
+ ) -> tuple[T | None, dict[str, Any]]: # pyright: ignore[reportExplicitAny]
82
+ """Process the args to hydrate an object.
83
+
84
+ Returns:
85
+ The created value and the updated dictionary of created values.
86
+
87
+ """
88
+ value = (
89
+ None
90
+ if all(value is None for value in args.values())
91
+ else self.spec(**args)
92
+ )
93
+ return value, spec_kwargs
94
+
95
+ @staticmethod
96
+ def ensure[X](o: CallableOrSpec[X]) -> Specification[X]:
97
+ """Ensure that Callable is wrapped by a Specification.
98
+
99
+ Returns:
100
+ A Specification.
101
+
102
+ """
103
+ return o if isinstance(o, Specification) else Specification(spec=o)
104
+
105
+ @property
106
+ def name_(self) -> str | None:
107
+ """The name of the parameter for the processed value."""
108
+
109
+ @property
110
+ def dependencies_(self) -> tuple[str, ...]:
111
+ """The dependencies this specification relies on from other Specifications."""
112
+ return ()
113
+
114
+
115
+ @dataclass(kw_only=True)
116
+ class NamedSpecification[T](Specification[T]):
117
+ """A named specification for how Dappyr should create objects from records."""
118
+
119
+ name: str
120
+
121
+ @override
122
+ def process(
123
+ self,
124
+ args: dict[str, Any | None], # pyright: ignore[reportExplicitAny]
125
+ spec_kwargs: dict[str, Any], # pyright: ignore[reportExplicitAny]
126
+ ) -> tuple[T | None, dict[str, Any]]: # pyright: ignore[reportExplicitAny]
127
+ value = (
128
+ None
129
+ if all(value is None for value in args.values())
130
+ else self.spec(**args)
131
+ )
132
+ spec_kwargs[self.name] = value
133
+ return value, spec_kwargs
134
+
135
+ @property
136
+ @override
137
+ def name_(self) -> str | None:
138
+ return self.name
139
+
140
+ @property
141
+ @override
142
+ def dependencies_(self) -> tuple[str, ...]:
143
+ return ()
144
+
145
+
146
+ @dataclass(kw_only=True)
147
+ class DependentSpecification[T](Specification[T]):
148
+ """A specification with dependencies for how Dappyr should create objects from records."""
149
+
150
+ dependencies: tuple[str, ...]
151
+
152
+ @override
153
+ def process(
154
+ self,
155
+ args: dict[str, Any | None], # pyright: ignore[reportExplicitAny]
156
+ spec_kwargs: dict[str, Any], # pyright: ignore[reportExplicitAny]
157
+ ) -> tuple[T | None, dict[str, Any]]: # pyright: ignore[reportExplicitAny]
158
+ deps = {dep: spec_kwargs[dep] for dep in self.dependencies}
159
+ value = (
160
+ None
161
+ if all(value is None for value in args.values())
162
+ else self.spec(**(args | deps))
163
+ )
164
+ return value, spec_kwargs
165
+
166
+ @property
167
+ @override
168
+ def name_(self) -> str | None:
169
+ return None
170
+
171
+ @property
172
+ @override
173
+ def dependencies_(self) -> tuple[str, ...]:
174
+ return self.dependencies
175
+
176
+
177
+ @dataclass(kw_only=True)
178
+ class NamedDependentSpecification[T](Specification[T]):
179
+ """A named specification with dependencies for how Dappyr should create objects from records."""
180
+
181
+ name: str
182
+ dependencies: tuple[str, ...]
183
+
184
+ @override
185
+ def process(
186
+ self,
187
+ args: dict[str, Any | None], # pyright: ignore[reportExplicitAny]
188
+ spec_kwargs: dict[str, Any], # pyright: ignore[reportExplicitAny]
189
+ ) -> tuple[T | None, dict[str, Any]]: # pyright: ignore[reportExplicitAny]
190
+ deps = {dep: spec_kwargs[dep] for dep in self.dependencies}
191
+ value = (
192
+ None
193
+ if all(value is None for value in args.values())
194
+ else self.spec(**(args | deps))
195
+ )
196
+ spec_kwargs[self.name] = value
197
+ return value, spec_kwargs
198
+
199
+ @property
200
+ @override
201
+ def name_(self) -> str | None:
202
+ return self.name
203
+
204
+ @property
205
+ @override
206
+ def dependencies_(self) -> tuple[str, ...]:
207
+ return self.dependencies
dappyr/sqlite3.py ADDED
@@ -0,0 +1,131 @@
1
+ # ruff: file-ignore[undocumented-public-module, missing-copyright-notice, missing-return-type-public-function, undocumented-public-function]
2
+ from __future__ import annotations
3
+
4
+ from sqlite3 import Connection, Cursor
5
+ from string.templatelib import Interpolation, Template
6
+ from typing import TYPE_CHECKING, Any, override
7
+
8
+ from dappyr.errors import NoResultSqlError
9
+
10
+ from .dappyr import Queryable as Queryable_
11
+ from .dappyr import QueryAsyncContextManager
12
+ from .dappyr import RecordAsyncIterable as RecordAsyncIterable_
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import AsyncGenerator
16
+
17
+
18
+ def use(connection: Connection):
19
+ queryable = Queryable(connection)
20
+ return QueryAsyncContextManager(queryable)
21
+
22
+
23
+ class Queryable(Queryable_):
24
+ """SQLite3 implementation of Queryable."""
25
+
26
+ connection: Connection
27
+ cursors: list[Cursor]
28
+
29
+ def __init__(self, connection: Connection) -> None:
30
+ """Create an instance of SQLite3 Queryable.
31
+
32
+ Raises:
33
+ TypeError: if connection is not a SQLite3 Connection.
34
+
35
+ """
36
+ if not isinstance(connection, Connection): # pyright: ignore[reportUnnecessaryIsInstance]
37
+ raise TypeError # pyright: ignore[reportUnreachable]
38
+ self.connection = connection
39
+ self.cursors = []
40
+
41
+ @override
42
+ async def close(self) -> None:
43
+ for cursor in self.cursors:
44
+ cursor.close()
45
+
46
+ @override
47
+ async def query(self, sql: Template) -> RecordAsyncIterable:
48
+ query, parameters = template_to_sql_and_parameters(sql)
49
+ cursor = self.connection.cursor()
50
+ self.cursors.append(cursor)
51
+ return RecordAsyncIterable(cursor, query, parameters)
52
+
53
+
54
+ class RecordAsyncIterable(RecordAsyncIterable_):
55
+ """SQLite3 implementation of RecordAsyncIterable."""
56
+
57
+ cursor: Cursor
58
+ statement: str
59
+ parameters: list[Any] # pyright: ignore[reportExplicitAny]
60
+
61
+ def __init__(
62
+ self,
63
+ cursor: Cursor,
64
+ statement: str,
65
+ parameters: list[Any], # pyright: ignore[reportExplicitAny]
66
+ ) -> None:
67
+ """Create an instance of RecordAsyncIterable from the records and column names.
68
+
69
+ Raises:
70
+ TypeError: If statement is not an asyncpg.PreparedStatement
71
+ TypeError: If parameters is not a sequence of Any values.
72
+
73
+ """
74
+ if not isinstance(cursor, Cursor): # pyright: ignore[reportUnnecessaryIsInstance]
75
+ raise TypeError # pyright: ignore[reportUnreachable]
76
+ if not isinstance(statement, str): # pyright: ignore[reportUnnecessaryIsInstance]
77
+ raise TypeError # pyright: ignore[reportUnreachable]
78
+ if not isinstance(parameters, list): # pyright: ignore[reportUnnecessaryIsInstance]
79
+ raise TypeError # pyright: ignore[reportUnreachable]
80
+ self.cursor = cursor
81
+ self.statement = statement
82
+ self.parameters = parameters
83
+
84
+ @override
85
+ async def column_names(self) -> list[str]:
86
+ self.execute_cursor()
87
+ return [col[0] for col in self.cursor.description]
88
+
89
+ @override
90
+ async def __aiter__(self) -> AsyncGenerator[tuple[Any, ...]]: # pyright: ignore[reportExplicitAny]
91
+ self.execute_cursor()
92
+ for record in self.cursor.fetchall(): # pyright: ignore[reportAny]
93
+ yield record
94
+
95
+ def execute_cursor(self) -> None:
96
+ """Execute the cursor if it has not yet been executed.
97
+
98
+ Raises:
99
+ NoResultSqlError: If the SQL statement does not return a result set.
100
+
101
+ """
102
+ if self.cursor.description is None:
103
+ _ = self.cursor.execute(self.statement, self.parameters)
104
+ if self.cursor.description is None:
105
+ raise NoResultSqlError(self.statement)
106
+
107
+
108
+ def template_to_sql_and_parameters(template: Template) -> tuple[str, list[Any]]: # pyright: ignore[reportExplicitAny]
109
+ """Convert a Template into a SQL string and associated SQL parameters.
110
+
111
+ Returns:
112
+ A SQL string
113
+ A list of associated parameters.
114
+
115
+ """
116
+ sql: list[str] = []
117
+ parameters: list[Any] = [] # pyright: ignore[reportExplicitAny]
118
+
119
+ for part in template:
120
+ if isinstance(part, Interpolation):
121
+ value = part.value # pyright: ignore[reportAny]
122
+ if isinstance(value, list):
123
+ parameters.extend(value) # pyright: ignore[reportUnknownArgumentType]
124
+ sql.append(", ".join(["?" for _ in range(len(value))])) # pyright: ignore[reportUnknownArgumentType]
125
+ else:
126
+ parameters.append(value)
127
+ sql.append("?")
128
+ else:
129
+ sql.append(part)
130
+
131
+ return "".join(sql), parameters