datus-postgresql 0.1.9__tar.gz → 0.1.12__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 (33) hide show
  1. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/PKG-INFO +47 -3
  2. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/README.md +41 -0
  3. datus_postgresql-0.1.12/datus_postgresql/config.py +55 -0
  4. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/datus_postgresql/connector.py +181 -24
  5. datus_postgresql-0.1.12/datus_postgresql/testing.py +54 -0
  6. datus_postgresql-0.1.12/datus_postgresql/timeouts.py +127 -0
  7. datus_postgresql-0.1.12/docker-compose.tls.yml +13 -0
  8. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/docker-compose.yml +3 -4
  9. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/pyproject.toml +7 -3
  10. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/integration/conftest.py +24 -12
  11. datus_postgresql-0.1.12/tests/integration/test_aurora_cloud.py +57 -0
  12. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/integration/test_integration.py +7 -24
  13. datus_postgresql-0.1.12/tests/integration/test_metadata_retrieval.py +365 -0
  14. datus_postgresql-0.1.12/tests/integration/test_timeouts.py +99 -0
  15. datus_postgresql-0.1.12/tests/integration/test_tls.py +47 -0
  16. datus_postgresql-0.1.12/tests/unit/test_aurora.py +113 -0
  17. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/unit/test_config.py +2 -4
  18. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/unit/test_connector_unit.py +264 -8
  19. datus_postgresql-0.1.12/tests/unit/test_scoped_ddl.py +58 -0
  20. datus_postgresql-0.1.12/tests/unit/test_timeouts.py +344 -0
  21. datus_postgresql-0.1.9/datus_postgresql/config.py +0 -29
  22. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/.gitignore +0 -0
  23. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/datus_postgresql/__init__.py +0 -0
  24. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/datus_postgresql/handlers.py +0 -0
  25. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/datus_postgresql/tpch_data.py +0 -0
  26. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/scripts/init_tpch_data.py +0 -0
  27. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/__init__.py +0 -0
  28. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/conftest.py +0 -0
  29. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/integration/__init__.py +0 -0
  30. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/integration/test_contract.py +0 -0
  31. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/integration/test_tpch.py +0 -0
  32. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/unit/__init__.py +0 -0
  33. {datus_postgresql-0.1.9 → datus_postgresql-0.1.12}/tests/unit/test_migration_mixin.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datus-postgresql
3
- Version: 0.1.9
3
+ Version: 0.1.12
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,60 @@ 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.7
18
- Requires-Dist: datus-sqlalchemy>=0.1.8
17
+ Requires-Dist: datus-db-core>=0.1.11
18
+ Requires-Dist: datus-sqlalchemy>=0.1.13
19
19
  Requires-Dist: psycopg2-binary>=2.9.11
20
20
  Requires-Dist: pydantic>=2.0.0
21
+ Requires-Dist: sqlglot>=30.0.0
22
+ Provides-Extra: aws
23
+ Requires-Dist: datus-db-core[aws]>=0.1.8; extra == 'aws'
21
24
  Description-Content-Type: text/markdown
22
25
 
23
26
  # datus-postgresql
24
27
 
