datus-postgresql 0.1.11__tar.gz → 0.1.13__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.11 → datus_postgresql-0.1.13}/PKG-INFO +4 -3
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/connector.py +122 -26
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/pyproject.toml +4 -3
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_integration.py +3 -4
- datus_postgresql-0.1.13/tests/integration/test_metadata_retrieval.py +365 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_timeouts.py +13 -1
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/unit/test_connector_unit.py +191 -1
- datus_postgresql-0.1.13/tests/unit/test_scoped_ddl.py +58 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/unit/test_timeouts.py +32 -0
- datus_postgresql-0.1.11/tests/integration/test_metadata_retrieval.py +0 -48
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/.gitignore +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/README.md +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/__init__.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/config.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/handlers.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/testing.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/timeouts.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/datus_postgresql/tpch_data.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/docker-compose.tls.yml +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/docker-compose.yml +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/scripts/init_tpch_data.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/__init__.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/conftest.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/__init__.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/conftest.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_aurora_cloud.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_contract.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_tls.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/integration/test_tpch.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/unit/__init__.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/unit/test_aurora.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/tests/unit/test_config.py +0 -0
- {datus_postgresql-0.1.11 → datus_postgresql-0.1.13}/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.
|
|
3
|
+
Version: 0.1.13
|
|
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,10 +14,11 @@ 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.12
|
|
18
|
+
Requires-Dist: datus-sqlalchemy>=0.1.14
|
|
19
19
|
Requires-Dist: psycopg2-binary>=2.9.11
|
|
20
20
|
Requires-Dist: pydantic>=2.0.0
|
|
21
|
+
Requires-Dist: sqlglot>=30.0.0
|
|
21
22
|
Provides-Extra: aws
|
|
22
23
|
Requires-Dist: datus-db-core[aws]>=0.1.8; extra == 'aws'
|
|
23
24
|
Description-Content-Type: text/markdown
|
|
@@ -4,12 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
from collections import OrderedDict
|
|
6
6
|
from contextlib import nullcontext
|
|
7
|
-
from typing import Any, Dict, List, Optional, Set, Union, override
|
|
7
|
+
from typing import Any, Dict, List, Optional, Set, Tuple, Union, override
|
|
8
8
|
from urllib.parse import quote_plus
|
|
9
9
|
|
|
10
10
|
from pydantic import BaseModel, Field
|
|
11
11
|
from sqlalchemy import text
|
|
12
|
-
from sqlalchemy.engine import URL, Engine
|
|
12
|
+
from sqlalchemy.engine import URL, Connection, Engine
|
|
13
|
+
from sqlglot.dialects.postgres import Postgres
|
|
14
|
+
from sqlglot.tokens import TokenType
|
|
13
15
|
|
|
14
16
|
from datus_db_core import (
|
|
15
17
|
TABLE_TYPE,
|
|
@@ -107,6 +109,16 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
107
109
|
}
|
|
108
110
|
configure_database_connection(self, config, connect_args, dialect="postgresql")
|
|
109
111
|
|
|
112
|
+
@property
|
|
113
|
+
def supports_query_timeout_override(self) -> bool:
|
|
114
|
+
return self.dialect in {"postgresql", "greenplum"} and not self.config.aurora
|
|
115
|
+
|
|
116
|
+
def _query_timeout_scope(self, conn: Connection, seconds: int):
|
|
117
|
+
# The SELECT shares this transaction. Checkout cleanup rolls it back,
|
|
118
|
+
# releasing the local setting without a second server-variable change.
|
|
119
|
+
conn.exec_driver_sql(f"SET LOCAL statement_timeout = {seconds * 1000}").close()
|
|
120
|
+
return nullcontext()
|
|
121
|
+
|
|
110
122
|
def _create_engine(self, connection_string: str | URL, **options: Any) -> Engine:
|
|
111
123
|
from .timeouts import configure_timeouts
|
|
112
124
|
|
|
@@ -157,6 +169,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
157
169
|
catalog_name: str = "",
|
|
158
170
|
database_name: str = "",
|
|
159
171
|
schema_name: str = "",
|
|
172
|
+
tables: Optional[List[str]] = None,
|
|
160
173
|
) -> List[Dict[str, str]]:
|
|
161
174
|
"""
|
|
162
175
|
Get metadata for tables/views from INFORMATION_SCHEMA or pg_catalog.
|
|
@@ -194,10 +207,14 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
194
207
|
)
|
|
195
208
|
else:
|
|
196
209
|
cmp = list_to_in_str("schemaname not in", sys_schemas)
|
|
197
|
-
return f"{base_query} WHERE {cmp}"
|
|
210
|
+
return f"{base_query} WHERE {cmp} {list_to_in_str('AND matviewname IN', tables)}"
|
|
198
211
|
|
|
199
212
|
query_result = self._execute_pandas(_build_mv(False), database_name=database_name)
|
|
200
|
-
if
|
|
213
|
+
if (
|
|
214
|
+
len(query_result) == 0
|
|
215
|
+
and schema_name
|
|
216
|
+
and (not tables or not self._metadata_schema_exists(database_name, schema_name))
|
|
217
|
+
):
|
|
201
218
|
query_result = self._execute_pandas(_build_mv(True), database_name=database_name)
|
|
202
219
|
self._raise_if_ambiguous_schema(query_result, schema_name)
|
|
203
220
|
else:
|
|
@@ -217,10 +234,17 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
217
234
|
)
|
|
218
235
|
else:
|
|
219
236
|
cmp = list_to_in_str("table_schema not in", sys_schemas)
|
|
220
|
-
return
|
|
237
|
+
return (
|
|
238
|
+
f"{base_query} WHERE table_catalog = '{safe_db}' AND {cmp} {type_filter} "
|
|
239
|
+
f"{list_to_in_str('AND table_name IN', tables)}"
|
|
240
|
+
)
|
|
221
241
|
|
|
222
242
|
query_result = self._execute_pandas(_build_tv(False), database_name=database_name)
|
|
223
|
-
if
|
|
243
|
+
if (
|
|
244
|
+
len(query_result) == 0
|
|
245
|
+
and schema_name
|
|
246
|
+
and (not tables or not self._metadata_schema_exists(database_name, schema_name))
|
|
247
|
+
):
|
|
224
248
|
query_result = self._execute_pandas(_build_tv(True), database_name=database_name)
|
|
225
249
|
self._raise_if_ambiguous_schema(query_result, schema_name)
|
|
226
250
|
|
|
@@ -245,6 +269,15 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
245
269
|
)
|
|
246
270
|
return result
|
|
247
271
|
|
|
272
|
+
def _metadata_schema_exists(self, database_name: str, schema_name: str) -> bool:
|
|
273
|
+
"""A missing selected table must not redirect a read to a case-variant schema."""
|
|
274
|
+
safe_schema = schema_name.replace("'", "''")
|
|
275
|
+
rows = self._execute_pandas(
|
|
276
|
+
f"SELECT nspname FROM pg_namespace WHERE nspname = '{safe_schema}'",
|
|
277
|
+
database_name=database_name,
|
|
278
|
+
)
|
|
279
|
+
return not rows.empty
|
|
280
|
+
|
|
248
281
|
def _get_ddl(
|
|
249
282
|
self,
|
|
250
283
|
schema_name: str,
|
|
@@ -316,29 +349,82 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
316
349
|
col_defs.append(col_def)
|
|
317
350
|
|
|
318
351
|
# Column-level pk flags cannot recover the declared composite-key order.
|
|
319
|
-
# Let PostgreSQL render constraints, including their names and
|
|
320
|
-
|
|
352
|
+
# Let PostgreSQL render constraints, including their names, options, and foreign keys.
|
|
353
|
+
# Deparse references independently of the configured schema's search_path.
|
|
354
|
+
with self._conn(database_name=database_name, schema_name="pg_catalog") as conn:
|
|
321
355
|
constraints = conn.execute(
|
|
322
356
|
text("""
|
|
323
|
-
SELECT c.conname,
|
|
357
|
+
SELECT c.conname,
|
|
358
|
+
c.convalidated,
|
|
359
|
+
pg_catalog.pg_get_constraintdef(c.oid) AS definition,
|
|
360
|
+
(c.contype = 'f' AND EXISTS (
|
|
361
|
+
SELECT 1
|
|
362
|
+
FROM pg_catalog.pg_index i
|
|
363
|
+
WHERE i.indexrelid = c.conindid
|
|
364
|
+
AND NOT EXISTS (
|
|
365
|
+
SELECT 1
|
|
366
|
+
FROM pg_catalog.pg_constraint uq
|
|
367
|
+
WHERE uq.conindid = i.indexrelid AND uq.contype IN ('p', 'u', 'x')
|
|
368
|
+
)
|
|
369
|
+
)) AS depends_on_standalone_index
|
|
324
370
|
FROM pg_catalog.pg_constraint c
|
|
325
371
|
JOIN pg_catalog.pg_class t ON t.oid = c.conrelid
|
|
326
372
|
JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
|
|
327
373
|
WHERE n.nspname = :schema_name AND t.relname = :table_name
|
|
328
|
-
AND c.contype IN ('p', 'u')
|
|
329
|
-
ORDER BY c.contype
|
|
374
|
+
AND c.contype IN ('p', 'u', 'f')
|
|
375
|
+
ORDER BY CASE c.contype
|
|
376
|
+
WHEN 'p' THEN 1
|
|
377
|
+
WHEN 'u' THEN 2
|
|
378
|
+
WHEN 'f' THEN 3
|
|
379
|
+
ELSE 4
|
|
380
|
+
END, c.conname
|
|
330
381
|
"""),
|
|
331
382
|
{"schema_name": schema_name, "table_name": table_name},
|
|
332
383
|
).fetchall()
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
384
|
+
|
|
385
|
+
table_constraints = []
|
|
386
|
+
deferred_alter_statements = []
|
|
387
|
+
for row in constraints:
|
|
388
|
+
name, is_validated, definition, depends_on_standalone_index = row
|
|
389
|
+
is_unvalidated = not is_validated
|
|
390
|
+
if is_unvalidated and "NOT VALID" not in definition:
|
|
391
|
+
definition = f"{definition} NOT VALID"
|
|
392
|
+
|
|
393
|
+
# PostgreSQL forbids NOT VALID inside CREATE TABLE definitions.
|
|
394
|
+
# In addition, foreign keys that depend on a standalone unique index
|
|
395
|
+
# cannot be created inside CREATE TABLE because the index does not yet exist.
|
|
396
|
+
# Emit both as standalone ALTER TABLE statements.
|
|
397
|
+
if is_unvalidated or depends_on_standalone_index:
|
|
398
|
+
deferred_alter_statements.append(
|
|
399
|
+
f"ALTER TABLE {full_name} ADD CONSTRAINT {self.quote_identifier(name)} {definition};"
|
|
400
|
+
)
|
|
401
|
+
else:
|
|
402
|
+
table_constraints.append(f" CONSTRAINT {self.quote_identifier(name)} {definition}")
|
|
403
|
+
|
|
404
|
+
col_defs.extend(table_constraints)
|
|
336
405
|
|
|
337
406
|
ddl = f"CREATE TABLE {full_name} (\n"
|
|
338
407
|
ddl += ",\n".join(col_defs)
|
|
339
408
|
ddl += "\n);"
|
|
409
|
+
if deferred_alter_statements:
|
|
410
|
+
ddl += "\n" + "\n".join(deferred_alter_statements)
|
|
340
411
|
return ddl
|
|
341
412
|
|
|
413
|
+
@staticmethod
|
|
414
|
+
def _partition_table_ddl(ddl: str) -> Tuple[str, List[str]]:
|
|
415
|
+
"""Split reconstructed table DDL into the CREATE TABLE statement and trailing ALTER statements."""
|
|
416
|
+
# Token positions retain the original SQL, including quoted text and comments.
|
|
417
|
+
tokens = Postgres().tokenize(ddl)
|
|
418
|
+
for i in range(1, len(tokens) - 1):
|
|
419
|
+
if (
|
|
420
|
+
tokens[i - 1].token_type == TokenType.SEMICOLON
|
|
421
|
+
and tokens[i].token_type == TokenType.ALTER
|
|
422
|
+
and tokens[i + 1].token_type == TokenType.TABLE
|
|
423
|
+
):
|
|
424
|
+
boundary = tokens[i - 1].end + 1
|
|
425
|
+
return ddl[:boundary], ddl[boundary:].strip().split("\n")
|
|
426
|
+
return ddl, []
|
|
427
|
+
|
|
342
428
|
def _get_unique_index_definitions(self, schema_name: str, table_name: str, database_name: str = "") -> List[str]:
|
|
343
429
|
"""Read standalone usable unique indexes, retaining predicates and expressions."""
|
|
344
430
|
with self._conn(database_name=database_name or self.database_name) as conn:
|
|
@@ -391,7 +477,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
391
477
|
}
|
|
392
478
|
object_type = object_type_map.get(table_type, "TABLE")
|
|
393
479
|
|
|
394
|
-
for meta in self._get_metadata(table_type, catalog_name, database_name, schema_name):
|
|
480
|
+
for meta in self._get_metadata(table_type, catalog_name, database_name, schema_name, tables=tables):
|
|
395
481
|
metadata_database = meta["database_name"]
|
|
396
482
|
full_name = self.full_name(
|
|
397
483
|
database_name=metadata_database,
|
|
@@ -416,7 +502,9 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
416
502
|
meta["table_name"],
|
|
417
503
|
object_type,
|
|
418
504
|
)
|
|
419
|
-
# Append indexes after subclass table clauses (e.g. distribution)
|
|
505
|
+
# Append indexes after subclass table clauses (e.g. distribution)
|
|
506
|
+
# and before any deferred ALTER TABLE statements so indexes exist
|
|
507
|
+
# before foreign keys referencing standalone unique indexes are added.
|
|
420
508
|
if object_type == "TABLE" and not ddl.startswith("-- DDL not available"):
|
|
421
509
|
try:
|
|
422
510
|
indexes = self._get_unique_index_definitions(meta["schema_name"], meta["table_name"])
|
|
@@ -426,9 +514,13 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
426
514
|
)
|
|
427
515
|
ddl += "\n-- Additional unique index metadata is unavailable."
|
|
428
516
|
else:
|
|
429
|
-
for
|
|
430
|
-
|
|
431
|
-
|
|
517
|
+
new_indexes = [idx for idx in indexes if idx.rstrip(";") not in ddl]
|
|
518
|
+
if new_indexes:
|
|
519
|
+
create_part, alter_lines = self._partition_table_ddl(ddl)
|
|
520
|
+
ddl_parts = [create_part] + new_indexes
|
|
521
|
+
if alter_lines:
|
|
522
|
+
ddl_parts.append("\n".join(alter_lines))
|
|
523
|
+
ddl = "\n".join(ddl_parts)
|
|
432
524
|
finally:
|
|
433
525
|
self._database_var.reset(token)
|
|
434
526
|
except Exception as e:
|
|
@@ -508,7 +600,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
508
600
|
table_name: str = "",
|
|
509
601
|
) -> List[Dict[str, Any]]:
|
|
510
602
|
"""
|
|
511
|
-
Get
|
|
603
|
+
Get visible columns from INFORMATION_SCHEMA with their declared PostgreSQL types.
|
|
512
604
|
|
|
513
605
|
Args:
|
|
514
606
|
catalog_name: Catalog name (unused)
|
|
@@ -545,12 +637,16 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
545
637
|
c.table_schema as table_schema,
|
|
546
638
|
c.table_name as table_name,
|
|
547
639
|
c.column_name as field,
|
|
548
|
-
|
|
640
|
+
pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
|
|
549
641
|
c.is_nullable as nullable,
|
|
550
642
|
c.column_default as default_value,
|
|
551
643
|
CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_pk,
|
|
552
644
|
pgd.description as comment
|
|
553
645
|
FROM information_schema.columns c
|
|
646
|
+
JOIN pg_catalog.pg_namespace n ON n.nspname = c.table_schema
|
|
647
|
+
JOIN pg_catalog.pg_class t ON t.relnamespace = n.oid AND t.relname = c.table_name
|
|
648
|
+
JOIN pg_catalog.pg_attribute a
|
|
649
|
+
ON a.attrelid = t.oid AND a.attnum = c.ordinal_position
|
|
554
650
|
LEFT JOIN (
|
|
555
651
|
SELECT kcu.table_schema, kcu.table_name, kcu.column_name
|
|
556
652
|
FROM information_schema.table_constraints tc
|
|
@@ -563,19 +659,19 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
563
659
|
) pk ON pk.table_schema = c.table_schema
|
|
564
660
|
AND pk.table_name = c.table_name
|
|
565
661
|
AND pk.column_name = c.column_name
|
|
566
|
-
LEFT JOIN pg_catalog.pg_statio_all_tables st
|
|
567
|
-
ON st.schemaname = c.table_schema AND st.relname = c.table_name
|
|
568
662
|
LEFT JOIN pg_catalog.pg_description pgd
|
|
569
|
-
ON pgd.objoid =
|
|
663
|
+
ON pgd.objoid = t.oid AND pgd.objsubid = a.attnum
|
|
664
|
+
AND pgd.classoid = 'pg_catalog.pg_class'::regclass
|
|
570
665
|
WHERE c.table_catalog = '{safe_db}'
|
|
571
666
|
AND {schema_cmp}
|
|
572
667
|
AND {table_cmp}
|
|
573
668
|
ORDER BY c.table_schema, c.table_name, c.ordinal_position
|
|
574
669
|
"""
|
|
575
670
|
|
|
576
|
-
|
|
671
|
+
# Keep user-defined type (and default expression) references schema-qualified.
|
|
672
|
+
query_result = self._execute_pandas(_build_sql(False), database_name=database_name, schema_name="pg_catalog")
|
|
577
673
|
if len(query_result) == 0:
|
|
578
|
-
query_result = self._execute_pandas(_build_sql(True), database_name=database_name)
|
|
674
|
+
query_result = self._execute_pandas(_build_sql(True), database_name=database_name, schema_name="pg_catalog")
|
|
579
675
|
self._raise_if_ambiguous_table(query_result, schema_name, table_name)
|
|
580
676
|
|
|
581
677
|
result = []
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "datus-postgresql"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.13"
|
|
4
4
|
description = "PostgreSQL database adapter for Datus"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -18,10 +18,11 @@ classifiers = [
|
|
|
18
18
|
]
|
|
19
19
|
|
|
20
20
|
dependencies = [
|
|
21
|
-
"datus-db-core>=0.1.
|
|
22
|
-
"datus-sqlalchemy>=0.1.
|
|
21
|
+
"datus-db-core>=0.1.12",
|
|
22
|
+
"datus-sqlalchemy>=0.1.14",
|
|
23
23
|
"psycopg2-binary>=2.9.11",
|
|
24
24
|
"pydantic>=2.0.0",
|
|
25
|
+
"sqlglot>=30.0.0",
|
|
25
26
|
]
|
|
26
27
|
|
|
27
28
|
[project.optional-dependencies]
|
|
@@ -110,13 +110,12 @@ def test_get_tables_with_ddl(connector: PostgreSQLConnector, config: PostgreSQLC
|
|
|
110
110
|
assert table["schema_name"] == config.schema_name
|
|
111
111
|
assert table["identifier"] == f"{config.database}.{config.schema_name}.{table_name}"
|
|
112
112
|
|
|
113
|
-
# The
|
|
114
|
-
# come back without their length modifier ("character varying", not "varchar(50)").
|
|
113
|
+
# The server renders canonical type names and retains their declared modifiers.
|
|
115
114
|
definition = table["definition"]
|
|
116
115
|
assert definition.startswith(f'CREATE TABLE "{config.database}"."{config.schema_name}"."{table_name}" (')
|
|
117
116
|
assert '"id" integer NOT NULL' in definition
|
|
118
|
-
assert f"nextval('{table_name}_id_seq'::regclass)" in definition
|
|
119
|
-
assert '"name" character varying' in definition
|
|
117
|
+
assert f"nextval('{config.schema_name}.{table_name}_id_seq'::regclass)" in definition
|
|
118
|
+
assert '"name" character varying(50)' in definition
|
|
120
119
|
assert f'CONSTRAINT "{table_name}_pkey" PRIMARY KEY (id)' in definition
|
|
121
120
|
finally:
|
|
122
121
|
connector.execute_ddl(f'DROP TABLE IF EXISTS "{config.schema_name}"."{table_name}"')
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
# Copyright 2025-present DatusAI, Inc.
|
|
2
|
+
# Licensed under the Apache License, Version 2.0.
|
|
3
|
+
|
|
4
|
+
import uuid
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from sqlalchemy import text
|
|
9
|
+
from sqlalchemy.exc import DBAPIError
|
|
10
|
+
|
|
11
|
+
from datus_db_core import build_reconciliation_checks
|
|
12
|
+
from datus_postgresql import PostgreSQLConnector
|
|
13
|
+
|
|
14
|
+
pytestmark = pytest.mark.integration
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def type_metadata_schema(connector):
|
|
19
|
+
"""Keep user-defined types outside the connector's configured search path."""
|
|
20
|
+
schema_name = f"Type Metadata_{uuid.uuid4().hex[:8]}"
|
|
21
|
+
schema_ref = connector.quote_identifier(schema_name)
|
|
22
|
+
created = connector.execute_ddl(f"CREATE SCHEMA {schema_ref}")
|
|
23
|
+
assert created.success, created.error
|
|
24
|
+
try:
|
|
25
|
+
yield schema_name, schema_ref
|
|
26
|
+
finally:
|
|
27
|
+
dropped = connector.execute_ddl(f"DROP SCHEMA {schema_ref} CASCADE")
|
|
28
|
+
assert dropped.success, dropped.error
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@pytest.mark.parametrize("relation_kind", ["table", "view"])
|
|
32
|
+
def test_schema_preserves_declared_column_types(connector, type_metadata_schema, relation_kind):
|
|
33
|
+
"""The information_schema type category loses modifiers, arrays and domain identity."""
|
|
34
|
+
schema_name, schema_ref = type_metadata_schema
|
|
35
|
+
table_ref = f'{schema_ref}."Typed Orders"'
|
|
36
|
+
enum_ref = f'{schema_ref}."Order State"'
|
|
37
|
+
domain_ref = f'{schema_ref}."Positive Amount"'
|
|
38
|
+
statements = [
|
|
39
|
+
f"CREATE TYPE {enum_ref} AS ENUM ('pending', 'paid')",
|
|
40
|
+
f"CREATE DOMAIN {domain_ref} AS numeric(8,2) CHECK (VALUE >= 0)",
|
|
41
|
+
f"CREATE TABLE {table_ref} (gone integer, "
|
|
42
|
+
f'"Amount" numeric(6,2) NOT NULL, currency varchar(3), fixed_code char(4), '
|
|
43
|
+
f"unlimited numeric, tags text[], rates numeric(8,3)[], "
|
|
44
|
+
f"recorded_at timestamp(3) with time zone, elapsed interval day to second(2), "
|
|
45
|
+
f"flags bit varying(7), state {enum_ref}, balance {domain_ref})",
|
|
46
|
+
f"ALTER TABLE {table_ref} DROP COLUMN gone",
|
|
47
|
+
f"COMMENT ON COLUMN {table_ref}.\"Amount\" IS 'Invoice amount'",
|
|
48
|
+
]
|
|
49
|
+
for statement in statements:
|
|
50
|
+
result = connector.execute_ddl(statement)
|
|
51
|
+
assert result.success, result.error
|
|
52
|
+
table_name = "Typed Orders"
|
|
53
|
+
if relation_kind == "view":
|
|
54
|
+
table_name = "Typed View"
|
|
55
|
+
result = connector.execute_ddl(f'CREATE VIEW {schema_ref}."{table_name}" AS SELECT * FROM {table_ref}')
|
|
56
|
+
assert result.success, result.error
|
|
57
|
+
result = connector.execute_ddl(f'COMMENT ON COLUMN {schema_ref}."{table_name}"."Amount" IS \'View amount\'')
|
|
58
|
+
assert result.success, result.error
|
|
59
|
+
|
|
60
|
+
expected = {
|
|
61
|
+
"Amount": "numeric(6,2)",
|
|
62
|
+
"currency": "character varying(3)",
|
|
63
|
+
"fixed_code": "character(4)",
|
|
64
|
+
"unlimited": "numeric",
|
|
65
|
+
"tags": "text[]",
|
|
66
|
+
"rates": "numeric(8,3)[]",
|
|
67
|
+
"recorded_at": "timestamp(3) with time zone",
|
|
68
|
+
"elapsed": "interval day to second(2)",
|
|
69
|
+
"flags": "bit varying(7)",
|
|
70
|
+
"state": enum_ref,
|
|
71
|
+
"balance": domain_ref,
|
|
72
|
+
}
|
|
73
|
+
columns = connector.get_schema(schema_name=schema_name, table_name=table_name)
|
|
74
|
+
assert [(col["name"], col["type"]) for col in columns] == list(expected.items())
|
|
75
|
+
assert columns[0]["comment"] == ("View amount" if relation_kind == "view" else "Invoice amount")
|
|
76
|
+
fallback_columns = connector.get_schema(schema_name=schema_name.upper(), table_name=table_name.upper())
|
|
77
|
+
assert fallback_columns == columns
|
|
78
|
+
|
|
79
|
+
if relation_kind == "table":
|
|
80
|
+
assert columns[0] == {
|
|
81
|
+
"cid": 0,
|
|
82
|
+
"name": "Amount",
|
|
83
|
+
"type": "numeric(6,2)",
|
|
84
|
+
"nullable": False,
|
|
85
|
+
"default_value": None,
|
|
86
|
+
"pk": False,
|
|
87
|
+
"comment": "Invoice amount",
|
|
88
|
+
}
|
|
89
|
+
definitions = connector.get_tables_with_ddl(schema_name=schema_name, tables=[table_name])
|
|
90
|
+
assert [item["table_name"] for item in definitions] == [table_name]
|
|
91
|
+
ddl = definitions[0]["definition"]
|
|
92
|
+
for name, column_type in expected.items():
|
|
93
|
+
assert f"{connector.quote_identifier(name)} {column_type}" in ddl
|
|
94
|
+
replay = connector.execute_ddl(ddl.replace('"Typed Orders"', '"Replayed Orders"', 1))
|
|
95
|
+
assert replay.success, replay.error
|
|
96
|
+
replay_columns = connector.get_schema(schema_name=schema_name, table_name="Replayed Orders")
|
|
97
|
+
assert [(col["name"], col["type"]) for col in replay_columns] == list(expected.items())
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_reconstructed_ddl_preserves_amount_and_currency_rules(connector, type_metadata_schema):
|
|
101
|
+
"""Replayed types must round amounts and reject the same out-of-range input."""
|
|
102
|
+
schema_name, schema_ref = type_metadata_schema
|
|
103
|
+
source = f'{schema_ref}."invoice"'
|
|
104
|
+
target = f'{schema_ref}."invoice_copy"'
|
|
105
|
+
created = connector.execute_ddl(f"CREATE TABLE {source} (amount numeric(6,2), currency varchar(3))")
|
|
106
|
+
assert created.success, created.error
|
|
107
|
+
ddl = connector.get_tables_with_ddl(schema_name=schema_name, tables=["invoice"])[0]["definition"]
|
|
108
|
+
replayed = connector.execute_ddl(ddl.replace('"invoice"', '"invoice_copy"', 1))
|
|
109
|
+
assert replayed.success, replayed.error
|
|
110
|
+
|
|
111
|
+
for table in (source, target):
|
|
112
|
+
with connector._conn() as conn:
|
|
113
|
+
amount = conn.execute(text(f"INSERT INTO {table} VALUES (1.239, 'CNY') RETURNING amount")).scalar_one()
|
|
114
|
+
assert amount == Decimal("1.24")
|
|
115
|
+
for amount, currency, sqlstate in [("10000", "CNY", "22003"), ("1", "CNYY", "22001")]:
|
|
116
|
+
with pytest.raises(DBAPIError) as error, connector._conn() as conn:
|
|
117
|
+
conn.execute(
|
|
118
|
+
text(f"INSERT INTO {table} VALUES (:amount, :currency)"), {"amount": amount, "currency": currency}
|
|
119
|
+
)
|
|
120
|
+
assert error.value.orig.pgcode == sqlstate
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.mark.parametrize("validated", [None, True, False], ids=["no-fk", "validated-fk", "not-valid-fk"])
|
|
124
|
+
def test_ddl_replay_preserves_multiline_defaults_and_unique_indexes(connector, type_metadata_schema, validated):
|
|
125
|
+
"""A line of a string literal must never become the boundary for inserting indexes."""
|
|
126
|
+
schema_name, schema_ref = type_metadata_schema
|
|
127
|
+
table_ref = f'{schema_ref}."literal_defaults"'
|
|
128
|
+
default_value = "head's;\nALTER TABLE literal text;\ntail"
|
|
129
|
+
literal = default_value.replace("'", "''")
|
|
130
|
+
statements = [
|
|
131
|
+
f"CREATE TABLE {table_ref} (id integer DEFAULT 0 PRIMARY KEY, code integer DEFAULT 0, "
|
|
132
|
+
f"parent_code integer DEFAULT 0, note text DEFAULT '{literal}')",
|
|
133
|
+
f'CREATE UNIQUE INDEX "literal_code_idx" ON {table_ref} (code)',
|
|
134
|
+
]
|
|
135
|
+
if validated is not None:
|
|
136
|
+
suffix = "" if validated else " NOT VALID"
|
|
137
|
+
statements.append(
|
|
138
|
+
f'ALTER TABLE {table_ref} ADD CONSTRAINT "parent_fk" '
|
|
139
|
+
f"FOREIGN KEY (parent_code) REFERENCES {table_ref} (code){suffix}"
|
|
140
|
+
)
|
|
141
|
+
for statement in statements:
|
|
142
|
+
result = connector.execute_ddl(statement)
|
|
143
|
+
assert result.success, result.error
|
|
144
|
+
|
|
145
|
+
definition = connector.get_tables_with_ddl(schema_name=schema_name, tables=["literal_defaults"])[0]["definition"]
|
|
146
|
+
dropped = connector.execute_ddl(f"DROP TABLE {table_ref}")
|
|
147
|
+
assert dropped.success, dropped.error
|
|
148
|
+
replayed = connector.execute_ddl(definition, schema_name=schema_name)
|
|
149
|
+
assert replayed.success, replayed.error
|
|
150
|
+
|
|
151
|
+
with connector._conn() as conn:
|
|
152
|
+
note = conn.execute(
|
|
153
|
+
text(f"INSERT INTO {table_ref} (id, code, parent_code) VALUES (1, 1, 1) RETURNING note")
|
|
154
|
+
).scalar_one()
|
|
155
|
+
assert note == default_value
|
|
156
|
+
conn.commit()
|
|
157
|
+
with pytest.raises(DBAPIError) as error, connector._conn() as conn:
|
|
158
|
+
conn.execute(text(f"INSERT INTO {table_ref} (id, code, parent_code) VALUES (2, 1, 1)"))
|
|
159
|
+
assert error.value.orig.pgcode == "23505"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@pytest.mark.parametrize("validated", [True, False])
|
|
163
|
+
def test_ddl_replay_preserves_cross_schema_foreign_key_target(connector, type_metadata_schema, validated):
|
|
164
|
+
"""An FK to a visible parent must retain its schema when replayed beside a namesake."""
|
|
165
|
+
schema_name, schema_ref = type_metadata_schema
|
|
166
|
+
parent_name = f"fk_parent_{uuid.uuid4().hex[:8]}"
|
|
167
|
+
parent_ref = f"{connector.quote_identifier(connector.schema_name)}.{connector.quote_identifier(parent_name)}"
|
|
168
|
+
shadow_ref = f"{schema_ref}.{connector.quote_identifier(parent_name)}"
|
|
169
|
+
child_ref = f'{schema_ref}."child"'
|
|
170
|
+
suffix = "" if validated else " NOT VALID"
|
|
171
|
+
try:
|
|
172
|
+
for statement in [
|
|
173
|
+
f"CREATE TABLE {parent_ref} (id integer PRIMARY KEY)",
|
|
174
|
+
f"CREATE TABLE {shadow_ref} (id integer PRIMARY KEY)",
|
|
175
|
+
f"CREATE TABLE {child_ref} (id integer, parent_id integer)",
|
|
176
|
+
f"ALTER TABLE {child_ref} ADD CONSTRAINT parent_fk FOREIGN KEY (parent_id) REFERENCES {parent_ref}(id){suffix}",
|
|
177
|
+
]:
|
|
178
|
+
result = connector.execute_ddl(statement)
|
|
179
|
+
assert result.success, result.error
|
|
180
|
+
definition = connector.get_tables_with_ddl(schema_name=schema_name, tables=["child"])[0]["definition"]
|
|
181
|
+
dropped = connector.execute_ddl(f"DROP TABLE {child_ref}")
|
|
182
|
+
assert dropped.success, dropped.error
|
|
183
|
+
replayed = connector.execute_ddl(definition, schema_name=schema_name)
|
|
184
|
+
assert replayed.success, replayed.error
|
|
185
|
+
|
|
186
|
+
with connector._conn() as conn:
|
|
187
|
+
target = conn.execute(
|
|
188
|
+
text("""SELECT n.nspname, p.relname, c.convalidated
|
|
189
|
+
FROM pg_catalog.pg_constraint c
|
|
190
|
+
JOIN pg_catalog.pg_class p ON p.oid = c.confrelid
|
|
191
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = p.relnamespace
|
|
192
|
+
WHERE c.conrelid = CAST(:child AS regclass) AND c.contype = 'f'"""),
|
|
193
|
+
{"child": child_ref},
|
|
194
|
+
).one()
|
|
195
|
+
assert tuple(target) == (connector.schema_name, parent_name, validated)
|
|
196
|
+
finally:
|
|
197
|
+
dropped = connector.execute_ddl(f"DROP TABLE IF EXISTS {parent_ref} CASCADE")
|
|
198
|
+
assert dropped.success, dropped.error
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@pytest.mark.parametrize("type_kind", ["enum", "domain"])
|
|
202
|
+
@pytest.mark.parametrize("array", [False, True], ids=["scalar", "array"])
|
|
203
|
+
def test_ddl_replay_preserves_visible_user_defined_type_identity(connector, type_metadata_schema, type_kind, array):
|
|
204
|
+
"""Visible enum/domain references must not bind to another schema's same-named type."""
|
|
205
|
+
schema_name, schema_ref = type_metadata_schema
|
|
206
|
+
type_name = f"Review Value_{uuid.uuid4().hex[:8]}"
|
|
207
|
+
type_ref = f"{connector.quote_identifier(connector.schema_name)}.{connector.quote_identifier(type_name)}"
|
|
208
|
+
shadow_ref = f"{schema_ref}.{connector.quote_identifier(type_name)}"
|
|
209
|
+
source_ref = f'{schema_ref}."typed_source"'
|
|
210
|
+
copy_ref = f'{schema_ref}."typed_copy"'
|
|
211
|
+
if type_kind == "enum":
|
|
212
|
+
statements = [
|
|
213
|
+
f"CREATE TYPE {type_ref} AS ENUM ('pending', 'paid')",
|
|
214
|
+
f"CREATE TYPE {shadow_ref} AS ENUM ('wrong')",
|
|
215
|
+
]
|
|
216
|
+
else:
|
|
217
|
+
statements = [
|
|
218
|
+
f"CREATE DOMAIN {type_ref} AS numeric(8,2) CHECK (VALUE >= 0)",
|
|
219
|
+
f"CREATE DOMAIN {shadow_ref} AS numeric(8,2)",
|
|
220
|
+
]
|
|
221
|
+
statements.append(f"CREATE TABLE {source_ref} (value {type_ref}{'[]' if array else ''})")
|
|
222
|
+
try:
|
|
223
|
+
for statement in statements:
|
|
224
|
+
result = connector.execute_ddl(statement)
|
|
225
|
+
assert result.success, result.error
|
|
226
|
+
definition = connector.get_tables_with_ddl(schema_name=schema_name, tables=["typed_source"])[0]["definition"]
|
|
227
|
+
replayed = connector.execute_ddl(
|
|
228
|
+
definition.replace('"typed_source"', '"typed_copy"', 1), schema_name=schema_name
|
|
229
|
+
)
|
|
230
|
+
assert replayed.success, replayed.error
|
|
231
|
+
with connector._conn() as conn:
|
|
232
|
+
type_oids = [
|
|
233
|
+
conn.execute(
|
|
234
|
+
text("""SELECT a.atttypid FROM pg_catalog.pg_attribute a
|
|
235
|
+
WHERE a.attrelid = CAST(:relation AS regclass) AND a.attname = 'value'"""),
|
|
236
|
+
{"relation": relation},
|
|
237
|
+
).scalar_one()
|
|
238
|
+
for relation in (source_ref, copy_ref)
|
|
239
|
+
]
|
|
240
|
+
assert type_oids[0] == type_oids[1]
|
|
241
|
+
# A metadata read must not change the context used by later operations.
|
|
242
|
+
visible_oid = conn.execute(
|
|
243
|
+
text("SELECT CAST(:type AS regtype)::oid"), {"type": connector.quote_identifier(type_name)}
|
|
244
|
+
).scalar_one()
|
|
245
|
+
expected_oid = conn.execute(text("SELECT CAST(:type AS regtype)::oid"), {"type": type_ref}).scalar_one()
|
|
246
|
+
assert visible_oid == expected_oid
|
|
247
|
+
finally:
|
|
248
|
+
drop_kind = "TYPE" if type_kind == "enum" else "DOMAIN"
|
|
249
|
+
dropped = connector.execute_ddl(f"DROP {drop_kind} IF EXISTS {type_ref} CASCADE")
|
|
250
|
+
assert dropped.success, dropped.error
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_declared_array_types_produce_executable_reconciliation_checks(connector, type_metadata_schema):
|
|
254
|
+
"""Array types retain their SQL identity without entering scalar SUM/AVG checks."""
|
|
255
|
+
schema_name, schema_ref = type_metadata_schema
|
|
256
|
+
table_ref = f'{schema_ref}."array_checks"'
|
|
257
|
+
created = connector.execute_ddl(
|
|
258
|
+
f"CREATE TABLE {table_ref} (id integer, amount numeric(6,2), amounts numeric(8,3)[], days date[])"
|
|
259
|
+
)
|
|
260
|
+
assert created.success, created.error
|
|
261
|
+
inserted = connector.execute_insert(
|
|
262
|
+
f"INSERT INTO {table_ref} VALUES (1, 1.24, ARRAY[1.123, 4.567], ARRAY[DATE '2024-01-01'])"
|
|
263
|
+
)
|
|
264
|
+
assert inserted.success, inserted.error
|
|
265
|
+
columns = connector.get_schema(schema_name=schema_name, table_name="array_checks")
|
|
266
|
+
assert [column["type"] for column in columns] == ["integer", "numeric(6,2)", "numeric(8,3)[]", "date[]"]
|
|
267
|
+
checks = build_reconciliation_checks(table_ref, table_ref, columns, key_columns=["id"])
|
|
268
|
+
with connector._conn() as conn:
|
|
269
|
+
results = {check["name"]: conn.execute(text(check["source_query"])).fetchall() for check in checks}
|
|
270
|
+
assert results["numeric_aggregate"] == [(1, Decimal("1"), Decimal("1.24"), Decimal("1.24"))]
|
|
271
|
+
assert results["duplicate_key"] == []
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def test_ddl_preserves_composite_keys_and_standalone_unique_indexes(config):
|
|
275
|
+
"""Key order comes from constraints; index predicates and expressions must survive."""
|
|
276
|
+
connector = PostgreSQLConnector(config)
|
|
277
|
+
table_name = f"ddl_keys_{uuid.uuid4().hex[:8]}"
|
|
278
|
+
table_ref = f'{connector.quote_identifier(config.schema_name)}."{table_name}"'
|
|
279
|
+
index_prefix = f"{table_name}_index"
|
|
280
|
+
statements = [
|
|
281
|
+
f'CREATE TABLE {table_ref} (id INT, "Tenant ID" INT, email TEXT, active BOOLEAN, '
|
|
282
|
+
'PRIMARY KEY ("Tenant ID", id), CONSTRAINT "Email Key" UNIQUE (email, "Tenant ID"))',
|
|
283
|
+
f"CREATE UNIQUE INDEX {index_prefix}_plain ON {table_ref} (email, id)",
|
|
284
|
+
f"CREATE UNIQUE INDEX {index_prefix}_partial ON {table_ref} (email) WHERE active",
|
|
285
|
+
f"CREATE UNIQUE INDEX {index_prefix}_expression ON {table_ref} (lower(email))",
|
|
286
|
+
f"CREATE INDEX {index_prefix}_ordinary ON {table_ref} (active)",
|
|
287
|
+
]
|
|
288
|
+
try:
|
|
289
|
+
for statement in statements:
|
|
290
|
+
result = connector.execute_ddl(statement)
|
|
291
|
+
assert result.success, result.error
|
|
292
|
+
|
|
293
|
+
tables = connector.get_tables_with_ddl(schema_name=config.schema_name, tables=[table_name])
|
|
294
|
+
|
|
295
|
+
assert [table["table_name"] for table in tables] == [table_name]
|
|
296
|
+
definition = tables[0]["definition"]
|
|
297
|
+
assert f'CONSTRAINT "{table_name}_pkey" PRIMARY KEY ("Tenant ID", id)' in definition
|
|
298
|
+
assert 'CONSTRAINT "Email Key" UNIQUE (email, "Tenant ID")' in definition
|
|
299
|
+
assert definition.count("CREATE UNIQUE INDEX") == 3
|
|
300
|
+
assert f"{index_prefix}_plain" in definition and "USING btree (email, id);" in definition
|
|
301
|
+
assert f"{index_prefix}_partial" in definition and "USING btree (email) WHERE active;" in definition
|
|
302
|
+
assert f"{index_prefix}_expression" in definition and "USING btree (lower(email));" in definition
|
|
303
|
+
assert f"{index_prefix}_ordinary" not in definition
|
|
304
|
+
finally:
|
|
305
|
+
try:
|
|
306
|
+
dropped = connector.execute_ddl(f"DROP TABLE IF EXISTS {table_ref}")
|
|
307
|
+
assert dropped.success, dropped.error
|
|
308
|
+
finally:
|
|
309
|
+
connector.close()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@pytest.mark.parametrize("validated", [True, False])
|
|
313
|
+
def test_ddl_round_trip_self_referencing_foreign_key_with_standalone_unique_index(config, validated):
|
|
314
|
+
"""Test that self-referencing foreign keys referencing standalone unique indexes round-trip successfully.
|
|
315
|
+
|
|
316
|
+
Validated foreign keys must be deferred out of CREATE TABLE to run after the
|
|
317
|
+
standalone unique index is created. NOT VALID foreign keys must also run after
|
|
318
|
+
the unique index. Replaying the reconstructed DDL on a clean table must succeed.
|
|
319
|
+
"""
|
|
320
|
+
connector = PostgreSQLConnector(config)
|
|
321
|
+
table_name = f"ddl_self_fk_{uuid.uuid4().hex[:8]}"
|
|
322
|
+
replay_table_name = f"{table_name}_replay"
|
|
323
|
+
table_ref = f'{connector.quote_identifier(config.schema_name)}."{table_name}"'
|
|
324
|
+
replay_ref = f'{connector.quote_identifier(config.schema_name)}."{replay_table_name}"'
|
|
325
|
+
index_name = f"{table_name}_code_idx"
|
|
326
|
+
fk_name = f"{table_name}_parent_fk"
|
|
327
|
+
|
|
328
|
+
fk_suffix = "" if validated else " NOT VALID"
|
|
329
|
+
statements = [
|
|
330
|
+
f"CREATE TABLE {table_ref} (id INT PRIMARY KEY, code INT, parent_code INT)",
|
|
331
|
+
f'CREATE UNIQUE INDEX "{index_name}" ON {table_ref} (code)',
|
|
332
|
+
f'ALTER TABLE {table_ref} ADD CONSTRAINT "{fk_name}" FOREIGN KEY (parent_code) REFERENCES {table_ref} (code){fk_suffix}',
|
|
333
|
+
]
|
|
334
|
+
try:
|
|
335
|
+
for statement in statements:
|
|
336
|
+
result = connector.execute_ddl(statement)
|
|
337
|
+
assert result.success, result.error
|
|
338
|
+
|
|
339
|
+
tables = connector.get_tables_with_ddl(schema_name=config.schema_name, tables=[table_name])
|
|
340
|
+
assert [table["table_name"] for table in tables] == [table_name]
|
|
341
|
+
definition = tables[0]["definition"]
|
|
342
|
+
|
|
343
|
+
# Verify dependency ordering in generated DDL:
|
|
344
|
+
# CREATE TABLE must not contain the foreign key referencing the standalone index
|
|
345
|
+
assert f'CONSTRAINT "{fk_name}"' not in definition.split("CREATE UNIQUE INDEX")[0]
|
|
346
|
+
# CREATE UNIQUE INDEX must precede ALTER TABLE ADD CONSTRAINT
|
|
347
|
+
assert definition.find("CREATE UNIQUE INDEX") < definition.find(f'ADD CONSTRAINT "{fk_name}"')
|
|
348
|
+
|
|
349
|
+
# Live round-trip: Replay reconstructed DDL under replay table name.
|
|
350
|
+
# Drop the source table first to guarantee replay does not depend on the existing table.
|
|
351
|
+
dropped = connector.execute_ddl(f"DROP TABLE IF EXISTS {table_ref} CASCADE")
|
|
352
|
+
assert dropped.success, dropped.error
|
|
353
|
+
|
|
354
|
+
replay_ddl = definition.replace(table_name, replay_table_name)
|
|
355
|
+
|
|
356
|
+
for stmt in [s.strip() for s in replay_ddl.split(";") if s.strip()]:
|
|
357
|
+
res = connector.execute_ddl(stmt)
|
|
358
|
+
assert res.success, f"Replaying statement failed: {stmt}\nError: {res.error}\nFull DDL:\n{definition}"
|
|
359
|
+
|
|
360
|
+
finally:
|
|
361
|
+
try:
|
|
362
|
+
connector.execute_ddl(f"DROP TABLE IF EXISTS {table_ref} CASCADE")
|
|
363
|
+
connector.execute_ddl(f"DROP TABLE IF EXISTS {replay_ref} CASCADE")
|
|
364
|
+
finally:
|
|
365
|
+
connector.close()
|
|
@@ -4,7 +4,7 @@ import pytest
|
|
|
4
4
|
|
|
5
5
|
from datus_db_core import DatusDbException, ErrorCode
|
|
6
6
|
from datus_postgresql import PostgreSQLConnector
|
|
7
|
-
from datus_sqlalchemy.testing import BlackholeProxy, assert_stalled_response_timeout
|
|
7
|
+
from datus_sqlalchemy.testing import BlackholeProxy, assert_query_timeout_override, assert_stalled_response_timeout
|
|
8
8
|
|
|
9
9
|
pytestmark = pytest.mark.integration
|
|
10
10
|
|
|
@@ -97,3 +97,15 @@ def test_reused_writer_validator_has_deadline_before_checkout_sql(config, engine
|
|
|
97
97
|
assert connection.execute(text("SELECT 42")).scalar_one() == 42
|
|
98
98
|
finally:
|
|
99
99
|
connector.close()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_query_timeout_override_is_scoped_to_one_select(config):
|
|
103
|
+
# Keep the TLS fixture's resolved verify-full mode and CA while testing
|
|
104
|
+
# the community server's per-statement timeout.
|
|
105
|
+
config = config.model_copy(update={"aurora": False})
|
|
106
|
+
assert_query_timeout_override(
|
|
107
|
+
config,
|
|
108
|
+
PostgreSQLConnector,
|
|
109
|
+
"SELECT setting AS deadline FROM pg_settings WHERE name = 'statement_timeout'",
|
|
110
|
+
units_per_second=1000,
|
|
111
|
+
)
|
|
@@ -644,7 +644,48 @@ def test_get_schema_empty_table_name_short_circuit():
|
|
|
644
644
|
connector._execute_pandas.assert_not_called()
|
|
645
645
|
|
|
646
646
|
|
|
647
|
+
@pytest.mark.parametrize("use_fallback", [False, True])
|
|
648
|
+
def test_get_schema_requests_declared_types_at_connection_boundary(use_fallback):
|
|
649
|
+
"""Both lookup paths use server type modifiers while retaining column visibility."""
|
|
650
|
+
connector = PostgreSQLConnector(PostgreSQLConfig(username="u", database="testdb"))
|
|
651
|
+
row = namedtuple("Column", _SCHEMA_COLS)(
|
|
652
|
+
"Types'24", "Orders'24", "amount", "numeric(6,2)", "NO", "0", False, "Invoice amount"
|
|
653
|
+
)
|
|
654
|
+
try:
|
|
655
|
+
with patch.object(connector, "_conn") as connection:
|
|
656
|
+
conn = connection.return_value.__enter__.return_value
|
|
657
|
+
conn.exec_driver_sql.return_value.fetchall.side_effect = [[], [row]] if use_fallback else [[row]]
|
|
658
|
+
columns = connector.get_schema(database_name="other_db", schema_name="Types'24", table_name="Orders'24")
|
|
659
|
+
|
|
660
|
+
assert columns == [
|
|
661
|
+
{
|
|
662
|
+
"cid": 0,
|
|
663
|
+
"name": "amount",
|
|
664
|
+
"type": "numeric(6,2)",
|
|
665
|
+
"nullable": False,
|
|
666
|
+
"default_value": "0",
|
|
667
|
+
"pk": False,
|
|
668
|
+
"comment": "Invoice amount",
|
|
669
|
+
}
|
|
670
|
+
]
|
|
671
|
+
assert conn.exec_driver_sql.call_count == (2 if use_fallback else 1)
|
|
672
|
+
for call in conn.exec_driver_sql.call_args_list:
|
|
673
|
+
sql = call.args[0]
|
|
674
|
+
assert "pg_catalog.format_type(a.atttypid, a.atttypmod) as type" in sql
|
|
675
|
+
assert "FROM information_schema.columns c" in sql
|
|
676
|
+
assert "a.attrelid = t.oid AND a.attnum = c.ordinal_position" in sql
|
|
677
|
+
assert "c.table_catalog = 'other_db'" in sql
|
|
678
|
+
assert "Types''24" in sql and "Orders''24" in sql
|
|
679
|
+
assert all(call.kwargs["database_name"] == "other_db" for call in connection.call_args_list)
|
|
680
|
+
assert all(call.kwargs["schema_name"] == "pg_catalog" for call in connection.call_args_list)
|
|
681
|
+
if use_fallback:
|
|
682
|
+
assert "lower(c.table_name)" in conn.exec_driver_sql.call_args.args[0]
|
|
683
|
+
finally:
|
|
684
|
+
connector.close()
|
|
685
|
+
|
|
686
|
+
|
|
647
687
|
def test_get_ddl_uses_requested_database_for_table_schema():
|
|
688
|
+
"""Test that _get_ddl retrieves table schema from the specified database_name."""
|
|
648
689
|
connector = _make_pg_connector_for_metadata(database_name="default_db")
|
|
649
690
|
connector.get_schema = MagicMock(return_value=[])
|
|
650
691
|
|
|
@@ -663,13 +704,32 @@ def test_get_ddl_uses_requested_database_for_table_schema():
|
|
|
663
704
|
[
|
|
664
705
|
([], ""),
|
|
665
706
|
(
|
|
666
|
-
[
|
|
707
|
+
[
|
|
708
|
+
("orders_pk", True, "PRIMARY KEY (tenant_id, id)", False),
|
|
709
|
+
('Unique "Email', True, "UNIQUE (email, tenant_id)", False),
|
|
710
|
+
],
|
|
667
711
|
',\n CONSTRAINT "orders_pk" PRIMARY KEY (tenant_id, id)'
|
|
668
712
|
',\n CONSTRAINT "Unique ""Email" UNIQUE (email, tenant_id)',
|
|
669
713
|
),
|
|
714
|
+
(
|
|
715
|
+
[
|
|
716
|
+
("orders_pk", True, "PRIMARY KEY (tenant_id, id)", False),
|
|
717
|
+
('Unique "Email', True, "UNIQUE (email, tenant_id)", False),
|
|
718
|
+
(
|
|
719
|
+
"orders_customer_fk",
|
|
720
|
+
True,
|
|
721
|
+
"FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE",
|
|
722
|
+
False,
|
|
723
|
+
),
|
|
724
|
+
],
|
|
725
|
+
',\n CONSTRAINT "orders_pk" PRIMARY KEY (tenant_id, id)'
|
|
726
|
+
',\n CONSTRAINT "Unique ""Email" UNIQUE (email, tenant_id)'
|
|
727
|
+
',\n CONSTRAINT "orders_customer_fk" FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE',
|
|
728
|
+
),
|
|
670
729
|
],
|
|
671
730
|
)
|
|
672
731
|
def test_table_ddl_preserves_server_constraint_order_and_names(constraints, expected_constraints):
|
|
732
|
+
"""Test that reconstructed table DDL preserves server constraint order, types, and names."""
|
|
673
733
|
connector = _make_pg_connector_for_metadata(database_name="default_db")
|
|
674
734
|
connector.dialect = "postgresql"
|
|
675
735
|
connector._conn = MagicMock()
|
|
@@ -694,7 +754,137 @@ def test_table_ddl_preserves_server_constraint_order_and_names(constraints, expe
|
|
|
694
754
|
f"{expected_constraints}\n);"
|
|
695
755
|
)
|
|
696
756
|
assert [call.kwargs["database_name"] for call in connector._conn.call_args_list] == ["other_db", "other_db"]
|
|
757
|
+
assert connector._conn.call_args.kwargs["schema_name"] == "pg_catalog"
|
|
697
758
|
assert connection.execute.call_args.args[1] == {"schema_name": "public", "table_name": "orders"}
|
|
759
|
+
assert "c.contype IN ('p', 'u', 'f')" in str(connection.execute.call_args.args[0])
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def test_table_ddl_emits_unvalidated_foreign_keys_as_alter_table():
|
|
763
|
+
"""Test that unvalidated constraints (NOT VALID) are emitted as separate ALTER TABLE statements."""
|
|
764
|
+
connector = _make_pg_connector_for_metadata(database_name="default_db")
|
|
765
|
+
connector.dialect = "postgresql"
|
|
766
|
+
connector._conn = MagicMock()
|
|
767
|
+
connection = connector._conn.return_value.__enter__.return_value
|
|
768
|
+
row = namedtuple("SchemaRow", _SCHEMA_COLS)
|
|
769
|
+
schema_result = MagicMock()
|
|
770
|
+
schema_result.fetchall.return_value = [
|
|
771
|
+
row("public", "orders", "id", "integer", "NO", None, True, None),
|
|
772
|
+
row("public", "orders", "customer_id", "integer", "NO", None, False, None),
|
|
773
|
+
]
|
|
774
|
+
constraint_result = MagicMock()
|
|
775
|
+
constraint_result.fetchall.return_value = [
|
|
776
|
+
("orders_pk", True, "PRIMARY KEY (id)", False),
|
|
777
|
+
("orders_customer_fk", False, "FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID", False),
|
|
778
|
+
]
|
|
779
|
+
connection.exec_driver_sql.return_value = schema_result
|
|
780
|
+
connection.execute.return_value = constraint_result
|
|
781
|
+
|
|
782
|
+
ddl = connector._get_ddl("public", "orders", database_name="other_db")
|
|
783
|
+
|
|
784
|
+
expected_ddl = (
|
|
785
|
+
'CREATE TABLE "other_db"."public"."orders" (\n'
|
|
786
|
+
' "id" integer NOT NULL,\n'
|
|
787
|
+
' "customer_id" integer NOT NULL,\n'
|
|
788
|
+
' CONSTRAINT "orders_pk" PRIMARY KEY (id)\n'
|
|
789
|
+
");\n"
|
|
790
|
+
'ALTER TABLE "other_db"."public"."orders" ADD CONSTRAINT "orders_customer_fk" FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;'
|
|
791
|
+
)
|
|
792
|
+
assert ddl == expected_ddl
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def test_table_ddl_defers_foreign_keys_referencing_standalone_indexes():
|
|
796
|
+
"""Test that foreign keys referencing standalone unique indexes are deferred to ALTER TABLE."""
|
|
797
|
+
connector = _make_pg_connector_for_metadata(database_name="default_db")
|
|
798
|
+
connector.dialect = "postgresql"
|
|
799
|
+
connector._conn = MagicMock()
|
|
800
|
+
connection = connector._conn.return_value.__enter__.return_value
|
|
801
|
+
row = namedtuple("SchemaRow", _SCHEMA_COLS)
|
|
802
|
+
schema_result = MagicMock()
|
|
803
|
+
schema_result.fetchall.return_value = [
|
|
804
|
+
row("public", "t", "id", "integer", "NO", None, True, None),
|
|
805
|
+
row("public", "t", "code", "integer", "YES", None, False, None),
|
|
806
|
+
row("public", "t", "parent_code", "integer", "YES", None, False, None),
|
|
807
|
+
]
|
|
808
|
+
constraint_result = MagicMock()
|
|
809
|
+
# (name, is_validated, definition, depends_on_standalone_index)
|
|
810
|
+
constraint_result.fetchall.return_value = [
|
|
811
|
+
("t_pkey", True, "PRIMARY KEY (id)", False),
|
|
812
|
+
("t_parent_fk", True, "FOREIGN KEY (parent_code) REFERENCES t(code)", True),
|
|
813
|
+
]
|
|
814
|
+
connection.exec_driver_sql.return_value = schema_result
|
|
815
|
+
connection.execute.return_value = constraint_result
|
|
816
|
+
|
|
817
|
+
ddl = connector._get_ddl("public", "t", database_name="other_db")
|
|
818
|
+
|
|
819
|
+
expected_ddl = (
|
|
820
|
+
'CREATE TABLE "other_db"."public"."t" (\n'
|
|
821
|
+
' "id" integer NOT NULL,\n'
|
|
822
|
+
' "code" integer,\n'
|
|
823
|
+
' "parent_code" integer,\n'
|
|
824
|
+
' CONSTRAINT "t_pkey" PRIMARY KEY (id)\n'
|
|
825
|
+
");\n"
|
|
826
|
+
'ALTER TABLE "other_db"."public"."t" ADD CONSTRAINT "t_parent_fk" FOREIGN KEY (parent_code) REFERENCES t(code);'
|
|
827
|
+
)
|
|
828
|
+
assert ddl == expected_ddl
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def test_get_objects_with_ddl_places_unique_indexes_before_deferred_alter_table():
|
|
832
|
+
"""Test that unique indexes are placed before deferred ALTER TABLE statements."""
|
|
833
|
+
connector = _make_pg_connector_for_metadata(database_name="default_db")
|
|
834
|
+
metadata = [
|
|
835
|
+
{
|
|
836
|
+
"identifier": "other_db.public.t",
|
|
837
|
+
"catalog_name": "",
|
|
838
|
+
"database_name": "other_db",
|
|
839
|
+
"schema_name": "public",
|
|
840
|
+
"table_name": "t",
|
|
841
|
+
"table_type": "table",
|
|
842
|
+
}
|
|
843
|
+
]
|
|
844
|
+
connector._get_metadata = MagicMock(return_value=metadata)
|
|
845
|
+
connector._get_ddl = MagicMock(
|
|
846
|
+
return_value=(
|
|
847
|
+
'CREATE TABLE "other_db"."public"."t" (\n'
|
|
848
|
+
' "id" integer PRIMARY KEY\n'
|
|
849
|
+
");\n"
|
|
850
|
+
'ALTER TABLE "other_db"."public"."t" ADD CONSTRAINT "t_parent_fk" FOREIGN KEY (parent_code) REFERENCES t(code);'
|
|
851
|
+
)
|
|
852
|
+
)
|
|
853
|
+
connector._get_unique_index_definitions = MagicMock(
|
|
854
|
+
return_value=["CREATE UNIQUE INDEX t_code_idx ON other_db.public.t USING btree (code);"]
|
|
855
|
+
)
|
|
856
|
+
|
|
857
|
+
result = connector._get_objects_with_ddl("table", database_name="other_db", schema_name="public")
|
|
858
|
+
|
|
859
|
+
expected_ddl = (
|
|
860
|
+
'CREATE TABLE "other_db"."public"."t" (\n'
|
|
861
|
+
' "id" integer PRIMARY KEY\n'
|
|
862
|
+
");\n"
|
|
863
|
+
"CREATE UNIQUE INDEX t_code_idx ON other_db.public.t USING btree (code);\n"
|
|
864
|
+
'ALTER TABLE "other_db"."public"."t" ADD CONSTRAINT "t_parent_fk" FOREIGN KEY (parent_code) REFERENCES t(code);'
|
|
865
|
+
)
|
|
866
|
+
assert result[0]["definition"] == expected_ddl
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
@pytest.mark.parametrize(
|
|
870
|
+
"column_definition",
|
|
871
|
+
[
|
|
872
|
+
"note text DEFAULT 'head\nALTER TABLE literal text;\ntail'",
|
|
873
|
+
"note text DEFAULT E'head\\'s;\nALTER TABLE literal text\ntail'",
|
|
874
|
+
"note text DEFAULT $$head;\nALTER TABLE literal text\ntail$$",
|
|
875
|
+
"note text DEFAULT $body$head;\nALTER TABLE literal text\ntail$body$",
|
|
876
|
+
'"head\nALTER TABLE column name" integer',
|
|
877
|
+
"id integer /* head;\nALTER TABLE comment text\ntail */",
|
|
878
|
+
],
|
|
879
|
+
)
|
|
880
|
+
@pytest.mark.parametrize("has_deferred_constraint", [False, True])
|
|
881
|
+
def test_partition_table_ddl_preserves_literals_identifiers_and_comments(column_definition, has_deferred_constraint):
|
|
882
|
+
"""Preserve SQL text while separating only actual deferred constraint statements."""
|
|
883
|
+
create = f"CREATE TABLE t (\n {column_definition}\n);"
|
|
884
|
+
alter = 'ALTER TABLE t ADD CONSTRAINT "fk" FOREIGN KEY (id) REFERENCES parent(id);'
|
|
885
|
+
ddl = create + ("\n" + alter if has_deferred_constraint else "")
|
|
886
|
+
|
|
887
|
+
assert PostgreSQLConnector._partition_table_ddl(ddl) == (create, [alter] if has_deferred_constraint else [])
|
|
698
888
|
|
|
699
889
|
|
|
700
890
|
def test_unique_index_definitions_preserve_predicates_and_bind_identifiers():
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Copyright 2025-present DatusAI, Inc.
|
|
2
|
+
# Licensed under the Apache License, Version 2.0.
|
|
3
|
+
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from unittest.mock import MagicMock, patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from datus_postgresql import PostgreSQLConnector
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.mark.parametrize("tables", [["orders"], None, []])
|
|
13
|
+
def test_ddl_metadata_predicate_reaches_database(tables):
|
|
14
|
+
connector = PostgreSQLConnector(
|
|
15
|
+
dict(host="localhost", username="u", password="p", database="db", schema_name="public")
|
|
16
|
+
)
|
|
17
|
+
engine = MagicMock()
|
|
18
|
+
connection = engine.connect.return_value
|
|
19
|
+
connection.exec_driver_sql.return_value.fetchall.return_value = [
|
|
20
|
+
SimpleNamespace(_asdict=lambda: {"table_schema": "public", "table_name": "orders"})
|
|
21
|
+
]
|
|
22
|
+
with (
|
|
23
|
+
patch.object(connector, "_ensure_engine", return_value=engine),
|
|
24
|
+
patch.object(connector, "_get_engine", return_value=engine),
|
|
25
|
+
):
|
|
26
|
+
rows = connector._get_metadata(tables=tables)
|
|
27
|
+
assert [row["table_name"] for row in rows] == ["orders"]
|
|
28
|
+
sql = connection.exec_driver_sql.call_args.args[0]
|
|
29
|
+
assert ("table_name IN ('orders')" in sql) == bool(tables)
|
|
30
|
+
assert "public" in sql
|
|
31
|
+
connection.close.assert_called_once()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_missing_target_does_not_fall_back_to_full_catalog():
|
|
35
|
+
connector = PostgreSQLConnector(
|
|
36
|
+
dict(host="localhost", username="u", password="p", database="db", schema_name="public")
|
|
37
|
+
)
|
|
38
|
+
engine = MagicMock()
|
|
39
|
+
connection = engine.connect.return_value
|
|
40
|
+
|
|
41
|
+
def execute(sql, **kwargs):
|
|
42
|
+
result = MagicMock()
|
|
43
|
+
result.fetchall.return_value = (
|
|
44
|
+
[SimpleNamespace(_asdict=lambda: {"nspname": "public"})] if "pg_namespace" in sql else []
|
|
45
|
+
)
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
connection.exec_driver_sql.side_effect = execute
|
|
49
|
+
with (
|
|
50
|
+
patch.object(connector, "_ensure_engine", return_value=engine),
|
|
51
|
+
patch.object(connector, "_get_engine", return_value=engine),
|
|
52
|
+
):
|
|
53
|
+
rows = connector.get_tables_with_ddl(tables=["missing"])
|
|
54
|
+
assert rows == []
|
|
55
|
+
calls = connection.exec_driver_sql.call_args_list
|
|
56
|
+
assert len(calls) == 2
|
|
57
|
+
assert all("table_name IN ('missing')" in call.args[0] for call in calls if "pg_namespace" not in call.args[0])
|
|
58
|
+
assert not any("lower(" in call.args[0] for call in calls)
|
|
@@ -342,3 +342,35 @@ def test_connector_timeout_wiring_in_base_and_database_engines(overrides, expect
|
|
|
342
342
|
)
|
|
343
343
|
finally:
|
|
344
344
|
connector.close()
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@pytest.mark.parametrize(
|
|
348
|
+
"overrides, dialect, expected",
|
|
349
|
+
[
|
|
350
|
+
({}, "postgresql", True),
|
|
351
|
+
({}, "greenplum", True),
|
|
352
|
+
({"aurora": True, "sslrootcert": "/tmp/ca.pem"}, "postgresql", False),
|
|
353
|
+
({}, "dws", False),
|
|
354
|
+
({}, "gaussdb", False),
|
|
355
|
+
({}, "hologres", False),
|
|
356
|
+
],
|
|
357
|
+
)
|
|
358
|
+
def test_query_timeout_override_capability_and_scope(overrides, dialect, expected):
|
|
359
|
+
from datus_postgresql import PostgreSQLConnector
|
|
360
|
+
|
|
361
|
+
connector = PostgreSQLConnector(
|
|
362
|
+
{"host": "db.test", "username": "reader", "password": "test", "database": "app", **overrides}
|
|
363
|
+
)
|
|
364
|
+
connector.dialect = dialect
|
|
365
|
+
try:
|
|
366
|
+
assert connector.supports_query_timeout_override is expected
|
|
367
|
+
if expected:
|
|
368
|
+
conn = Mock()
|
|
369
|
+
applied = Mock()
|
|
370
|
+
conn.exec_driver_sql.return_value = applied
|
|
371
|
+
with connector._query_timeout_scope(conn, 9):
|
|
372
|
+
pass
|
|
373
|
+
conn.exec_driver_sql.assert_called_once_with("SET LOCAL statement_timeout = 9000")
|
|
374
|
+
applied.close.assert_called_once_with()
|
|
375
|
+
finally:
|
|
376
|
+
connector.close()
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
# Copyright 2025-present DatusAI, Inc.
|
|
2
|
-
# Licensed under the Apache License, Version 2.0.
|
|
3
|
-
|
|
4
|
-
import uuid
|
|
5
|
-
|
|
6
|
-
import pytest
|
|
7
|
-
|
|
8
|
-
from datus_postgresql import PostgreSQLConnector
|
|
9
|
-
|
|
10
|
-
pytestmark = pytest.mark.integration
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def test_ddl_preserves_composite_keys_and_standalone_unique_indexes(config):
|
|
14
|
-
"""Key order comes from constraints; index predicates and expressions must survive."""
|
|
15
|
-
connector = PostgreSQLConnector(config)
|
|
16
|
-
table_name = f"ddl_keys_{uuid.uuid4().hex[:8]}"
|
|
17
|
-
table_ref = f'{connector.quote_identifier(config.schema_name)}."{table_name}"'
|
|
18
|
-
index_prefix = f"{table_name}_index"
|
|
19
|
-
statements = [
|
|
20
|
-
f'CREATE TABLE {table_ref} (id INT, "Tenant ID" INT, email TEXT, active BOOLEAN, '
|
|
21
|
-
'PRIMARY KEY ("Tenant ID", id), CONSTRAINT "Email Key" UNIQUE (email, "Tenant ID"))',
|
|
22
|
-
f"CREATE UNIQUE INDEX {index_prefix}_plain ON {table_ref} (email, id)",
|
|
23
|
-
f"CREATE UNIQUE INDEX {index_prefix}_partial ON {table_ref} (email) WHERE active",
|
|
24
|
-
f"CREATE UNIQUE INDEX {index_prefix}_expression ON {table_ref} (lower(email))",
|
|
25
|
-
f"CREATE INDEX {index_prefix}_ordinary ON {table_ref} (active)",
|
|
26
|
-
]
|
|
27
|
-
try:
|
|
28
|
-
for statement in statements:
|
|
29
|
-
result = connector.execute_ddl(statement)
|
|
30
|
-
assert result.success, result.error
|
|
31
|
-
|
|
32
|
-
tables = connector.get_tables_with_ddl(schema_name=config.schema_name, tables=[table_name])
|
|
33
|
-
|
|
34
|
-
assert [table["table_name"] for table in tables] == [table_name]
|
|
35
|
-
definition = tables[0]["definition"]
|
|
36
|
-
assert f'CONSTRAINT "{table_name}_pkey" PRIMARY KEY ("Tenant ID", id)' in definition
|
|
37
|
-
assert 'CONSTRAINT "Email Key" UNIQUE (email, "Tenant ID")' in definition
|
|
38
|
-
assert definition.count("CREATE UNIQUE INDEX") == 3
|
|
39
|
-
assert f"{index_prefix}_plain" in definition and "USING btree (email, id);" in definition
|
|
40
|
-
assert f"{index_prefix}_partial" in definition and "USING btree (email) WHERE active;" in definition
|
|
41
|
-
assert f"{index_prefix}_expression" in definition and "USING btree (lower(email));" in definition
|
|
42
|
-
assert f"{index_prefix}_ordinary" not in definition
|
|
43
|
-
finally:
|
|
44
|
-
try:
|
|
45
|
-
dropped = connector.execute_ddl(f"DROP TABLE IF EXISTS {table_ref}")
|
|
46
|
-
assert dropped.success, dropped.error
|
|
47
|
-
finally:
|
|
48
|
-
connector.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|