pgtern 0.3.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.
Files changed (50) hide show
  1. pgtern-0.3.0/CHANGELOG.md +7 -0
  2. pgtern-0.3.0/CONTRIBUTING.md +63 -0
  3. pgtern-0.3.0/LICENSE +202 -0
  4. pgtern-0.3.0/MANIFEST.in +3 -0
  5. pgtern-0.3.0/PKG-INFO +265 -0
  6. pgtern-0.3.0/README.md +240 -0
  7. pgtern-0.3.0/SECURITY.md +31 -0
  8. pgtern-0.3.0/pyproject.toml +45 -0
  9. pgtern-0.3.0/scripts/start-test-postgres.sh +63 -0
  10. pgtern-0.3.0/setup.cfg +4 -0
  11. pgtern-0.3.0/src/pgtern/__init__.py +46 -0
  12. pgtern-0.3.0/src/pgtern/_binary.py +226 -0
  13. pgtern-0.3.0/src/pgtern/_composite.py +103 -0
  14. pgtern-0.3.0/src/pgtern/_conn.py +907 -0
  15. pgtern-0.3.0/src/pgtern/_copy.py +186 -0
  16. pgtern-0.3.0/src/pgtern/_cursor.py +261 -0
  17. pgtern-0.3.0/src/pgtern/_dsn.py +182 -0
  18. pgtern-0.3.0/src/pgtern/_protocol.py +258 -0
  19. pgtern-0.3.0/src/pgtern/_query.py +69 -0
  20. pgtern-0.3.0/src/pgtern/_scram.py +101 -0
  21. pgtern-0.3.0/src/pgtern/_types.py +442 -0
  22. pgtern-0.3.0/src/pgtern/adapters.py +85 -0
  23. pgtern-0.3.0/src/pgtern/aio.py +1287 -0
  24. pgtern-0.3.0/src/pgtern/errors.py +248 -0
  25. pgtern-0.3.0/src/pgtern/hooks.py +53 -0
  26. pgtern-0.3.0/src/pgtern/pipeline.py +202 -0
  27. pgtern-0.3.0/src/pgtern/pool.py +309 -0
  28. pgtern-0.3.0/src/pgtern/py.typed +0 -0
  29. pgtern-0.3.0/src/pgtern/rows.py +31 -0
  30. pgtern-0.3.0/src/pgtern/sql.py +200 -0
  31. pgtern-0.3.0/src/pgtern/types/__init__.py +30 -0
  32. pgtern-0.3.0/src/pgtern/types/json.py +5 -0
  33. pgtern-0.3.0/src/pgtern.egg-info/PKG-INFO +265 -0
  34. pgtern-0.3.0/src/pgtern.egg-info/SOURCES.txt +48 -0
  35. pgtern-0.3.0/src/pgtern.egg-info/dependency_links.txt +1 -0
  36. pgtern-0.3.0/src/pgtern.egg-info/requires.txt +4 -0
  37. pgtern-0.3.0/src/pgtern.egg-info/top_level.txt +1 -0
  38. pgtern-0.3.0/tests/conftest.py +66 -0
  39. pgtern-0.3.0/tests/test_adapters.py +206 -0
  40. pgtern-0.3.0/tests/test_async.py +350 -0
  41. pgtern-0.3.0/tests/test_binary.py +235 -0
  42. pgtern-0.3.0/tests/test_executemany.py +105 -0
  43. pgtern-0.3.0/tests/test_executemany_async.py +135 -0
  44. pgtern-0.3.0/tests/test_features.py +238 -0
  45. pgtern-0.3.0/tests/test_integration.py +651 -0
  46. pgtern-0.3.0/tests/test_journey.py +409 -0
  47. pgtern-0.3.0/tests/test_pipeline.py +257 -0
  48. pgtern-0.3.0/tests/test_restart.py +85 -0
  49. pgtern-0.3.0/tests/test_transaction_pooler.py +109 -0
  50. pgtern-0.3.0/tests/test_unit.py +299 -0
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ All notable changes to pgtern are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
@@ -0,0 +1,63 @@
1
+ # Contributing to pgtern
2
+
3
+ Thank you for considering a contribution. pgtern is a small library with a strict scope:
4
+ zero runtime dependencies, standard library only, and a stable public API. Please keep
5
+ these in mind when you propose a change.
6
+
7
+ ## Getting started
8
+
9
+ ```
10
+ git clone <repository-url> pgtern
11
+ cd pgtern
12
+ python -m venv .venv && . .venv/bin/activate
13
+ pip install -e ".[dev]"
14
+ ```
15
+
16
+ ## Running the tests
17
+
18
+ The unit tests need no server:
19
+
20
+ ```
21
+ pytest tests/test_unit.py
22
+ ```
23
+
24
+ The full suite needs a PostgreSQL server. The helper script starts a throwaway cluster with
25
+ SCRAM, MD5, cleartext, trust and TLS users:
26
+
27
+ ```
28
+ eval "$(scripts/start-test-postgres.sh)"
29
+ pytest
30
+ scripts/start-test-postgres.sh stop
31
+ ```
32
+
33
+ To test another server, set `PGTERN_TEST_DSN` (and `PGTERN_TEST_HOST`, `PGTERN_TEST_PORT`
34
+ for the tests that open their own connections). Every change must pass the suite against
35
+ all supported PostgreSQL major versions.
36
+
37
+ ## Guidelines
38
+
39
+ - **No new runtime dependencies.** pgtern imports only the standard library. Test and build
40
+ tooling belongs in the `dev` extra.
41
+ - **Keep the public API stable.** Anything exported from `pgtern` or its submodules is public.
42
+ Changes that break it need a major version and a changelog entry.
43
+ - **Protocol changes need tests against a real server.** Mock tests cannot show that the
44
+ wire protocol is right.
45
+ - **Security-sensitive code** (authentication, TLS, parameter encoding) needs tests for the
46
+ failure paths as well as the success paths.
47
+ - **Style:** type-annotate public functions, keep modules focused, and write docstrings for
48
+ public behaviour.
49
+ - **Changelog:** add an entry under `[Unreleased]` in `CHANGELOG.md` for every user-visible
50
+ change.
51
+
52
+ ## Submitting a change
53
+
54
+ 1. Open an issue first for anything larger than a bug fix, so the design can be agreed early.
55
+ 2. Make focused commits with clear messages that explain the why.
56
+ 3. Run the full test suite against at least PostgreSQL 14 and the newest supported version.
57
+ 4. Open a pull request describing the change, how it was tested, and any compatibility impact.
58
+
59
+ By contributing, you agree that your contribution is licensed under the Apache License 2.0.
60
+
61
+ ## Reporting security issues
62
+
63
+ Do not open a public issue for a vulnerability. See [SECURITY.md](SECURITY.md).
pgtern-0.3.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ include CHANGELOG.md CONTRIBUTING.md SECURITY.md
2
+ recursive-include tests *.py
3
+ include scripts/*.sh
pgtern-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgtern
3
+ Version: 0.3.0
4
+ Summary: A zero-dependency, pure-Python PostgreSQL client with blocking and asyncio APIs.
5
+ Author: Ahmad Karawash
6
+ License-Expression: Apache-2.0
7
+ Keywords: postgresql,postgres,database,driver,dbapi,scram,pure-python,zero-dependency
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Database
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8; extra == "dev"
23
+ Requires-Dist: build>=1.2; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # pgtern
27
+
28
+ **A PostgreSQL client for Python with zero dependencies.**
29
+
30
+ pgtern speaks the PostgreSQL wire protocol directly, in pure Python and the standard library only. There is no C library dependency, no C extension and no build step, so `pip install pgtern` is the whole setup. It offers a familiar DB-API style interface in two flavours: blocking, and `asyncio`.
31
+
32
+ ```python
33
+ import pgtern
34
+ from pgtern.rows import dict_row
35
+
36
+ with pgtern.connect("postgresql://app:secret@localhost/app", row_factory=dict_row) as conn:
37
+ with conn.transaction():
38
+ conn.execute("INSERT INTO notes (body) VALUES (%s)", ["hello"])
39
+ print(conn.execute("SELECT id, body FROM notes ORDER BY id").fetchall())
40
+ ```
41
+
42
+ ```python
43
+ import asyncio
44
+ from pgtern import aio
45
+
46
+ async def main():
47
+ async with aio.AsyncConnectionPool("postgresql://app:secret@localhost/app", min_size=2, max_size=10) as pool:
48
+ async with pool.connection() as conn:
49
+ cur = await conn.execute("SELECT %s::int", [1])
50
+ print(cur.fetchall())
51
+
52
+ asyncio.run(main())
53
+ ```
54
+
55
+ ## Why pgtern
56
+
57
+ - **Nothing to audit but the code you run.** No transitive dependencies means no dependency tree to pin, scan or keep patched. The package is a small, readable, pure-Python wheel.
58
+ - **Installs anywhere Python runs.** No compiler, no system libraries, no architecture-specific binaries. Containers, minimal images and locked-down hosts all get the same package.
59
+ - **Encrypted by default, verifiable.** SCRAM-SHA-256 authentication, TLS whenever the server offers it, and certificate and hostname verification with `sslmode=verify-full`.
60
+ - **Blocking and async, one API.** The same concepts, names and behaviour in `pgtern` and `pgtern.aio`, including pools, transactions, COPY and notifications.
61
+ - **Fast bulk writes.** `executemany` sends a whole batch as a single pipelined transaction. In measurements on PostgreSQL 16 it ran about five times faster than a row-by-row loop, both blocking and async.
62
+ - **Built for modern deployments.** It uses unnamed prepared statements only, so it cooperates with transaction-mode connection poolers. Pools check connections before handing them out and replace any the server has closed.
63
+
64
+ ## Install
65
+
66
+ ```
67
+ pip install pgtern
68
+ ```
69
+
70
+ Requires Python 3.11 or newer.
71
+
72
+ ## Connecting
73
+
74
+ `pgtern.connect` accepts URL and key=value DSNs, the standard `PG*` environment variables, Unix sockets, and a list of hosts for failover.
75
+
76
+ ```python
77
+ conn = pgtern.connect("postgresql://app@db1.internal,db2.internal/app?sslmode=verify-full&sslrootcert=/etc/ssl/ca.pem")
78
+ ```
79
+
80
+ TLS modes follow the PostgreSQL convention: `disable`, `allow`, `prefer`, `require`, `verify-ca` and `verify-full`. Authentication supports SCRAM-SHA-256, MD5, cleartext and trust.
81
+
82
+ ## Queries and transactions
83
+
84
+ ```python
85
+ with pgtern.connect(dsn) as conn:
86
+ conn.execute("CREATE TABLE IF NOT EXISTS accounts (id int PRIMARY KEY, balance numeric)")
87
+
88
+ with conn.transaction(): # commits on success, rolls back on error
89
+ conn.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", [10, 1])
90
+ conn.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", [10, 2])
91
+
92
+ cur = conn.execute("SELECT id, balance FROM accounts WHERE balance > %s", [0])
93
+ for row in cur:
94
+ print(row)
95
+ ```
96
+
97
+ Parameters use `%s` placeholders and are always sent separately from the SQL text. The `sql` module composes identifiers and literals safely:
98
+
99
+ ```python
100
+ import pgtern
101
+ from pgtern import sql
102
+
103
+ with pgtern.connect(dsn) as conn:
104
+ query = sql.SQL("SELECT * FROM {} WHERE id = %s").format(sql.Identifier("accounts"))
105
+ conn.execute(query, [1])
106
+ ```
107
+
108
+ ## Rows
109
+
110
+ Choose how rows come back with a row factory: `tuple_row` (the default), `dict_row`, or `namedtuple_row`. Pass one to `connect` or to a single cursor.
111
+
112
+ ## Bulk loading
113
+
114
+ `executemany` sends the whole batch as one pipelined transaction. In autocommit mode a failing row rolls back the entire batch; inside a transaction it aborts that transaction, as usual.
115
+
116
+ ```python
117
+ with pgtern.connect(dsn, autocommit=True) as conn:
118
+ conn.cursor().executemany("INSERT INTO events (kind, payload) VALUES (%s, %s)", rows)
119
+ ```
120
+
121
+ For the fastest loads, use `COPY`:
122
+
123
+ ```python
124
+ with pgtern.connect(dsn) as conn:
125
+ with conn.cursor().copy("COPY events (kind, payload) FROM STDIN") as copy:
126
+ for kind, payload in rows:
127
+ copy.write_row((kind, payload))
128
+ ```
129
+
130
+ Exporting works the same way with `COPY ... TO STDOUT`, read through `for chunk in copy` or `copy.rows()`.
131
+
132
+ ## Streaming large results
133
+
134
+ A named cursor runs on the server and fetches in batches, so a result never has to fit in memory:
135
+
136
+ ```python
137
+ with pgtern.connect(dsn) as conn:
138
+ with conn.transaction():
139
+ with conn.cursor("big_report") as cur:
140
+ cur.execute("SELECT * FROM events")
141
+ cur.itersize = 1000
142
+ for row in cur:
143
+ process(row)
144
+ ```
145
+
146
+ Server-side cursors support `scrollable`, `withhold` and `scroll()`.
147
+
148
+ ## Real-time notifications
149
+
150
+ ```python
151
+ with pgtern.connect(dsn) as conn:
152
+ conn.execute("LISTEN orders")
153
+ for note in conn.notifies(timeout=30):
154
+ print(note.channel, note.payload)
155
+ ```
156
+
157
+ The asyncio connection supports `async for` over the same notifications. Session features such as `LISTEN` run on a direct or session-mode connection.
158
+
159
+ ## Binary format and pipelines
160
+
161
+ Opt into binary transfer per statement with `binary=True`. It covers integers, floats, booleans, text, bytea, uuid, dates and times, intervals, json/jsonb, numeric results and one-dimensional arrays of these. Other types keep using text.
162
+
163
+ Pipeline mode sends many statements before reading any reply:
164
+
165
+ ```python
166
+ with pgtern.connect(dsn) as conn:
167
+ with conn.pipeline() as pipe:
168
+ a = pipe.execute("INSERT INTO queue (job) VALUES (%s)", ["a"])
169
+ b = pipe.execute("SELECT count(*) FROM queue")
170
+ print(b.fetchone()) # results are ready once the block ends
171
+ ```
172
+
173
+ Statements are read in order at each sync point (`pipe.sync()`, the end of the block, or every `batch_size` statements). With `autocommit=True` a sync point is a commit point, so the statements in one batch succeed or fail together. Statements after a failure are skipped and raise `pgtern.errors.PipelineAborted`.
174
+
175
+ ## Custom types
176
+
177
+ Register how a PostgreSQL type becomes a Python value, and how a Python class is sent:
178
+
179
+ ```python
180
+ from enum import Enum
181
+ from pgtern import adapters
182
+
183
+ class Mood(Enum):
184
+ SAD = "sad"
185
+ HAPPY = "happy"
186
+
187
+ adapters.register_loader("mood", adapters.enum_loader(Mood)) # CREATE TYPE mood AS ENUM (...)
188
+ adapters.register_loader("span", adapters.range_loader(int)) # CREATE TYPE span AS RANGE (subtype = int4)
189
+ adapters.register_dumper(Mood, lambda m: m.value)
190
+ ```
191
+
192
+ Loaders are looked up by type name once per connection and cached. Registering a loader applies to connections opened afterwards, and to pooled connections once they are returned to the pool.
193
+
194
+ ## Pools
195
+
196
+ ```python
197
+ from pgtern.pool import ConnectionPool
198
+
199
+ pool = ConnectionPool(dsn, min_size=4, max_size=20, timeout=5)
200
+ with pool.connection() as conn:
201
+ conn.execute("SELECT 1")
202
+ ```
203
+
204
+ Pools keep `min_size` connections warm and grow to `max_size` on demand. A connection is checked for liveness each time it is handed out, rolled back if it comes back mid-transaction, and replaced when the server has closed it. Waiting callers receive `pgtern.PoolTimeout` after `timeout` seconds.
205
+
206
+ ## Observability
207
+
208
+ Query hooks see every statement and its row count, without ever seeing bound parameter values:
209
+
210
+ ```python
211
+ from contextlib import contextmanager
212
+ import pgtern
213
+ import time
214
+
215
+ @contextmanager
216
+ def timing(info):
217
+ started = time.perf_counter()
218
+ try:
219
+ yield
220
+ finally:
221
+ print(f"{info.statement!r} took {time.perf_counter() - started:.3f}s ({info.rowcount} rows)")
222
+
223
+ remove = pgtern.add_query_hook(timing)
224
+ ```
225
+
226
+ The same hook point works for OpenTelemetry spans, metrics, and audit logging.
227
+
228
+ ## Errors
229
+
230
+ Every error is a subclass of `pgtern.Error`, and each common SQLSTATE has its own class, such as `UniqueViolation` or `DeadlockDetected`. Catch the family you need, or the specific case:
231
+
232
+ ```python
233
+ with pgtern.connect(dsn) as conn:
234
+ try:
235
+ conn.execute("INSERT INTO accounts (id) VALUES (%s)", [1])
236
+ except pgtern.IntegrityError:
237
+ ...
238
+ ```
239
+
240
+ ## Compatibility
241
+
242
+ - **PostgreSQL:** 14, 15, 16, 17 and 18.
243
+ - **Python:** 3.11 and newer. The continuous integration workflow runs the test suite on every supported version.
244
+ - **Platforms:** anywhere CPython runs.
245
+
246
+ ## Development
247
+
248
+ ```
249
+ pip install -e ".[dev]"
250
+ eval "$(scripts/start-test-postgres.sh)" # throwaway server with SCRAM, MD5, cleartext, trust and TLS users
251
+ pytest
252
+ scripts/start-test-postgres.sh stop
253
+ ```
254
+
255
+ Without a server the unit tests still run. The integration tests need `PGTERN_TEST_DSN`; the optional suites read `PGTERN_TEST_POOLER_DSN` (a transaction-mode connection pooler) and `PGTERN_TEST_RESTART_CMD` (a command that restarts the server). See `CONTRIBUTING.md` for the full workflow.
256
+
257
+ ## Documentation and support
258
+
259
+ - Release history: [CHANGELOG.md](CHANGELOG.md)
260
+ - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
261
+ - Security reports: [SECURITY.md](SECURITY.md)
262
+
263
+ ## License
264
+
265
+ Apache License 2.0. See [LICENSE](LICENSE).