25
28
  PostgreSQL database adapter for [Datus](https://github.com/Datus-ai/datus-agent).
26
29
 
30
+ ## Timeouts
31
+
32
+ `timeout_seconds` must be positive and now bounds driver I/O as well as pool
33
+ checkout where applicable. Long operations may need a larger value. Server
34
+ execution deadlines and supported overrides are described in the shared
35
+ [timeout policy and real-database validation](../docs/adapter-timeouts.md).
36
+ A socket/RPC timeout is distinct from an overall operation deadline.
37
+
38
+ ## Amazon Aurora PostgreSQL
39
+
40
+ Aurora uses this adapter with the PostgreSQL dialect. Set `aurora=True` and provide
41
+ `sslrootcert`; the adapter requires `sslmode=verify-full`. Password authentication
42
+ needs no AWS SDK. Install `pip install 'datus-postgresql[aws]'` for IAM or Secrets Manager.
43
+
44
+ ```python
45
+ import os
46
+ from datus_postgresql import PostgreSQLConnector
47
+
48
+ connector = PostgreSQLConnector({
49
+ "host": os.environ["AURORA_POSTGRESQL_ENDPOINT"],
50
+ "username": os.environ["AURORA_DB_USER"],
51
+ "database": os.environ["AURORA_DATABASE"],
52
+ "aurora": True,
53
+ "auth_mode": "iam",
54
+ "aws": {"region": os.environ["AWS_REGION"]},
55
+ "sslrootcert": os.environ["AURORA_CA_BUNDLE"],
56
+ })
57
+ try:
58
+ result = connector.execute_query("SELECT 1", result_format="list")
59
+ assert result.success, result.error
60
+ finally:
61
+ connector.close()
62
+ ```
63
+
64
+ TLS and dynamic credentials apply to the base engine and every cached database
65
+ engine. See [Aurora authentication and lifecycle](../docs/aurora.md) for the full
66
+ contract, IAM permissions/user setup, Role profiles, Secret rotation and pending
67
+ cloud acceptance. From the workspace root,
68
+ `uv run --no-project python -m ci.run_tls_integration_tests postgresql` runs verified
69
+ TLS, multiple databases, shared contracts and wrong-CA/hostname rejection.
70
+
27
71
  ## Overview
28
72
 
29
73
  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,15 @@
3
3
  # See http://www.apache.org/licenses/LICENSE-2.0 for details.
4
4
 
5
5
  from collections import OrderedDict
6
- from typing import Any, Dict, List, Optional, Set, Union, override
6
+ from contextlib import nullcontext
7
+ from typing import Any, Dict, List, Optional, Set, Tuple, Union, override
7
8
  from urllib.parse import quote_plus
8
9
 
9
10
  from pydantic import BaseModel, Field
10
- from sqlalchemy import create_engine, text
11
+ from sqlalchemy import text
12
+ from sqlalchemy.engine import URL, Engine
13
+ from sqlglot.dialects.postgres import Postgres
14
+ from sqlglot.tokens import TokenType
11
15
 
12
16
  from datus_db_core import (
13
17
  TABLE_TYPE,
@@ -18,6 +22,7 @@ from datus_db_core import (
18
22
  list_to_in_str,
19
23
  )
20
24
  from datus_sqlalchemy import SQLAlchemyConnector
25
+ from datus_sqlalchemy.auth import configure_database_connection
21
26
 
22
27
  from .config import PostgreSQLConfig
23
28
 
@@ -97,6 +102,23 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
97
102
  self._default_schema = config.schema_name or "public"
98
103
  self._engines: OrderedDict = OrderedDict() # LRU cache: database_name -> engine
99
104
  self._max_engines = 8
105
+ connect_args = {
106
+ key: getattr(config, key)
107
+ for key in ("sslrootcert", "sslcert", "sslkey")
108
+ if getattr(config, key) is not None
109
+ }
110
+ configure_database_connection(self, config, connect_args, dialect="postgresql")
111
+
112
+ def _create_engine(self, connection_string: str | URL, **options: Any) -> Engine:
113
+ from .timeouts import configure_timeouts
114
+
115
+ engine = super()._create_engine(connection_string, **options)
116
+ configure_timeouts(
117
+ engine,
118
+ self.config.read_timeout_seconds or self.config.timeout_seconds,
119
+ self.config.query_timeout_seconds or self.config.timeout_seconds,
120
+ )
121
+ return engine
100
122
 
101
123
  # ==================== System Resources ====================
102
124
 
@@ -137,6 +159,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
137
159
  catalog_name: str = "",
138
160
  database_name: str = "",
139
161
  schema_name: str = "",
162
+ tables: Optional[List[str]] = None,
140
163
  ) -> List[Dict[str, str]]:
141
164
  """
142
165
  Get metadata for tables/views from INFORMATION_SCHEMA or pg_catalog.
@@ -174,10 +197,14 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
174
197
  )
175
198
  else:
176
199
  cmp = list_to_in_str("schemaname not in", sys_schemas)
177
- return f"{base_query} WHERE {cmp}"
200
+ return f"{base_query} WHERE {cmp} {list_to_in_str('AND matviewname IN', tables)}"
178
201
 
179
202
  query_result = self._execute_pandas(_build_mv(False), database_name=database_name)
180
- if len(query_result) == 0 and schema_name:
203
+ if (
204
+ len(query_result) == 0
205
+ and schema_name
206
+ and (not tables or not self._metadata_schema_exists(database_name, schema_name))
207
+ ):
181
208
  query_result = self._execute_pandas(_build_mv(True), database_name=database_name)
182
209
  self._raise_if_ambiguous_schema(query_result, schema_name)
183
210
  else:
@@ -197,10 +224,17 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
197
224
  )
198
225
  else:
199
226
  cmp = list_to_in_str("table_schema not in", sys_schemas)
200
- return f"{base_query} WHERE table_catalog = '{safe_db}' AND {cmp} {type_filter}"
227
+ return (
228
+ f"{base_query} WHERE table_catalog = '{safe_db}' AND {cmp} {type_filter} "
229
+ f"{list_to_in_str('AND table_name IN', tables)}"
230
+ )
201
231
 
202
232
  query_result = self._execute_pandas(_build_tv(False), database_name=database_name)
203
- if len(query_result) == 0 and schema_name:
233
+ if (
234
+ len(query_result) == 0
235
+ and schema_name
236
+ and (not tables or not self._metadata_schema_exists(database_name, schema_name))
237
+ ):
204
238
  query_result = self._execute_pandas(_build_tv(True), database_name=database_name)
205
239
  self._raise_if_ambiguous_schema(query_result, schema_name)
206
240
 
@@ -225,6 +259,15 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
225
259
  )
226
260
  return result
227
261
 
262
+ def _metadata_schema_exists(self, database_name: str, schema_name: str) -> bool:
263
+ """A missing selected table must not redirect a read to a case-variant schema."""
264
+ safe_schema = schema_name.replace("'", "''")
265
+ rows = self._execute_pandas(
266
+ f"SELECT nspname FROM pg_namespace WHERE nspname = '{safe_schema}'",
267
+ database_name=database_name,
268
+ )
269
+ return not rows.empty
270
+
228
271
  def _get_ddl(
229
272
  self,
230
273
  schema_name: str,
@@ -233,7 +276,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
233
276
  database_name: str = "",
234
277
  ) -> str:
235
278
  """
236
- Get DDL for a table/view using pg_get_tabledef or reconstructing from metadata.
279
+ Reconstruct table DDL from column and declared constraint metadata, or return view DDL.
237
280
 
238
281
  Args:
239
282
  schema_name: Schema name
@@ -287,7 +330,6 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
287
330
  return f"-- DDL not available for {full_name}"
288
331
 
289
332
  col_defs = []
290
- pk_cols = []
291
333
  for col in columns:
292
334
  col_def = f" {self.quote_identifier(col['name'])} {col['type']}"
293
335
  if not col.get("nullable", True):
@@ -295,17 +337,105 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
295
337
  if col.get("default_value"):
296
338
  col_def += f" DEFAULT {col['default_value']}"
297
339
  col_defs.append(col_def)
298
- if col.get("pk"):
299
- pk_cols.append(col["name"])
340
+
341
+ # Column-level pk flags cannot recover the declared composite-key order.
342
+ # Let PostgreSQL render constraints, including their names, options, and foreign keys.
343
+ # Deparse references independently of the configured schema's search_path.
344
+ with self._conn(database_name=database_name, schema_name="pg_catalog") as conn:
345
+ constraints = conn.execute(
346
+ text("""
347
+ SELECT c.conname,
348
+ c.convalidated,
349
+ pg_catalog.pg_get_constraintdef(c.oid) AS definition,
350
+ (c.contype = 'f' AND EXISTS (
351
+ SELECT 1
352
+ FROM pg_catalog.pg_index i
353
+ WHERE i.indexrelid = c.conindid
354
+ AND NOT EXISTS (
355
+ SELECT 1
356
+ FROM pg_catalog.pg_constraint uq
357
+ WHERE uq.conindid = i.indexrelid AND uq.contype IN ('p', 'u', 'x')
358
+ )
359
+ )) AS depends_on_standalone_index
360
+ FROM pg_catalog.pg_constraint c
361
+ JOIN pg_catalog.pg_class t ON t.oid = c.conrelid
362
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
363
+ WHERE n.nspname = :schema_name AND t.relname = :table_name
364
+ AND c.contype IN ('p', 'u', 'f')
365
+ ORDER BY CASE c.contype
366
+ WHEN 'p' THEN 1
367
+ WHEN 'u' THEN 2
368
+ WHEN 'f' THEN 3
369
+ ELSE 4
370
+ END, c.conname
371
+ """),
372
+ {"schema_name": schema_name, "table_name": table_name},
373
+ ).fetchall()
374
+
375
+ table_constraints = []
376
+ deferred_alter_statements = []
377
+ for row in constraints:
378
+ name, is_validated, definition, depends_on_standalone_index = row
379
+ is_unvalidated = not is_validated
380
+ if is_unvalidated and "NOT VALID" not in definition:
381
+ definition = f"{definition} NOT VALID"
382
+
383
+ # PostgreSQL forbids NOT VALID inside CREATE TABLE definitions.
384
+ # In addition, foreign keys that depend on a standalone unique index
385
+ # cannot be created inside CREATE TABLE because the index does not yet exist.
386
+ # Emit both as standalone ALTER TABLE statements.
387
+ if is_unvalidated or depends_on_standalone_index:
388
+ deferred_alter_statements.append(
389
+ f"ALTER TABLE {full_name} ADD CONSTRAINT {self.quote_identifier(name)} {definition};"
390
+ )
391
+ else:
392
+ table_constraints.append(f" CONSTRAINT {self.quote_identifier(name)} {definition}")
393
+
394
+ col_defs.extend(table_constraints)
300
395
 
301
396
  ddl = f"CREATE TABLE {full_name} (\n"
302
397
  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
398
  ddl += "\n);"
399
+ if deferred_alter_statements:
400
+ ddl += "\n" + "\n".join(deferred_alter_statements)
307
401
  return ddl
308
402
 
403
+ @staticmethod
404
+ def _partition_table_ddl(ddl: str) -> Tuple[str, List[str]]:
405
+ """Split reconstructed table DDL into the CREATE TABLE statement and trailing ALTER statements."""
406
+ # Token positions retain the original SQL, including quoted text and comments.
407
+ tokens = Postgres().tokenize(ddl)
408
+ for i in range(1, len(tokens) - 1):
409
+ if (
410
+ tokens[i - 1].token_type == TokenType.SEMICOLON
411
+ and tokens[i].token_type == TokenType.ALTER
412
+ and tokens[i + 1].token_type == TokenType.TABLE
413
+ ):
414
+ boundary = tokens[i - 1].end + 1
415
+ return ddl[:boundary], ddl[boundary:].strip().split("\n")
416
+ return ddl, []
417
+
418
+ def _get_unique_index_definitions(self, schema_name: str, table_name: str, database_name: str = "") -> List[str]:
419
+ """Read standalone usable unique indexes, retaining predicates and expressions."""
420
+ with self._conn(database_name=database_name or self.database_name) as conn:
421
+ rows = conn.execute(
422
+ text("""
423
+ SELECT pg_catalog.pg_get_indexdef(i.indexrelid) AS definition
424
+ FROM pg_catalog.pg_index i
425
+ JOIN pg_catalog.pg_class t ON t.oid = i.indrelid
426
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
427
+ WHERE n.nspname = :schema_name AND t.relname = :table_name
428
+ AND i.indisunique AND i.indisvalid AND i.indisready
429
+ AND NOT EXISTS (
430
+ SELECT 1 FROM pg_catalog.pg_constraint c
431
+ WHERE c.conindid = i.indexrelid AND c.contype IN ('p', 'u', 'x')
432
+ )
433
+ ORDER BY i.indexrelid
434
+ """),
435
+ {"schema_name": schema_name, "table_name": table_name},
436
+ ).fetchall()
437
+ return [row[0].rstrip().rstrip(";") + ";" for row in rows]
438
+
309
439
  def _get_objects_with_ddl(
310
440
  self,
311
441
  table_type: TABLE_TYPE = "table",
@@ -337,7 +467,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
337
467
  }
338
468
  object_type = object_type_map.get(table_type, "TABLE")
339
469
 
340
- for meta in self._get_metadata(table_type, catalog_name, database_name, schema_name):
470
+ for meta in self._get_metadata(table_type, catalog_name, database_name, schema_name, tables=tables):
341
471
  metadata_database = meta["database_name"]
342
472
  full_name = self.full_name(
343
473
  database_name=metadata_database,
@@ -362,6 +492,25 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
362
492
  meta["table_name"],
363
493
  object_type,
364
494
  )
495
+ # Append indexes after subclass table clauses (e.g. distribution)
496
+ # and before any deferred ALTER TABLE statements so indexes exist
497
+ # before foreign keys referencing standalone unique indexes are added.
498
+ if object_type == "TABLE" and not ddl.startswith("-- DDL not available"):
499
+ try:
500
+ indexes = self._get_unique_index_definitions(meta["schema_name"], meta["table_name"])
501
+ except Exception as exc:
502
+ logger.warning(
503
+ f"Could not read unique indexes for {full_name}; preserving table DDL: {exc}"
504
+ )
505
+ ddl += "\n-- Additional unique index metadata is unavailable."
506
+ else:
507
+ new_indexes = [idx for idx in indexes if idx.rstrip(";") not in ddl]
508
+ if new_indexes:
509
+ create_part, alter_lines = self._partition_table_ddl(ddl)
510
+ ddl_parts = [create_part] + new_indexes
511
+ if alter_lines:
512
+ ddl_parts.append("\n".join(alter_lines))
513
+ ddl = "\n".join(ddl_parts)
365
514
  finally:
366
515
  self._database_var.reset(token)
367
516
  except Exception as e:
@@ -441,7 +590,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
441
590
  table_name: str = "",
442
591
  ) -> List[Dict[str, Any]]:
