asyncpg-typed 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Levente Hunyadi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: asyncpg_typed
3
+ Version: 0.1.0
4
+ Summary: Type-safe queries for asyncpg
5
+ Author-email: Levente Hunyadi <hunyadi@gmail.com>
6
+ Maintainer-email: Levente Hunyadi <hunyadi@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/hunyadi/asyncpg_typed
9
+ Project-URL: Source, https://github.com/hunyadi/asyncpg_typed
10
+ Keywords: asyncpg,typed,database-client
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: SQL
22
+ Classifier: Topic :: Database
23
+ Classifier: Topic :: Utilities
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: asyncpg>=0.31
29
+ Requires-Dist: typing-extensions>=4.15; python_version < "3.11"
30
+ Provides-Extra: vector
31
+ Requires-Dist: asyncpg-vector>=0.1; extra == "vector"
32
+ Provides-Extra: dev
33
+ Requires-Dist: asyncpg-stubs>=0.31; extra == "dev"
34
+ Requires-Dist: build>=1.3; extra == "dev"
35
+ Requires-Dist: mypy>=1.19; extra == "dev"
36
+ Requires-Dist: ruff>=0.14; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # Type-safe queries for asyncpg
40
+
41
+ [asyncpg](https://magicstack.github.io/asyncpg/current/) is a high-performance database client to connect to a PostgreSQL server, and execute SQL statements using the async/await paradigm in Python. The library exposes a `Connection` object, which has methods like `execute` and `fetch` that run SQL queries against the database. Unfortunately, these methods take the query as a plain `str`, arguments as `object`, and the resultset is exposed as a `Record`, which is a `tuple`/`dict` hybrid whose `get` and indexer have a return type of `Any`. There is no mechanism to check compatibility of input or output arguments, even if their types are preliminarily known.
42
+
43
+ This Python library provides "compile-time" validation for SQL queries that linters and type checkers can enforce. By creating a generic `SQL` object and associating input and output type information with the query, the signatures of `execute` and `fetch` reveal the exact expected and returned types.
44
+
45
+
46
+ ## Motivating example
47
+
48
+ ```python
49
+ # create a typed object, setting expected and returned types
50
+ select_where_sql = sql(
51
+ """--sql
52
+ SELECT boolean_value, integer_value, string_value
53
+ FROM sample_data
54
+ WHERE boolean_value = $1 AND integer_value > $2
55
+ ORDER BY integer_value;
56
+ """,
57
+ args=tuple[bool, int],
58
+ resultset=tuple[bool, int, str | None],
59
+ )
60
+
61
+ conn = await asyncpg.connect(host="localhost", port=5432, user="postgres", password="postgres")
62
+ try:
63
+ # ✅ Valid signature
64
+ rows = await select_where_sql.fetch(conn, False, 2)
65
+
66
+ # ✅ Type of "rows" is "list[tuple[bool, int, str | None]]"
67
+ reveal_type(rows)
68
+
69
+ # ⚠️ Argument missing for parameter "arg2"
70
+ rows = await select_where_sql.fetch(conn, False)
71
+
72
+ # ⚠️ Argument of type "float" cannot be assigned to parameter "arg2" of type "int" in function "fetch"; "float" is not assignable to "int"
73
+ rows = await select_where_sql.fetch(conn, False, 3.14)
74
+
75
+ finally:
76
+ await conn.close()
77
+ ```
78
+
79
+
80
+ ## Syntax
81
+
82
+ ### Creating a SQL object
83
+
84
+ Instantiate a SQL object with the `sql` function:
85
+
86
+ ```python
87
+ def sql(
88
+ stmt: str | string.templatelib.Template,
89
+ *,
90
+ args: None | type[P1] | type[tuple[P1, P2]] | type[tuple[P1, P2, P3]] | ... = None,
91
+ resultset: None | type[R1] | type[tuple[R1, R2]] | type[tuple[R1, R2, R3]] | ... = None
92
+ ) -> _SQL: ...
93
+ ```
94
+
95
+ The parameter `stmt` represents a SQL expression, either as a string (including an *f-string*) or a template (i.e. a *t-string*).
96
+
97
+ If the expression is a string, it can have PostgreSQL parameter placeholders such as `$1`, `$2` or `$3`:
98
+
99
+ ```python
100
+ f"INSERT INTO table_name (col_1, col_2, col_3) VALUES ($1, $2, $3);"
101
+ ```
102
+
103
+ If the expression is a *t-string*, it can have replacement fields that evaluate to integers:
104
+
105
+ ```python
106
+ t"INSERT INTO table_name (col_1, col_2, col_3) VALUES ({1}, {2}, {3});"
107
+ ```
108
+
109
+ The parameters `args` and `resultset` take a series type `P` or `R`, which may be any of the following:
110
+
111
+ * (required) simple type
112
+ * optional simple type (`T | None`)
113
+ * `tuple` of several (required or optional) simple types.
114
+
115
+ Simple types include:
116
+
117
+ * `bool`
118
+ * `int`
119
+ * `float`
120
+ * `decimal.Decimal`
121
+ * `datetime.date`
122
+ * `datetime.time`
123
+ * `datetime.datetime`
124
+ * `str`
125
+ * `bytes`
126
+ * `uuid.UUID`
127
+
128
+ Types are grouped together with `tuple`:
129
+
130
+ ```python
131
+ tuple[bool, int, str | None]
132
+ ```
133
+
134
+ Passing a simple type directly (e.g. `type[T]`) is for convenience, and is equivalent to passing a one-element tuple of the same simple type (i.e. `type[tuple[T]]`).
135
+
136
+ The number of types in `args` must correspond to the number of query parameters. (This is validated on calling `sql(...)` for the *t-string* syntax.) The number of types in `resultset` must correspond to the number of columns returned by the query.
137
+
138
+ Both `args` and `resultset` types must be compatible with their corresponding PostgreSQL query parameter types and resultset column types, respectively. The following table shows the mapping between PostgreSQL and Python types.
139
+
140
+ | PostgreSQL type | Python type |
141
+ | ----------------- | ------------------ |
142
+ | `bool` | `bool` |
143
+ | `smallint` | `int` |
144
+ | `integer` | `int` |
145
+ | `bigint` | `int` |
146
+ | `real`/`float4` | `float` |
147
+ | `double`/`float8` | `float` |
148
+ | `decimal` | `Decimal` |
149
+ | `numeric` | `Decimal` |
150
+ | `date` | `date` |
151
+ | `time` | `time` (naive) |
152
+ | `timetz` | `time` (tz) |
153
+ | `timestamp` | `datetime` (naive) |
154
+ | `timestamptz` | `datetime` (tz) |
155
+ | `char(N)` | `str` |
156
+ | `varchar(N)` | `str` |
157
+ | `text` | `str` |
158
+ | `bytea` | `bytes` |
159
+ | `json` | `str` |
160
+ | `jsonb` | `str` |
161
+ | `uuid` | `UUID` |
162
+
163
+ ### Using a SQL object
164
+
165
+ The function `sql` returns an object that derives from the base class `_SQL` and is specific to the number and types of parameters passed in `args` and `resultset`.
166
+
167
+ The following functions are available on SQL objects:
168
+
169
+ ```python
170
+ async def execute(self, connection: Connection, *args: *P) -> None: ...
171
+ async def executemany(self, connection: Connection, args: Iterable[tuple[*P]]) -> None: ...
172
+ async def fetch(self, connection: Connection, *args: *P) -> list[tuple[*R]]: ...
173
+ async def fetchmany(self, connection: Connection, args: Iterable[tuple[*P]]) -> list[tuple[*R]]: ...
174
+ async def fetchrow(self, connection: Connection, *args: *P) -> tuple[*R] | None: ...
175
+ async def fetchval(self, connection: Connection, *args: *P) -> R1: ...
176
+ ```
177
+
178
+ `Connection` may be an `asyncpg.Connection` or an `asyncpg.pool.PoolConnectionProxy` acquired from a connection pool.
179
+
180
+ `*P` and `*R` denote several types (a type pack) corresponding to those listed in `args` and `resultset`, respectively.
181
+
182
+ Only those functions are prompted on code completion that make sense in the context of the given number of input and output arguments. Specifically, `fetchval` is available only for a single type passed to `resultset`, and `executemany` and `fetchmany` are available only if the query takes (one or more) parameters.
183
+
184
+
185
+ ## Run-time behavior
186
+
187
+ When a call such as `sql.executemany(conn, records)` or `sql.fetch(conn, param1, param2)` is made on a `SQL` object at run time, the library invokes `connection.prepare(sql)` to create a `PreparedStatement` and compares the actual statement signature against the expected Python types. Unfortunately, PostgreSQL doesn't propagate nullability via prepared statements: resultset types that are declared as required (e.g. `T` as opposed to `T | None`) are validated at run time.
@@ -0,0 +1,149 @@
1
+ # Type-safe queries for asyncpg
2
+
3
+ [asyncpg](https://magicstack.github.io/asyncpg/current/) is a high-performance database client to connect to a PostgreSQL server, and execute SQL statements using the async/await paradigm in Python. The library exposes a `Connection` object, which has methods like `execute` and `fetch` that run SQL queries against the database. Unfortunately, these methods take the query as a plain `str`, arguments as `object`, and the resultset is exposed as a `Record`, which is a `tuple`/`dict` hybrid whose `get` and indexer have a return type of `Any`. There is no mechanism to check compatibility of input or output arguments, even if their types are preliminarily known.
4
+
5
+ This Python library provides "compile-time" validation for SQL queries that linters and type checkers can enforce. By creating a generic `SQL` object and associating input and output type information with the query, the signatures of `execute` and `fetch` reveal the exact expected and returned types.
6
+
7
+
8
+ ## Motivating example
9
+
10
+ ```python
11
+ # create a typed object, setting expected and returned types
12
+ select_where_sql = sql(
13
+ """--sql
14
+ SELECT boolean_value, integer_value, string_value
15
+ FROM sample_data
16
+ WHERE boolean_value = $1 AND integer_value > $2
17
+ ORDER BY integer_value;
18
+ """,
19
+ args=tuple[bool, int],
20
+ resultset=tuple[bool, int, str | None],
21
+ )
22
+
23
+ conn = await asyncpg.connect(host="localhost", port=5432, user="postgres", password="postgres")
24
+ try:
25
+ # ✅ Valid signature
26
+ rows = await select_where_sql.fetch(conn, False, 2)
27
+
28
+ # ✅ Type of "rows" is "list[tuple[bool, int, str | None]]"
29
+ reveal_type(rows)
30
+
31
+ # ⚠️ Argument missing for parameter "arg2"
32
+ rows = await select_where_sql.fetch(conn, False)
33
+
34
+ # ⚠️ Argument of type "float" cannot be assigned to parameter "arg2" of type "int" in function "fetch"; "float" is not assignable to "int"
35
+ rows = await select_where_sql.fetch(conn, False, 3.14)
36
+
37
+ finally:
38
+ await conn.close()
39
+ ```
40
+
41
+
42
+ ## Syntax
43
+
44
+ ### Creating a SQL object
45
+
46
+ Instantiate a SQL object with the `sql` function:
47
+
48
+ ```python
49
+ def sql(
50
+ stmt: str | string.templatelib.Template,
51
+ *,
52
+ args: None | type[P1] | type[tuple[P1, P2]] | type[tuple[P1, P2, P3]] | ... = None,
53
+ resultset: None | type[R1] | type[tuple[R1, R2]] | type[tuple[R1, R2, R3]] | ... = None
54
+ ) -> _SQL: ...
55
+ ```
56
+
57
+ The parameter `stmt` represents a SQL expression, either as a string (including an *f-string*) or a template (i.e. a *t-string*).
58
+
59
+ If the expression is a string, it can have PostgreSQL parameter placeholders such as `$1`, `$2` or `$3`:
60
+
61
+ ```python
62
+ f"INSERT INTO table_name (col_1, col_2, col_3) VALUES ($1, $2, $3);"
63
+ ```
64
+
65
+ If the expression is a *t-string*, it can have replacement fields that evaluate to integers:
66
+
67
+ ```python
68
+ t"INSERT INTO table_name (col_1, col_2, col_3) VALUES ({1}, {2}, {3});"
69
+ ```
70
+
71
+ The parameters `args` and `resultset` take a series type `P` or `R`, which may be any of the following:
72
+
73
+ * (required) simple type
74
+ * optional simple type (`T | None`)
75
+ * `tuple` of several (required or optional) simple types.
76
+
77
+ Simple types include:
78
+
79
+ * `bool`
80
+ * `int`
81
+ * `float`
82
+ * `decimal.Decimal`
83
+ * `datetime.date`
84
+ * `datetime.time`
85
+ * `datetime.datetime`
86
+ * `str`
87
+ * `bytes`
88
+ * `uuid.UUID`
89
+
90
+ Types are grouped together with `tuple`:
91
+
92
+ ```python
93
+ tuple[bool, int, str | None]
94
+ ```
95
+
96
+ Passing a simple type directly (e.g. `type[T]`) is for convenience, and is equivalent to passing a one-element tuple of the same simple type (i.e. `type[tuple[T]]`).
97
+
98
+ The number of types in `args` must correspond to the number of query parameters. (This is validated on calling `sql(...)` for the *t-string* syntax.) The number of types in `resultset` must correspond to the number of columns returned by the query.
99
+
100
+ Both `args` and `resultset` types must be compatible with their corresponding PostgreSQL query parameter types and resultset column types, respectively. The following table shows the mapping between PostgreSQL and Python types.
101
+
102
+ | PostgreSQL type | Python type |
103
+ | ----------------- | ------------------ |
104
+ | `bool` | `bool` |
105
+ | `smallint` | `int` |
106
+ | `integer` | `int` |
107
+ | `bigint` | `int` |
108
+ | `real`/`float4` | `float` |
109
+ | `double`/`float8` | `float` |
110
+ | `decimal` | `Decimal` |
111
+ | `numeric` | `Decimal` |
112
+ | `date` | `date` |
113
+ | `time` | `time` (naive) |
114
+ | `timetz` | `time` (tz) |
115
+ | `timestamp` | `datetime` (naive) |
116
+ | `timestamptz` | `datetime` (tz) |
117
+ | `char(N)` | `str` |
118
+ | `varchar(N)` | `str` |
119
+ | `text` | `str` |
120
+ | `bytea` | `bytes` |
121
+ | `json` | `str` |
122
+ | `jsonb` | `str` |
123
+ | `uuid` | `UUID` |
124
+
125
+ ### Using a SQL object
126
+
127
+ The function `sql` returns an object that derives from the base class `_SQL` and is specific to the number and types of parameters passed in `args` and `resultset`.
128
+
129
+ The following functions are available on SQL objects:
130
+
131
+ ```python
132
+ async def execute(self, connection: Connection, *args: *P) -> None: ...
133
+ async def executemany(self, connection: Connection, args: Iterable[tuple[*P]]) -> None: ...
134
+ async def fetch(self, connection: Connection, *args: *P) -> list[tuple[*R]]: ...
135
+ async def fetchmany(self, connection: Connection, args: Iterable[tuple[*P]]) -> list[tuple[*R]]: ...
136
+ async def fetchrow(self, connection: Connection, *args: *P) -> tuple[*R] | None: ...
137
+ async def fetchval(self, connection: Connection, *args: *P) -> R1: ...
138
+ ```
139
+
140
+ `Connection` may be an `asyncpg.Connection` or an `asyncpg.pool.PoolConnectionProxy` acquired from a connection pool.
141
+
142
+ `*P` and `*R` denote several types (a type pack) corresponding to those listed in `args` and `resultset`, respectively.
143
+
144
+ Only those functions are prompted on code completion that make sense in the context of the given number of input and output arguments. Specifically, `fetchval` is available only for a single type passed to `resultset`, and `executemany` and `fetchmany` are available only if the query takes (one or more) parameters.
145
+
146
+
147
+ ## Run-time behavior
148
+
149
+ When a call such as `sql.executemany(conn, records)` or `sql.fetch(conn, param1, param2)` is made on a `SQL` object at run time, the library invokes `connection.prepare(sql)` to create a `PreparedStatement` and compares the actual statement signature against the expected Python types. Unfortunately, PostgreSQL doesn't propagate nullability via prepared statements: resultset types that are declared as required (e.g. `T` as opposed to `T | None`) are validated at run time.