sanka-connector-postgres 0.1.0a10__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,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ release/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ .DS_Store
@@ -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,59 @@
1
+ Metadata-Version: 2.5
2
+ Name: sanka-connector-postgres
3
+ Version: 0.1.0a10
4
+ Summary: PostgreSQL connector for the Sanka migration runtime
5
+ Project-URL: Repository, https://github.com/sankaHQ/sanka-connectors
6
+ Project-URL: Issues, https://github.com/sankaHQ/sanka-connectors/issues
7
+ Author: Sanka, Inc.
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: psycopg[binary]>=3.2
12
+ Requires-Dist: sanka-connector-sdk==0.1.0a10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # PostgreSQL connector
16
+
17
+ PostgreSQL connector for Sanka, registering both roles under the `postgres`
18
+ type. The DSN arrives in `settings["connection"]` (`postgres://…`,
19
+ `postgresql://…`, or a libpq keyword string); `settings["schema"]` selects the
20
+ schema (default `public`). Uses psycopg 3's async API with one cached
21
+ connection per DSN per event loop; all identifiers are quoted with
22
+ `psycopg.sql.Identifier`.
23
+
24
+ **Source**: discovers BASE TABLEs, inventories columns/type families/exact
25
+ counts, and reads with keyset pagination on the single-column primary key
26
+ (`WHERE pk > cursor ORDER BY pk LIMIT n`). Cursors and snapshot bounds are the
27
+ JSON-safe string of the key value; integer keys are re-cast client-side, every
28
+ other key type is sent as an untyped literal the server casts back to the
29
+ column's native type — so ordering is always native-type ordering, never text
30
+ ordering. Tables with a composite, missing, or bytea primary key are
31
+ inventoried with a warning and no identity fields (the planner skips them).
32
+ Values come back JSON-safe: datetime/date/time → ISO 8601 strings, `Decimal` →
33
+ string, `UUID` → string, json/jsonb → dict/list, other exotic scalars → their
34
+ string form. `bytea` columns are excluded from the inventoried fields, and any
35
+ binary value that still shows up in a read is dropped from the record with a
36
+ one-time warning per column. Capabilities: exact counts
37
+ (`SupportsRecordCounts`) and snapshot bounds via `MAX(pk)`
38
+ (`SupportsSnapshotBounds`). Source filters are not supported yet and raise
39
+ `UnsupportedFeatureError` rather than being silently ignored.
40
+
41
+ **Destination**: creates tables lazily from first-seen Python values
42
+ (bool → `boolean`, int → `bigint`, float → `double precision`, dict/list →
43
+ `jsonb`, everything else → `text`), widens with
44
+ `ALTER TABLE … ADD COLUMN IF NOT EXISTS`, creates the target schema if
45
+ missing, and puts a `CREATE UNIQUE INDEX IF NOT EXISTS` on the identity
46
+ columns. Mixed-type source fields never fail the run: when a value cannot be
47
+ represented in a column this destination minted, the column is promoted up the
48
+ boolean → bigint → double precision → text ladder
49
+ (`ALTER COLUMN … TYPE … USING`), losslessly. Conflicts follow `WriteOptions.conflict_policy` via an identity
50
+ pre-SELECT (skip/update/plain-insert). `destination_record_id` is the identity
51
+ value as a string when exactly one identity field is present, else `None` —
52
+ PostgreSQL has no stable rowid, and `ctid` moves. Params are adapted to the
53
+ actual column type: dict/list → psycopg `Json` for json/jsonb columns (scalars
54
+ written to jsonb are JSON-encoded too), non-string values headed for text
55
+ columns are stringified client-side, and strings are sent untyped so the
56
+ server casts them into any column.
57
+
58
+ Apache-2.0; depends only on the `sanka-connector-sdk` interface and `psycopg[binary]`.
59
+ Integration tests need `SANKA_MIGRATE_TEST_POSTGRES_DSN` and skip cleanly without it.
@@ -0,0 +1,45 @@
1
+ # PostgreSQL connector
2
+
3
+ PostgreSQL connector for Sanka, registering both roles under the `postgres`
4
+ type. The DSN arrives in `settings["connection"]` (`postgres://…`,
5
+ `postgresql://…`, or a libpq keyword string); `settings["schema"]` selects the
6
+ schema (default `public`). Uses psycopg 3's async API with one cached
7
+ connection per DSN per event loop; all identifiers are quoted with
8
+ `psycopg.sql.Identifier`.
9
+
10
+ **Source**: discovers BASE TABLEs, inventories columns/type families/exact
11
+ counts, and reads with keyset pagination on the single-column primary key
12
+ (`WHERE pk > cursor ORDER BY pk LIMIT n`). Cursors and snapshot bounds are the
13
+ JSON-safe string of the key value; integer keys are re-cast client-side, every
14
+ other key type is sent as an untyped literal the server casts back to the
15
+ column's native type — so ordering is always native-type ordering, never text
16
+ ordering. Tables with a composite, missing, or bytea primary key are
17
+ inventoried with a warning and no identity fields (the planner skips them).
18
+ Values come back JSON-safe: datetime/date/time → ISO 8601 strings, `Decimal` →
19
+ string, `UUID` → string, json/jsonb → dict/list, other exotic scalars → their
20
+ string form. `bytea` columns are excluded from the inventoried fields, and any
21
+ binary value that still shows up in a read is dropped from the record with a
22
+ one-time warning per column. Capabilities: exact counts
23
+ (`SupportsRecordCounts`) and snapshot bounds via `MAX(pk)`
24
+ (`SupportsSnapshotBounds`). Source filters are not supported yet and raise
25
+ `UnsupportedFeatureError` rather than being silently ignored.
26
+
27
+ **Destination**: creates tables lazily from first-seen Python values
28
+ (bool → `boolean`, int → `bigint`, float → `double precision`, dict/list →
29
+ `jsonb`, everything else → `text`), widens with
30
+ `ALTER TABLE … ADD COLUMN IF NOT EXISTS`, creates the target schema if
31
+ missing, and puts a `CREATE UNIQUE INDEX IF NOT EXISTS` on the identity
32
+ columns. Mixed-type source fields never fail the run: when a value cannot be
33
+ represented in a column this destination minted, the column is promoted up the
34
+ boolean → bigint → double precision → text ladder
35
+ (`ALTER COLUMN … TYPE … USING`), losslessly. Conflicts follow `WriteOptions.conflict_policy` via an identity
36
+ pre-SELECT (skip/update/plain-insert). `destination_record_id` is the identity
37
+ value as a string when exactly one identity field is present, else `None` —
38
+ PostgreSQL has no stable rowid, and `ctid` moves. Params are adapted to the
39
+ actual column type: dict/list → psycopg `Json` for json/jsonb columns (scalars
40
+ written to jsonb are JSON-encoded too), non-string values headed for text
41
+ columns are stringified client-side, and strings are sent untyped so the
42
+ server casts them into any column.
43
+
44
+ Apache-2.0; depends only on the `sanka-connector-sdk` interface and `psycopg[binary]`.
45
+ Integration tests need `SANKA_MIGRATE_TEST_POSTGRES_DSN` and skip cleanly without it.
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "sanka-connector-postgres"
3
+ version = "0.1.0a10"
4
+ description = "PostgreSQL connector for the Sanka migration runtime"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Sanka, Inc." }]
10
+ dependencies = ["psycopg[binary]>=3.2", "sanka-connector-sdk==0.1.0a10"]
11
+
12
+ [project.entry-points."sanka.connectors"]
13
+ postgres = "sanka_connector_postgres:CONNECTOR"
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/sankaHQ/sanka-connectors"
17
+ Issues = "https://github.com/sankaHQ/sanka-connectors/issues"
18
+
19
+ [build-system]
20
+ requires = ["hatchling>=1.27"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/sanka_connector_postgres"]
@@ -0,0 +1,24 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """PostgreSQL connector: source + destination roles for Sanka migrations.
3
+
4
+ The DSN arrives in ``settings["connection"]`` (``postgres://``,
5
+ ``postgresql://``, or a libpq keyword string); ``settings["schema"]`` picks
6
+ the schema (default ``public``). The source keyset-paginates on single-column
7
+ primary keys and returns JSON-safe values; the destination creates and widens
8
+ tables from the records written to them. See the package README for the
9
+ detailed typing, pagination, and identity semantics.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from sanka_connector import ConnectorRegistration
15
+ from sanka_connector_postgres._destination import PostgresDestination
16
+ from sanka_connector_postgres._source import PostgresSource
17
+
18
+ __all__ = ["CONNECTOR", "PostgresDestination", "PostgresSource"]
19
+
20
+ CONNECTOR = ConnectorRegistration(
21
+ name="postgres",
22
+ source=PostgresSource(),
23
+ destination=PostgresDestination(),
24
+ )
@@ -0,0 +1,286 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Shared internals for the PostgreSQL connector.
3
+
4
+ Connection management (one cached ``psycopg.AsyncConnection`` per DSN per
5
+ event loop, autocommit), identifier sanitization, source type-family mapping,
6
+ JSON-safe value conversion, cursor handling, and the psycopg → Sanka error
7
+ mapping. Both roles subclass :class:`PostgresConnectorBase`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import datetime
14
+ import re
15
+ import uuid
16
+ from collections.abc import AsyncIterator
17
+ from contextlib import asynccontextmanager
18
+ from decimal import Decimal
19
+ from typing import Any, Final
20
+
21
+ import psycopg
22
+ from psycopg.conninfo import conninfo_to_dict
23
+
24
+ from sanka_connector import (
25
+ AuthenticationError,
26
+ ConfigurationError,
27
+ ConflictError,
28
+ ConnectorError,
29
+ Credentials,
30
+ DataError,
31
+ ErrorCategory,
32
+ PermissionDeniedError,
33
+ ProviderTimeoutError,
34
+ TransientProviderError,
35
+ )
36
+
37
+ _IDENTIFIER = re.compile(r"[^a-z0-9_]+")
38
+ _MAX_IDENTIFIER_LENGTH = 63
39
+
40
+ # information_schema ``data_type`` groupings (already lowercase for built-ins).
41
+ _NUMBER_TYPES: Final = frozenset(
42
+ {"smallint", "integer", "bigint", "numeric", "decimal", "real", "double precision"}
43
+ )
44
+ _INTEGER_TYPES: Final = frozenset({"smallint", "integer", "bigint"})
45
+ _TEMPORAL_TYPES: Final = frozenset(
46
+ {
47
+ "date",
48
+ "time without time zone",
49
+ "time with time zone",
50
+ "timestamp without time zone",
51
+ "timestamp with time zone",
52
+ }
53
+ )
54
+ _JSON_TYPES: Final = frozenset({"json", "jsonb"})
55
+ _BINARY_TYPES: Final = frozenset({"bytea"})
56
+
57
+ #: Sentinel returned by :func:`json_safe` for binary values the connector skips.
58
+ SKIPPED_BINARY: Final = object()
59
+
60
+
61
+ def identifier(value: str, *, kind: str) -> str:
62
+ """Sanitize ``value`` into a lowercase PostgreSQL identifier."""
63
+ normalized = _IDENTIFIER.sub("_", value.strip().lower()).strip("_")
64
+ if not normalized:
65
+ raise DataError(f"cannot derive a PostgreSQL {kind} name from {value!r}")
66
+ if normalized[0].isdigit():
67
+ normalized = f"t_{normalized}"
68
+ if len(normalized) > _MAX_IDENTIFIER_LENGTH:
69
+ normalized = normalized[:_MAX_IDENTIFIER_LENGTH].rstrip("_")
70
+ return normalized
71
+
72
+
73
+ def field_family(data_type: str) -> str:
74
+ """Map an information_schema ``data_type`` to a Sanka field type family."""
75
+ lowered = data_type.lower()
76
+ if lowered in _NUMBER_TYPES:
77
+ return "number"
78
+ if lowered == "boolean":
79
+ return "boolean"
80
+ if lowered in _JSON_TYPES:
81
+ return "object"
82
+ return "string"
83
+
84
+
85
+ def is_temporal(data_type: str) -> bool:
86
+ return data_type.lower() in _TEMPORAL_TYPES
87
+
88
+
89
+ def is_binary(data_type: str) -> bool:
90
+ return data_type.lower() in _BINARY_TYPES
91
+
92
+
93
+ def is_integer(data_type: str) -> bool:
94
+ return data_type.lower() in _INTEGER_TYPES
95
+
96
+
97
+ def json_safe(value: Any) -> Any:
98
+ """Convert a fetched value into a JSON-safe Python value.
99
+
100
+ datetime/date/time → ISO 8601 string, ``Decimal`` → string (no precision
101
+ loss), ``UUID`` → string, containers convert recursively (binary elements
102
+ become ``None``), binary scalars return :data:`SKIPPED_BINARY` so callers
103
+ can drop the column, and any other exotic scalar becomes its ``str`` form.
104
+ """
105
+ if value is None or isinstance(value, bool | int | float | str):
106
+ return value
107
+ if isinstance(value, datetime.datetime | datetime.date | datetime.time):
108
+ return value.isoformat()
109
+ if isinstance(value, Decimal):
110
+ return str(value)
111
+ if isinstance(value, uuid.UUID):
112
+ return str(value)
113
+ if isinstance(value, bytes | bytearray | memoryview):
114
+ return SKIPPED_BINARY
115
+ if isinstance(value, list | tuple):
116
+ return [_element(item) for item in value]
117
+ if isinstance(value, dict):
118
+ return {str(key): _element(item) for key, item in value.items()}
119
+ return str(value)
120
+
121
+
122
+ def _element(item: Any) -> Any:
123
+ converted = json_safe(item)
124
+ return None if converted is SKIPPED_BINARY else converted
125
+
126
+
127
+ def cursor_text(value: Any) -> str:
128
+ """Render a key value as an opaque string cursor / snapshot bound."""
129
+ converted = json_safe(value)
130
+ if converted is SKIPPED_BINARY or converted is None:
131
+ raise DataError("cannot build a pagination cursor from a binary or NULL key value")
132
+ return converted if isinstance(converted, str) else str(converted)
133
+
134
+
135
+ def cursor_param(data_type: str, text: str) -> Any:
136
+ """Turn a string cursor back into a query parameter for the key column.
137
+
138
+ Integer-family keys are cast client-side; every other key type is sent as
139
+ a string, which psycopg dumps with unknown OID so the server casts it to
140
+ the column's native type — comparisons always run in that native type.
141
+ """
142
+ if is_integer(data_type):
143
+ try:
144
+ return int(text)
145
+ except ValueError as error:
146
+ raise DataError(f"cursor {text!r} is not valid for a {data_type} key") from error
147
+ return text
148
+
149
+
150
+ def mapped_error(error: psycopg.Error, *, context: str) -> ConnectorError:
151
+ """Map a psycopg exception onto the Sanka error taxonomy."""
152
+ message = f"{context}: {error}"
153
+ sqlstate = error.sqlstate or ""
154
+ if sqlstate.startswith("28") or "authentication failed" in str(error).lower():
155
+ return AuthenticationError(message)
156
+ if sqlstate == "42501":
157
+ return PermissionDeniedError(message)
158
+ if sqlstate in ("42P01", "42703"):
159
+ return DataError(message)
160
+ if sqlstate == "23505":
161
+ return ConflictError(message)
162
+ if sqlstate == "57014":
163
+ return ProviderTimeoutError(message)
164
+ if sqlstate.startswith(("08", "53", "57", "58")):
165
+ return TransientProviderError(message)
166
+ if isinstance(error, psycopg.OperationalError):
167
+ # Connection refused / DNS / timeouts / broken connections.
168
+ return TransientProviderError(message)
169
+ return ConnectorError(message, category=ErrorCategory.UNKNOWN)
170
+
171
+
172
+ @asynccontextmanager
173
+ async def pg_errors(context: str) -> AsyncIterator[None]:
174
+ """Re-raise psycopg failures as Sanka connector errors."""
175
+ try:
176
+ yield
177
+ except psycopg.Error as error:
178
+ raise mapped_error(error, context=context) from error
179
+
180
+
181
+ _TABLES_SQL = """
182
+ SELECT table_name
183
+ FROM information_schema.tables
184
+ WHERE table_schema = %s AND table_type = 'BASE TABLE'
185
+ ORDER BY table_name
186
+ """
187
+
188
+ _COLUMNS_SQL = """
189
+ SELECT column_name, data_type
190
+ FROM information_schema.columns
191
+ WHERE table_schema = %s AND table_name = %s
192
+ ORDER BY ordinal_position
193
+ """
194
+
195
+ _PRIMARY_KEY_SQL = """
196
+ SELECT kcu.column_name, col.data_type
197
+ FROM information_schema.table_constraints tc
198
+ JOIN information_schema.key_column_usage kcu
199
+ ON kcu.constraint_schema = tc.constraint_schema
200
+ AND kcu.constraint_name = tc.constraint_name
201
+ AND kcu.table_schema = tc.table_schema
202
+ AND kcu.table_name = tc.table_name
203
+ JOIN information_schema.columns col
204
+ ON col.table_schema = kcu.table_schema
205
+ AND col.table_name = kcu.table_name
206
+ AND col.column_name = kcu.column_name
207
+ WHERE tc.constraint_type = 'PRIMARY KEY'
208
+ AND tc.table_schema = %s
209
+ AND tc.table_name = %s
210
+ ORDER BY kcu.ordinal_position
211
+ """
212
+
213
+
214
+ class PostgresConnectorBase:
215
+ """Connection and information_schema plumbing shared by both roles."""
216
+
217
+ provider = "postgres"
218
+ binding_kind = "database"
219
+
220
+ def __init__(self) -> None:
221
+ self._connections: dict[tuple[int, str], psycopg.AsyncConnection[Any]] = {}
222
+
223
+ async def close(self) -> None:
224
+ """Close connections cached for the running event loop (test hygiene;
225
+ the runtime does not require it)."""
226
+ loop_id = id(asyncio.get_running_loop())
227
+ for key in [key for key in self._connections if key[0] == loop_id]:
228
+ connection = self._connections.pop(key)
229
+ if not connection.closed:
230
+ await connection.close()
231
+
232
+ # -- internals ----------------------------------------------------------
233
+
234
+ def _dsn(self, credentials: Credentials) -> str:
235
+ raw = credentials.settings.get("connection")
236
+ if raw is None or not str(raw).strip():
237
+ raise ConfigurationError(
238
+ "postgres connector needs a DSN in settings['connection']"
239
+ " (postgres://…, postgresql://…, or a libpq keyword string)"
240
+ )
241
+ dsn = str(raw).strip()
242
+ try:
243
+ conninfo_to_dict(dsn)
244
+ except psycopg.ProgrammingError as error:
245
+ raise ConfigurationError(f"invalid postgres DSN: {error}") from error
246
+ return dsn
247
+
248
+ def _schema_name(self, credentials: Credentials) -> str:
249
+ raw = credentials.settings.get("schema", "public")
250
+ if not isinstance(raw, str) or not raw.strip():
251
+ raise ConfigurationError("settings['schema'] must be a non-empty schema name")
252
+ return raw.strip()
253
+
254
+ async def _connection(self, credentials: Credentials) -> psycopg.AsyncConnection[Any]:
255
+ """One cached connection per (event loop, DSN).
256
+
257
+ Keying by loop matters because the registration object is a process
258
+ singleton: successive ``asyncio.run`` calls (CLI invocations, test
259
+ functions) must not share a loop-bound connection. Connections from
260
+ finished loops are simply dropped; broken or closed connections are
261
+ replaced on the next call.
262
+ """
263
+ dsn = self._dsn(credentials)
264
+ key = (id(asyncio.get_running_loop()), dsn)
265
+ cached = self._connections.get(key)
266
+ if cached is not None and not cached.closed and not cached.broken:
267
+ return cached
268
+ connection = await psycopg.AsyncConnection.connect(dsn, autocommit=True)
269
+ self._connections[key] = connection
270
+ return connection
271
+
272
+ async def _tables(self, connection: psycopg.AsyncConnection[Any], schema: str) -> list[str]:
273
+ cursor = await connection.execute(_TABLES_SQL, (schema,))
274
+ return [str(row[0]) for row in await cursor.fetchall()]
275
+
276
+ async def _columns(
277
+ self, connection: psycopg.AsyncConnection[Any], schema: str, table: str
278
+ ) -> list[tuple[str, str]]:
279
+ cursor = await connection.execute(_COLUMNS_SQL, (schema, table))
280
+ return [(str(row[0]), str(row[1])) for row in await cursor.fetchall()]
281
+
282
+ async def _primary_key_columns(
283
+ self, connection: psycopg.AsyncConnection[Any], schema: str, table: str
284
+ ) -> list[tuple[str, str]]:
285
+ cursor = await connection.execute(_PRIMARY_KEY_SQL, (schema, table))
286
+ return [(str(row[0]), str(row[1])) for row in await cursor.fetchall()]