443
592
  """
444
- Get table schema using INFORMATION_SCHEMA.
593
+ Get visible columns from INFORMATION_SCHEMA with their declared PostgreSQL types.
445
594
 
446
595
  Args:
447
596
  catalog_name: Catalog name (unused)
@@ -478,12 +627,16 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
478
627
  c.table_schema as table_schema,
479
628
  c.table_name as table_name,
480
629
  c.column_name as field,
481
- c.data_type as type,
630
+ pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
482
631
  c.is_nullable as nullable,
483
632
  c.column_default as default_value,
484
633
  CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_pk,
485
634
  pgd.description as comment
486
635
  FROM information_schema.columns c
636
+ JOIN pg_catalog.pg_namespace n ON n.nspname = c.table_schema
637
+ JOIN pg_catalog.pg_class t ON t.relnamespace = n.oid AND t.relname = c.table_name
638
+ JOIN pg_catalog.pg_attribute a
639
+ ON a.attrelid = t.oid AND a.attnum = c.ordinal_position
487
640
  LEFT JOIN (
488
641
  SELECT kcu.table_schema, kcu.table_name, kcu.column_name
489
642
  FROM information_schema.table_constraints tc
@@ -496,19 +649,19 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
496
649
  ) pk ON pk.table_schema = c.table_schema
497
650
  AND pk.table_name = c.table_name
498
651
  AND pk.column_name = c.column_name
499
- LEFT JOIN pg_catalog.pg_statio_all_tables st
500
- ON st.schemaname = c.table_schema AND st.relname = c.table_name
501
652
  LEFT JOIN pg_catalog.pg_description pgd
502
- ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position
653
+ ON pgd.objoid = t.oid AND pgd.objsubid = a.attnum
654
+ AND pgd.classoid = 'pg_catalog.pg_class'::regclass
503
655
  WHERE c.table_catalog = '{safe_db}'
504
656
  AND {schema_cmp}
505
657
  AND {table_cmp}
506
658
  ORDER BY c.table_schema, c.table_name, c.ordinal_position
507
659
  """
