datus-postgresql 0.1.8__tar.gz → 0.1.11__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.
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/.gitignore +8 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/PKG-INFO +47 -4
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/README.md +41 -0
- datus_postgresql-0.1.11/datus_postgresql/config.py +55 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/datus_postgresql/connector.py +82 -11
- datus_postgresql-0.1.11/datus_postgresql/testing.py +54 -0
- datus_postgresql-0.1.11/datus_postgresql/timeouts.py +127 -0
- datus_postgresql-0.1.11/datus_postgresql/tpch_data.py +84 -0
- datus_postgresql-0.1.11/docker-compose.tls.yml +13 -0
- datus_postgresql-0.1.11/docker-compose.yml +25 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/pyproject.toml +6 -3
- datus_postgresql-0.1.11/scripts/init_tpch_data.py +129 -0
- datus_postgresql-0.1.11/tests/integration/conftest.py +119 -0
- datus_postgresql-0.1.11/tests/integration/test_aurora_cloud.py +57 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/integration/test_integration.py +47 -39
- datus_postgresql-0.1.11/tests/integration/test_metadata_retrieval.py +48 -0
- datus_postgresql-0.1.11/tests/integration/test_timeouts.py +99 -0
- datus_postgresql-0.1.11/tests/integration/test_tls.py +47 -0
- datus_postgresql-0.1.11/tests/integration/test_tpch.py +182 -0
- datus_postgresql-0.1.11/tests/unit/test_aurora.py +113 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/unit/test_config.py +2 -4
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/unit/test_connector_unit.py +74 -8
- datus_postgresql-0.1.11/tests/unit/test_timeouts.py +344 -0
- datus_postgresql-0.1.8/datus_postgresql/config.py +0 -29
- datus_postgresql-0.1.8/docker-compose.yml +0 -20
- datus_postgresql-0.1.8/scripts/init_tpch_data.py +0 -555
- datus_postgresql-0.1.8/tests/integration/conftest.py +0 -536
- datus_postgresql-0.1.8/tests/integration/test_tpch.py +0 -162
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/datus_postgresql/__init__.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/datus_postgresql/handlers.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/__init__.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/conftest.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/integration/__init__.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/integration/test_contract.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/unit/__init__.py +0 -0
- {datus_postgresql-0.1.8 → datus_postgresql-0.1.11}/tests/unit/test_migration_mixin.py +0 -0
|
@@ -136,6 +136,14 @@ dmypy.json
|
|
|
136
136
|
.DS_Store
|
|
137
137
|
Thumbs.db
|
|
138
138
|
|
|
139
|
+
# AI agent local state (AGENTS.md and CLAUDE.md are tracked)
|
|
140
|
+
.claude/
|
|
141
|
+
|
|
142
|
+
# Generated by ci/run_pr_coverage.py
|
|
143
|
+
ci/coverage.xml
|
|
144
|
+
ci/diff-cover.json
|
|
145
|
+
ci/diff-cover-report.md
|
|
146
|
+
|
|
139
147
|
|
|
140
148
|
.omc
|
|
141
149
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: datus-postgresql
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.11
|
|
4
4
|
Summary: PostgreSQL database adapter for Datus
|
|
5
5
|
Project-URL: Homepage, https://github.com/Datus-ai/datus-db-adapters
|
|
6
6
|
Project-URL: Repository, https://github.com/Datus-ai/datus-db-adapters
|
|
@@ -14,16 +14,59 @@ Classifier: License :: OSI Approved :: Apache Software License
|
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
16
|
Requires-Python: >=3.12
|
|
17
|
-
Requires-Dist: datus-db-core>=0.1.
|
|
18
|
-
Requires-Dist: datus-sqlalchemy>=0.1.
|
|
17
|
+
Requires-Dist: datus-db-core>=0.1.9
|
|
18
|
+
Requires-Dist: datus-sqlalchemy>=0.1.11
|
|
19
19
|
Requires-Dist: psycopg2-binary>=2.9.11
|
|
20
20
|
Requires-Dist: pydantic>=2.0.0
|
|
21
|
+
Provides-Extra: aws
|
|
22
|
+
Requires-Dist: datus-db-core[aws]>=0.1.8; extra == 'aws'
|
|
21
23
|
Description-Content-Type: text/markdown
|
|
22
24
|
|
|
23
25
|
# datus-postgresql
|
|
24
26
|
|
|
25
27
|
PostgreSQL database adapter for [Datus](https://github.com/Datus-ai/datus-agent).
|
|
26
28
|
|
|
29
|
+
## Timeouts
|
|
30
|
+
|
|
31
|
+
`timeout_seconds` must be positive and now bounds driver I/O as well as pool
|
|
32
|
+
checkout where applicable. Long operations may need a larger value. Server
|
|
33
|
+
execution deadlines and supported overrides are described in the shared
|
|
34
|
+
[timeout policy and real-database validation](../docs/adapter-timeouts.md).
|
|
35
|
+
A socket/RPC timeout is distinct from an overall operation deadline.
|
|
36
|
+
|
|
37
|
+
## Amazon Aurora PostgreSQL
|
|
38
|
+
|
|
39
|
+
Aurora uses this adapter with the PostgreSQL dialect. Set `aurora=True` and provide
|
|
40
|
+
`sslrootcert`; the adapter requires `sslmode=verify-full`. Password authentication
|
|
41
|
+
needs no AWS SDK. Install `pip install 'datus-postgresql[aws]'` for IAM or Secrets Manager.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import os
|
|
45
|
+
from datus_postgresql import PostgreSQLConnector
|
|
46
|
+
|
|
47
|
+
connector = PostgreSQLConnector({
|
|
48
|
+
"host": os.environ["AURORA_POSTGRESQL_ENDPOINT"],
|
|
49
|
+
"username": os.environ["AURORA_DB_USER"],
|
|
50
|
+
"database": os.environ["AURORA_DATABASE"],
|
|
51
|
+
"aurora": True,
|
|
52
|
+
"auth_mode": "iam",
|
|
53
|
+
"aws": {"region": os.environ["AWS_REGION"]},
|
|
54
|
+
"sslrootcert": os.environ["AURORA_CA_BUNDLE"],
|
|
55
|
+
})
|
|
56
|
+
try:
|
|
57
|
+
result = connector.execute_query("SELECT 1", result_format="list")
|
|
58
|
+
assert result.success, result.error
|
|
59
|
+
finally:
|
|
60
|
+
connector.close()
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
TLS and dynamic credentials apply to the base engine and every cached database
|
|
64
|
+
engine. See [Aurora authentication and lifecycle](../docs/aurora.md) for the full
|
|
65
|
+
contract, IAM permissions/user setup, Role profiles, Secret rotation and pending
|
|
66
|
+
cloud acceptance. From the workspace root,
|
|
67
|
+
`uv run --no-project python -m ci.run_tls_integration_tests postgresql` runs verified
|
|
68
|
+
TLS, multiple databases, shared contracts and wrong-CA/hostname rejection.
|
|
69
|
+
|
|
27
70
|
## Overview
|
|
28
71
|
|
|
29
72
|
This adapter provides PostgreSQL connectivity for Datus, supporting full SQL operations, metadata discovery, schema management, and materialized views via the standard PostgreSQL protocol.
|
|
@@ -2,6 +2,47 @@
|
|
|
2
2
|
|
|
3
3
|
PostgreSQL database adapter for [Datus](https://github.com/Datus-ai/datus-agent).
|
|
4
4
|
|
|
5
|
+
## Timeouts
|
|
6
|
+
|
|
7
|
+
`timeout_seconds` must be positive and now bounds driver I/O as well as pool
|
|
8
|
+
checkout where applicable. Long operations may need a larger value. Server
|
|
9
|
+
execution deadlines and supported overrides are described in the shared
|
|
10
|
+
[timeout policy and real-database validation](../docs/adapter-timeouts.md).
|
|
11
|
+
A socket/RPC timeout is distinct from an overall operation deadline.
|
|
12
|
+
|
|
13
|
+
## Amazon Aurora PostgreSQL
|
|
14
|
+
|
|
15
|
+
Aurora uses this adapter with the PostgreSQL dialect. Set `aurora=True` and provide
|
|
16
|
+
`sslrootcert`; the adapter requires `sslmode=verify-full`. Password authentication
|
|
17
|
+
needs no AWS SDK. Install `pip install 'datus-postgresql[aws]'` for IAM or Secrets Manager.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import os
|
|
21
|
+
from datus_postgresql import PostgreSQLConnector
|
|
22
|
+
|
|
23
|
+
connector = PostgreSQLConnector({
|
|
24
|
+
"host": os.environ["AURORA_POSTGRESQL_ENDPOINT"],
|
|
25
|
+
"username": os.environ["AURORA_DB_USER"],
|
|
26
|
+
"database": os.environ["AURORA_DATABASE"],
|
|
27
|
+
"aurora": True,
|
|
28
|
+
"auth_mode": "iam",
|
|
29
|
+
"aws": {"region": os.environ["AWS_REGION"]},
|
|
30
|
+
"sslrootcert": os.environ["AURORA_CA_BUNDLE"],
|
|
31
|
+
})
|
|
32
|
+
try:
|
|
33
|
+
result = connector.execute_query("SELECT 1", result_format="list")
|
|
34
|
+
assert result.success, result.error
|
|
35
|
+
finally:
|
|
36
|
+
connector.close()
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
TLS and dynamic credentials apply to the base engine and every cached database
|
|
40
|
+
engine. See [Aurora authentication and lifecycle](../docs/aurora.md) for the full
|
|
41
|
+
contract, IAM permissions/user setup, Role profiles, Secret rotation and pending
|
|
42
|
+
cloud acceptance. From the workspace root,
|
|
43
|
+
`uv run --no-project python -m ci.run_tls_integration_tests postgresql` runs verified
|
|
44
|
+
TLS, multiple databases, shared contracts and wrong-CA/hostname rejection.
|
|
45
|
+
|
|
5
46
|
## Overview
|
|
6
47
|
|
|
7
48
|
This adapter provides PostgreSQL connectivity for Datus, supporting full SQL operations, metadata discovery, schema management, and materialized views via the standard PostgreSQL protocol.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Copyright 2025-present DatusAI, Inc.
|
|
2
|
+
# Licensed under the Apache License, Version 2.0.
|
|
3
|
+
# See http://www.apache.org/licenses/LICENSE-2.0 for details.
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from pydantic import ConfigDict, Field, model_validator
|
|
8
|
+
|
|
9
|
+
from datus_sqlalchemy.auth import DatabaseAuthConfig
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PostgreSQLConfig(DatabaseAuthConfig):
|
|
13
|
+
"""PostgreSQL-specific configuration."""
|
|
14
|
+
|
|
15
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
16
|
+
|
|
17
|
+
host: str = Field(default="127.0.0.1", description="PostgreSQL server host")
|
|
18
|
+
port: int = Field(default=5432, description="PostgreSQL server port")
|
|
19
|
+
username: str = Field(..., description="PostgreSQL username")
|
|
20
|
+
password: str = Field(
|
|
21
|
+
default="",
|
|
22
|
+
repr=False,
|
|
23
|
+
description="PostgreSQL password",
|
|
24
|
+
json_schema_extra={"input_type": "password"},
|
|
25
|
+
)
|
|
26
|
+
database: Optional[str] = Field(default=None, description="Default database name")
|
|
27
|
+
schema_name: Optional[str] = Field(default="public", alias="schema", description="Default schema name")
|
|
28
|
+
sslmode: str = Field(
|
|
29
|
+
default="prefer",
|
|
30
|
+
description="SSL mode (disable, allow, prefer, require, verify-ca, verify-full)",
|
|
31
|
+
)
|
|
32
|
+
timeout_seconds: int = Field(
|
|
33
|
+
default=30, gt=0, description="Pool, socket-operation and default query deadline in seconds"
|
|
34
|
+
)
|
|
35
|
+
read_timeout_seconds: Optional[int] = Field(
|
|
36
|
+
default=None, gt=0, description="Override the connection checkout deadline"
|
|
37
|
+
)
|
|
38
|
+
query_timeout_seconds: Optional[int] = Field(
|
|
39
|
+
default=None, gt=0, description="Override the server statement timeout"
|
|
40
|
+
)
|
|
41
|
+
sslrootcert: Optional[str] = None
|
|
42
|
+
sslcert: Optional[str] = None
|
|
43
|
+
sslkey: Optional[str] = Field(default=None, repr=False)
|
|
44
|
+
|
|
45
|
+
@model_validator(mode="after")
|
|
46
|
+
def validate_tls(self):
|
|
47
|
+
if bool(self.sslcert) != bool(self.sslkey):
|
|
48
|
+
raise ValueError("sslcert and sslkey must be supplied together")
|
|
49
|
+
if self.aurora or self.auth_mode == "iam":
|
|
50
|
+
if not self.sslrootcert:
|
|
51
|
+
raise ValueError("Aurora/IAM requires sslrootcert")
|
|
52
|
+
if "sslmode" in self.model_fields_set and self.sslmode != "verify-full":
|
|
53
|
+
raise ValueError("Aurora/IAM requires sslmode=verify-full")
|
|
54
|
+
self.sslmode = "verify-full"
|
|
55
|
+
return self
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
# See http://www.apache.org/licenses/LICENSE-2.0 for details.
|
|
4
4
|
|
|
5
5
|
from collections import OrderedDict
|
|
6
|
+
from contextlib import nullcontext
|
|
6
7
|
from typing import Any, Dict, List, Optional, Set, Union, override
|
|
7
8
|
from urllib.parse import quote_plus
|
|
8
9
|
|
|
9
10
|
from pydantic import BaseModel, Field
|
|
10
|
-
from sqlalchemy import
|
|
11
|
+
from sqlalchemy import text
|
|
12
|
+
from sqlalchemy.engine import URL, Engine
|
|
11
13
|
|
|
12
14
|
from datus_db_core import (
|
|
13
15
|
TABLE_TYPE,
|
|
@@ -18,6 +20,7 @@ from datus_db_core import (
|
|
|
18
20
|
list_to_in_str,
|
|
19
21
|
)
|
|
20
22
|
from datus_sqlalchemy import SQLAlchemyConnector
|
|
23
|
+
from datus_sqlalchemy.auth import configure_database_connection
|
|
21
24
|
|
|
22
25
|
from .config import PostgreSQLConfig
|
|
23
26
|
|
|
@@ -97,6 +100,23 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
97
100
|
self._default_schema = config.schema_name or "public"
|
|
98
101
|
self._engines: OrderedDict = OrderedDict() # LRU cache: database_name -> engine
|
|
99
102
|
self._max_engines = 8
|
|
103
|
+
connect_args = {
|
|
104
|
+
key: getattr(config, key)
|
|
105
|
+
for key in ("sslrootcert", "sslcert", "sslkey")
|
|
106
|
+
if getattr(config, key) is not None
|
|
107
|
+
}
|
|
108
|
+
configure_database_connection(self, config, connect_args, dialect="postgresql")
|
|
109
|
+
|
|
110
|
+
def _create_engine(self, connection_string: str | URL, **options: Any) -> Engine:
|
|
111
|
+
from .timeouts import configure_timeouts
|
|
112
|
+
|
|
113
|
+
engine = super()._create_engine(connection_string, **options)
|
|
114
|
+
configure_timeouts(
|
|
115
|
+
engine,
|
|
116
|
+
self.config.read_timeout_seconds or self.config.timeout_seconds,
|
|
117
|
+
self.config.query_timeout_seconds or self.config.timeout_seconds,
|
|
118
|
+
)
|
|
119
|
+
return engine
|
|
100
120
|
|
|
101
121
|
# ==================== System Resources ====================
|
|
102
122
|
|
|
@@ -233,7 +253,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
233
253
|
database_name: str = "",
|
|
234
254
|
) -> str:
|
|
235
255
|
"""
|
|
236
|
-
|
|
256
|
+
Reconstruct table DDL from column and declared constraint metadata, or return view DDL.
|
|
237
257
|
|
|
238
258
|
Args:
|
|
239
259
|
schema_name: Schema name
|
|
@@ -287,7 +307,6 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
287
307
|
return f"-- DDL not available for {full_name}"
|
|
288
308
|
|
|
289
309
|
col_defs = []
|
|
290
|
-
pk_cols = []
|
|
291
310
|
for col in columns:
|
|
292
311
|
col_def = f" {self.quote_identifier(col['name'])} {col['type']}"
|
|
293
312
|
if not col.get("nullable", True):
|
|
@@ -295,17 +314,52 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
295
314
|
if col.get("default_value"):
|
|
296
315
|
col_def += f" DEFAULT {col['default_value']}"
|
|
297
316
|
col_defs.append(col_def)
|
|
298
|
-
|
|
299
|
-
|
|
317
|
+
|
|
318
|
+
# Column-level pk flags cannot recover the declared composite-key order.
|
|
319
|
+
# Let PostgreSQL render constraints, including their names and options.
|
|
320
|
+
with self._conn(database_name=database_name) as conn:
|
|
321
|
+
constraints = conn.execute(
|
|
322
|
+
text("""
|
|
323
|
+
SELECT c.conname, pg_catalog.pg_get_constraintdef(c.oid) AS definition
|
|
324
|
+
FROM pg_catalog.pg_constraint c
|
|
325
|
+
JOIN pg_catalog.pg_class t ON t.oid = c.conrelid
|
|
326
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
|
|
327
|
+
WHERE n.nspname = :schema_name AND t.relname = :table_name
|
|
328
|
+
AND c.contype IN ('p', 'u')
|
|
329
|
+
ORDER BY c.contype, c.conname
|
|
330
|
+
"""),
|
|
331
|
+
{"schema_name": schema_name, "table_name": table_name},
|
|
332
|
+
).fetchall()
|
|
333
|
+
col_defs.extend(
|
|
334
|
+
f" CONSTRAINT {self.quote_identifier(name)} {definition}" for name, definition in constraints
|
|
335
|
+
)
|
|
300
336
|
|
|
301
337
|
ddl = f"CREATE TABLE {full_name} (\n"
|
|
302
338
|
ddl += ",\n".join(col_defs)
|
|
303
|
-
if pk_cols:
|
|
304
|
-
pk_names = ", ".join(self.quote_identifier(c) for c in pk_cols)
|
|
305
|
-
ddl += f",\n PRIMARY KEY ({pk_names})"
|
|
306
339
|
ddl += "\n);"
|
|
307
340
|
return ddl
|
|
308
341
|
|
|
342
|
+
def _get_unique_index_definitions(self, schema_name: str, table_name: str, database_name: str = "") -> List[str]:
|
|
343
|
+
"""Read standalone usable unique indexes, retaining predicates and expressions."""
|
|
344
|
+
with self._conn(database_name=database_name or self.database_name) as conn:
|
|
345
|
+
rows = conn.execute(
|
|
346
|
+
text("""
|
|
347
|
+
SELECT pg_catalog.pg_get_indexdef(i.indexrelid) AS definition
|
|
348
|
+
FROM pg_catalog.pg_index i
|
|
349
|
+
JOIN pg_catalog.pg_class t ON t.oid = i.indrelid
|
|
350
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
|
|
351
|
+
WHERE n.nspname = :schema_name AND t.relname = :table_name
|
|
352
|
+
AND i.indisunique AND i.indisvalid AND i.indisready
|
|
353
|
+
AND NOT EXISTS (
|
|
354
|
+
SELECT 1 FROM pg_catalog.pg_constraint c
|
|
355
|
+
WHERE c.conindid = i.indexrelid AND c.contype IN ('p', 'u', 'x')
|
|
356
|
+
)
|
|
357
|
+
ORDER BY i.indexrelid
|
|
358
|
+
"""),
|
|
359
|
+
{"schema_name": schema_name, "table_name": table_name},
|
|
360
|
+
).fetchall()
|
|
361
|
+
return [row[0].rstrip().rstrip(";") + ";" for row in rows]
|
|
362
|
+
|
|
309
363
|
def _get_objects_with_ddl(
|
|
310
364
|
self,
|
|
311
365
|
table_type: TABLE_TYPE = "table",
|
|
@@ -362,6 +416,19 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
362
416
|
meta["table_name"],
|
|
363
417
|
object_type,
|
|
364
418
|
)
|
|
419
|
+
# Append indexes after subclass table clauses (e.g. distribution).
|
|
420
|
+
if object_type == "TABLE" and not ddl.startswith("-- DDL not available"):
|
|
421
|
+
try:
|
|
422
|
+
indexes = self._get_unique_index_definitions(meta["schema_name"], meta["table_name"])
|
|
423
|
+
except Exception as exc:
|
|
424
|
+
logger.warning(
|
|
425
|
+
f"Could not read unique indexes for {full_name}; preserving table DDL: {exc}"
|
|
426
|
+
)
|
|
427
|
+
ddl += "\n-- Additional unique index metadata is unavailable."
|
|
428
|
+
else:
|
|
429
|
+
for index_ddl in indexes:
|
|
430
|
+
if index_ddl.rstrip(";") not in ddl:
|
|
431
|
+
ddl += f"\n{index_ddl}"
|
|
365
432
|
finally:
|
|
366
433
|
self._database_var.reset(token)
|
|
367
434
|
except Exception as e:
|
|
@@ -604,12 +671,13 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
604
671
|
Uses LRU eviction (max 8 engines) to avoid holding too many connections.
|
|
605
672
|
"""
|
|
606
673
|
db = database_name or self.database_name
|
|
674
|
+
self._prepare_connection()
|
|
607
675
|
with self._engine_lock:
|
|
608
676
|
if db in self._engines:
|
|
609
677
|
self._engines.move_to_end(db)
|
|
610
678
|
return self._engines[db]
|
|
611
679
|
conn_str = self._build_connection_string(db)
|
|
612
|
-
engine =
|
|
680
|
+
engine = self._create_engine(
|
|
613
681
|
conn_str,
|
|
614
682
|
pool_size=5,
|
|
615
683
|
max_overflow=10,
|
|
@@ -659,12 +727,15 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
659
727
|
@override
|
|
660
728
|
def close(self):
|
|
661
729
|
"""Dispose all engines (per-database pool + parent engine)."""
|
|
662
|
-
|
|
730
|
+
with getattr(self, "_engine_lock", nullcontext()):
|
|
731
|
+
engines = list(getattr(self, "_engines", {}).values())
|
|
732
|
+
if hasattr(self, "_engines"):
|
|
733
|
+
self._engines.clear()
|
|
734
|
+
for engine in engines:
|
|
663
735
|
try:
|
|
664
736
|
engine.dispose()
|
|
665
737
|
except Exception as e:
|
|
666
738
|
logger.warning(f"Error disposing engine: {e}")
|
|
667
|
-
self._engines.clear()
|
|
668
739
|
# Dispose parent engine that may have been created via connect()/_ensure_engine()
|
|
669
740
|
super().close()
|
|
670
741
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Database-free timeout wiring assertions shared by PostgreSQL adapters."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from unittest.mock import Mock, patch
|
|
6
|
+
|
|
7
|
+
from sqlalchemy.engine import Engine
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def assert_engine_timeout_configuration(
|
|
11
|
+
engine: Engine, *, connect_seconds: int, read_seconds: int, query_seconds: int
|
|
12
|
+
) -> None:
|
|
13
|
+
"""Check real dialect arguments and installed connection lifecycle callbacks.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
engine: Real engine created by the adapter under test.
|
|
17
|
+
connect_seconds: Expected timeout at the final DBAPI connection boundary.
|
|
18
|
+
read_seconds: Expected socket timer interval.
|
|
19
|
+
query_seconds: Expected statement timeout sent through the DBAPI cursor.
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
AssertionError: Dialect translation or timeout callback wiring is wrong.
|
|
23
|
+
"""
|
|
24
|
+
with patch.object(engine.dialect.dbapi, "connect", return_value=Mock()) as connect:
|
|
25
|
+
engine.pool._creator()
|
|
26
|
+
parameters = connect.call_args.kwargs
|
|
27
|
+
assert float(parameters.get("connect_timeout", parameters.get("timeout"))) == connect_seconds
|
|
28
|
+
|
|
29
|
+
# Deliver only this package's callbacks: other connect listeners initialize
|
|
30
|
+
# native UUID/type codecs and require a real vendor server/DBAPI object.
|
|
31
|
+
# The callbacks themselves were installed by the actual connector, rather
|
|
32
|
+
# than by calling configure_timeouts in the test.
|
|
33
|
+
callbacks = [fn for fn in engine.pool.dispatch.connect if fn.__module__ == "datus_postgresql.timeouts"]
|
|
34
|
+
assert len(callbacks) == 2, "Connector did not install socket and statement deadlines"
|
|
35
|
+
for _ in range(2):
|
|
36
|
+
local, peer = socket.socketpair()
|
|
37
|
+
cursor = Mock()
|
|
38
|
+
attributes = {"_usock": local} if engine.dialect.driver == "pg8000" else {"fileno": local.fileno}
|
|
39
|
+
connection = SimpleNamespace(**attributes, autocommit=False, cursor=Mock(return_value=cursor))
|
|
40
|
+
record = SimpleNamespace(info={})
|
|
41
|
+
try:
|
|
42
|
+
for callback in callbacks:
|
|
43
|
+
callback(connection, record)
|
|
44
|
+
deadline = record.info["datus_socket_deadline"]
|
|
45
|
+
assert deadline._timer.interval == read_seconds
|
|
46
|
+
cursor.execute.assert_called_once_with(f"SET statement_timeout = {query_seconds * 1000}")
|
|
47
|
+
cursor.close.assert_called_once()
|
|
48
|
+
assert connection.autocommit is False
|
|
49
|
+
finally:
|
|
50
|
+
engine.pool.dispatch.close(connection, record)
|
|
51
|
+
local.close()
|
|
52
|
+
peer.close()
|
|
53
|
+
assert deadline.socket.fileno() == -1
|
|
54
|
+
assert record.info == {}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Connector-local deadlines for PostgreSQL wire drivers, including libpq.
|
|
2
|
+
|
|
3
|
+
libpq has no socket read-timeout option. Interrupt its socket at the checkout
|
|
4
|
+
deadline instead of leaving a worker blocked or installing a process-wide wait
|
|
5
|
+
callback. Duplicating the socket prevents descriptor reuse from affecting a
|
|
6
|
+
different connection when a deadline races with cleanup.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import socket
|
|
10
|
+
import threading
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from sqlalchemy import event
|
|
14
|
+
from sqlalchemy.engine import Engine, ExceptionContext
|
|
15
|
+
from sqlalchemy.exc import OperationalError
|
|
16
|
+
from sqlalchemy.pool import ConnectionPoolEntry
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SocketDeadline:
|
|
20
|
+
"""Interrupt one native database socket after a cancellable lease deadline.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
connection: DBAPI connection exposing fileno() or pg8000's _usock.
|
|
24
|
+
seconds: Positive lease budget; receipt of data does not reset it.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, connection: Any, seconds: float) -> None:
|
|
28
|
+
fileno = getattr(connection, "fileno", None)
|
|
29
|
+
descriptor = fileno() if fileno else connection._usock.fileno()
|
|
30
|
+
borrowed = socket.socket(fileno=descriptor)
|
|
31
|
+
try:
|
|
32
|
+
self.socket = borrowed.dup()
|
|
33
|
+
finally:
|
|
34
|
+
borrowed.detach()
|
|
35
|
+
self.expired = False
|
|
36
|
+
self._active = True
|
|
37
|
+
self._lock = threading.Lock()
|
|
38
|
+
self._timer = threading.Timer(seconds, self._expire)
|
|
39
|
+
self._timer.daemon = True
|
|
40
|
+
self._timer.start()
|
|
41
|
+
|
|
42
|
+
def _expire(self) -> None:
|
|
43
|
+
with self._lock:
|
|
44
|
+
if self._active:
|
|
45
|
+
self.expired = True
|
|
46
|
+
try:
|
|
47
|
+
self.socket.shutdown(socket.SHUT_RDWR)
|
|
48
|
+
except OSError:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
def close(self) -> None:
|
|
52
|
+
"""Cancel the timer and release the duplicated descriptor."""
|
|
53
|
+
with self._lock:
|
|
54
|
+
self._active = False
|
|
55
|
+
self._timer.cancel()
|
|
56
|
+
self.socket.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def configure_timeouts(engine: Engine, seconds: float, query_seconds: int) -> None:
|
|
60
|
+
"""Install connection-local initialization, checkout and pre-ping deadlines.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
engine: Engine whose physical connections should receive these bounds.
|
|
64
|
+
seconds: Socket lease budget, including fetches and pool reset.
|
|
65
|
+
query_seconds: Server statement timeout, in seconds.
|
|
66
|
+
"""
|
|
67
|
+
key = "datus_socket_deadline"
|
|
68
|
+
|
|
69
|
+
def stop(connection: Any, record: ConnectionPoolEntry, *args: Any) -> SocketDeadline | None:
|
|
70
|
+
deadline = record.info.pop(key, None)
|
|
71
|
+
if deadline is not None:
|
|
72
|
+
deadline.close()
|
|
73
|
+
return deadline
|
|
74
|
+
|
|
75
|
+
def arm(connection: Any, record: ConnectionPoolEntry, *args: Any) -> None:
|
|
76
|
+
stop(connection, record)
|
|
77
|
+
record.info[key] = SocketDeadline(connection, seconds)
|
|
78
|
+
|
|
79
|
+
# Arm before dialect introspection and existing checkout validators, whose
|
|
80
|
+
# SQL/rollback must remain bounded after the previous lease was cancelled.
|
|
81
|
+
event.listen(engine, "connect", arm, insert=True)
|
|
82
|
+
event.listen(engine, "checkout", arm, insert=True)
|
|
83
|
+
event.listen(engine, "close", stop)
|
|
84
|
+
event.listen(engine, "invalidate", stop)
|
|
85
|
+
|
|
86
|
+
@event.listens_for(engine, "checkin")
|
|
87
|
+
def checked_in(connection: Any, record: ConnectionPoolEntry) -> None:
|
|
88
|
+
deadline = stop(connection, record)
|
|
89
|
+
if deadline is not None and deadline.expired and connection is not None:
|
|
90
|
+
record.invalidate()
|
|
91
|
+
|
|
92
|
+
ping = engine.dialect.do_ping
|
|
93
|
+
|
|
94
|
+
def bounded_ping(connection: Any) -> bool:
|
|
95
|
+
deadline = SocketDeadline(connection, seconds)
|
|
96
|
+
try:
|
|
97
|
+
return ping(connection)
|
|
98
|
+
finally:
|
|
99
|
+
deadline.close()
|
|
100
|
+
|
|
101
|
+
engine.dialect.do_ping = bounded_ping
|
|
102
|
+
|
|
103
|
+
@event.listens_for(engine, "handle_error", retval=True)
|
|
104
|
+
def classify_deadline(context: ExceptionContext) -> OperationalError | None:
|
|
105
|
+
if context.connection is not None:
|
|
106
|
+
deadline = context.connection.info.get(key)
|
|
107
|
+
if deadline is not None and deadline.expired:
|
|
108
|
+
context.is_disconnect = True
|
|
109
|
+
return OperationalError(
|
|
110
|
+
context.statement,
|
|
111
|
+
context.parameters,
|
|
112
|
+
TimeoutError("Database socket operation timed out"),
|
|
113
|
+
connection_invalidated=True,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
@event.listens_for(engine, "connect")
|
|
117
|
+
def statement_deadline(connection: Any, record: ConnectionPoolEntry) -> None:
|
|
118
|
+
previous = connection.autocommit
|
|
119
|
+
connection.autocommit = True
|
|
120
|
+
try:
|
|
121
|
+
cursor = connection.cursor()
|
|
122
|
+
try:
|
|
123
|
+
cursor.execute(f"SET statement_timeout = {query_seconds * 1000}")
|
|
124
|
+
finally:
|
|
125
|
+
cursor.close()
|
|
126
|
+
finally:
|
|
127
|
+
connection.autocommit = previous
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Copyright 2025-present DatusAI, Inc.
|
|
2
|
+
# Licensed under the Apache License, Version 2.0.
|
|
3
|
+
# See http://www.apache.org/licenses/LICENSE-2.0 for details.
|
|
4
|
+
|
|
5
|
+
"""PostgreSQL-dialect TPC-H test data definitions.
|
|
6
|
+
|
|
7
|
+
Table names are unqualified: callers set the target schema through the
|
|
8
|
+
connector's ``schema_name`` (applied as ``SET search_path`` on every
|
|
9
|
+
statement), matching the Greenplum and GaussDB adapters.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from datus_db_core.testing.tpch import ROW_COUNTS, TPCH_TABLES, build_tpch_inserts
|
|
13
|
+
|
|
14
|
+
_TPCH_DDL_ITEMS = [
|
|
15
|
+
(
|
|
16
|
+
"tpch_region",
|
|
17
|
+
"""
|
|
18
|
+
CREATE TABLE IF NOT EXISTS "tpch_region" (
|
|
19
|
+
"regionkey" INTEGER NOT NULL,
|
|
20
|
+
"name" VARCHAR(25) NOT NULL,
|
|
21
|
+
"comment" VARCHAR(152),
|
|
22
|
+
PRIMARY KEY ("regionkey")
|
|
23
|
+
)
|
|
24
|
+
""",
|
|
25
|
+
),
|
|
26
|
+
(
|
|
27
|
+
"tpch_nation",
|
|
28
|
+
"""
|
|
29
|
+
CREATE TABLE IF NOT EXISTS "tpch_nation" (
|
|
30
|
+
"nationkey" INTEGER NOT NULL,
|
|
31
|
+
"name" VARCHAR(25) NOT NULL,
|
|
32
|
+
"regionkey" INTEGER NOT NULL,
|
|
33
|
+
"comment" VARCHAR(152),
|
|
34
|
+
PRIMARY KEY ("nationkey")
|
|
35
|
+
)
|
|
36
|
+
""",
|
|
37
|
+
),
|
|
38
|
+
(
|
|
39
|
+
"tpch_customer",
|
|
40
|
+
"""
|
|
41
|
+
CREATE TABLE IF NOT EXISTS "tpch_customer" (
|
|
42
|
+
"custkey" INTEGER NOT NULL,
|
|
43
|
+
"name" VARCHAR(25) NOT NULL,
|
|
44
|
+
"nationkey" INTEGER NOT NULL,
|
|
45
|
+
"acctbal" DECIMAL(15,2) NOT NULL,
|
|
46
|
+
"mktsegment" VARCHAR(10) NOT NULL,
|
|
47
|
+
PRIMARY KEY ("custkey")
|
|
48
|
+
)
|
|
49
|
+
""",
|
|
50
|
+
),
|
|
51
|
+
(
|
|
52
|
+
"tpch_orders",
|
|
53
|
+
"""
|
|
54
|
+
CREATE TABLE IF NOT EXISTS "tpch_orders" (
|
|
55
|
+
"orderkey" INTEGER NOT NULL,
|
|
56
|
+
"custkey" INTEGER NOT NULL,
|
|
57
|
+
"orderstatus" CHAR(1) NOT NULL,
|
|
58
|
+
"totalprice" DECIMAL(15,2) NOT NULL,
|
|
59
|
+
"orderdate" DATE NOT NULL,
|
|
60
|
+
PRIMARY KEY ("orderkey")
|
|
61
|
+
)
|
|
62
|
+
""",
|
|
63
|
+
),
|
|
64
|
+
(
|
|
65
|
+
"tpch_supplier",
|
|
66
|
+
"""
|
|
67
|
+
CREATE TABLE IF NOT EXISTS "tpch_supplier" (
|
|
68
|
+
"suppkey" INTEGER NOT NULL,
|
|
69
|
+
"name" VARCHAR(25) NOT NULL,
|
|
70
|
+
"nationkey" INTEGER NOT NULL,
|
|
71
|
+
"acctbal" DECIMAL(15,2) NOT NULL,
|
|
72
|
+
PRIMARY KEY ("suppkey")
|
|
73
|
+
)
|
|
74
|
+
""",
|
|
75
|
+
),
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
if [table for table, _ in _TPCH_DDL_ITEMS] != TPCH_TABLES:
|
|
79
|
+
raise ValueError("PostgreSQL TPC-H DDL order must match the shared TPCH_TABLES order")
|
|
80
|
+
|
|
81
|
+
TPCH_DDL = [ddl for _, ddl in _TPCH_DDL_ITEMS]
|
|
82
|
+
TPCH_DATA = build_tpch_inserts(lambda t: f'"{t}"')
|
|
83
|
+
|
|
84
|
+
__all__ = ["TPCH_DDL", "TPCH_DATA", "TPCH_TABLES", "ROW_COUNTS"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Overlay: docker compose -f docker-compose.yml -f docker-compose.tls.yml up -d
|
|
2
|
+
services:
|
|
3
|
+
postgres:
|
|
4
|
+
volumes:
|
|
5
|
+
- ${DATUS_TEST_TLS_DIR:?Generate disposable certificates first}:/tls:ro
|
|
6
|
+
command:
|
|
7
|
+
- bash
|
|
8
|
+
- -ec
|
|
9
|
+
- |
|
|
10
|
+
cp /tls/server.key /tmp/datus-server.key
|
|
11
|
+
chown postgres:postgres /tmp/datus-server.key
|
|
12
|
+
chmod 0600 /tmp/datus-server.key
|
|
13
|
+
exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tls/server.crt -c ssl_key_file=/tmp/datus-server.key -c ssl_ca_file=/tls/ca.crt
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# DATUS_TEST_* configures this container; the POSTGRESQL_* the tests read
|
|
2
|
+
# configures the client. See docs/adapter-testing-standard.md.
|
|
3
|
+
services:
|
|
4
|
+
postgres:
|
|
5
|
+
image: postgres:16
|
|
6
|
+
environment:
|
|
7
|
+
TZ: UTC
|
|
8
|
+
POSTGRES_DB: ${DATUS_TEST_POSTGRESQL_DATABASE:-test}
|
|
9
|
+
POSTGRES_USER: ${DATUS_TEST_POSTGRESQL_USER:-test_user}
|
|
10
|
+
POSTGRES_PASSWORD: ${DATUS_TEST_POSTGRESQL_PASSWORD:-test_password}
|
|
11
|
+
ports:
|
|
12
|
+
- "${POSTGRESQL_HOST_PORT:-5432}:5432"
|
|
13
|
+
healthcheck:
|
|
14
|
+
# The init server accepts socket connections before setup finishes.
|
|
15
|
+
# Authenticate over TCP, which is enabled only for the final server.
|
|
16
|
+
test: ["CMD-SHELL", "PGPASSWORD=\"$${POSTGRES_PASSWORD}\" psql -h 127.0.0.1 -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\" -w -c 'SELECT 1' >/dev/null 2>&1"]
|
|
17
|
+
interval: 10s
|
|
18
|
+
timeout: 5s
|
|
19
|
+
retries: 5
|
|
20
|
+
start_period: 30s
|
|
21
|
+
volumes:
|
|
22
|
+
- postgres_data:/var/lib/postgresql/data
|
|
23
|
+
|
|
24
|
+
volumes:
|
|
25
|
+
postgres_data:
|