508
660
 
509
- query_result = self._execute_pandas(_build_sql(False), database_name=database_name)
661
+ # Keep user-defined type (and default expression) references schema-qualified.
662
+ query_result = self._execute_pandas(_build_sql(False), database_name=database_name, schema_name="pg_catalog")
510
663
  if len(query_result) == 0:
511
- query_result = self._execute_pandas(_build_sql(True), database_name=database_name)
664
+ query_result = self._execute_pandas(_build_sql(True), database_name=database_name, schema_name="pg_catalog")
512
665
  self._raise_if_ambiguous_table(query_result, schema_name, table_name)
513
666
 
514
667
  result = []
@@ -604,12 +757,13 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
604
757
  Uses LRU eviction (max 8 engines) to avoid holding too many connections.
605
758
  """
606
759
  db = database_name or self.database_name
760
+ self._prepare_connection()
607
761
  with self._engine_lock:
608
762
  if db in self._engines:
609
763
  self._engines.move_to_end(db)
610
764
  return self._engines[db]
611
765
  conn_str = self._build_connection_string(db)
612
- engine = create_engine(
766
+ engine = self._create_engine(
613
767
  conn_str,
614
768
  pool_size=5,
615
769
  max_overflow=10,
@@ -659,12 +813,15 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
659
813
  @override
660
814
  def close(self):
661
815
  """Dispose all engines (per-database pool + parent engine)."""
662
- for engine in self._engines.values():
816
+ with getattr(self, "_engine_lock", nullcontext()):
817
+ engines = list(getattr(self, "_engines", {}).values())
818
+ if hasattr(self, "_engines"):
819
+ self._engines.clear()
820
+ for engine in engines:
663
821
  try:
664
822
  engine.dispose()
665
823
  except Exception as e:
666
824
  logger.warning(f"Error disposing engine: {e}")
667
- self._engines.clear()
668
825
  # Dispose parent engine that may have been created via connect()/_ensure_engine()
669
826
  super().close()
670
827
 
@@ -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 == {}