datus-postgresql 0.1.7__tar.gz → 0.1.9__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.7 → datus_postgresql-0.1.9}/.gitignore +8 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/PKG-INFO +4 -4
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/datus_postgresql/connector.py +71 -21
- datus_postgresql-0.1.9/datus_postgresql/tpch_data.py +84 -0
- datus_postgresql-0.1.9/docker-compose.yml +26 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/pyproject.toml +3 -3
- datus_postgresql-0.1.9/scripts/init_tpch_data.py +129 -0
- datus_postgresql-0.1.9/tests/integration/conftest.py +107 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/integration/test_integration.py +44 -20
- datus_postgresql-0.1.9/tests/integration/test_tpch.py +182 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/unit/test_connector_unit.py +107 -0
- datus_postgresql-0.1.7/docker-compose.yml +0 -20
- datus_postgresql-0.1.7/scripts/init_tpch_data.py +0 -555
- datus_postgresql-0.1.7/tests/integration/conftest.py +0 -536
- datus_postgresql-0.1.7/tests/integration/test_tpch.py +0 -162
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/README.md +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/datus_postgresql/__init__.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/datus_postgresql/config.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/datus_postgresql/handlers.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/__init__.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/conftest.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/integration/__init__.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/integration/test_contract.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/unit/__init__.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/tests/unit/test_config.py +0 -0
- {datus_postgresql-0.1.7 → datus_postgresql-0.1.9}/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.9
|
|
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,8 +14,8 @@ 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.7
|
|
18
|
+
Requires-Dist: datus-sqlalchemy>=0.1.8
|
|
19
19
|
Requires-Dist: psycopg2-binary>=2.9.11
|
|
20
20
|
Requires-Dist: pydantic>=2.0.0
|
|
21
21
|
Description-Content-Type: text/markdown
|
|
@@ -144,7 +144,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
144
144
|
Args:
|
|
145
145
|
table_type: Type of object (table, view, mv)
|
|
146
146
|
catalog_name: Catalog name (unused in PostgreSQL)
|
|
147
|
-
database_name: Database
|
|
147
|
+
database_name: Database in which to inspect the objects
|
|
148
148
|
schema_name: Schema name to query
|
|
149
149
|
|
|
150
150
|
Returns:
|
|
@@ -211,7 +211,11 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
211
211
|
tb_name = query_result["table_name"][i]
|
|
212
212
|
result.append(
|
|
213
213
|
{
|
|
214
|
-
"identifier": self.identifier(
|
|
214
|
+
"identifier": self.identifier(
|
|
215
|
+
database_name=database_name,
|
|
216
|
+
schema_name=schema,
|
|
217
|
+
table_name=tb_name,
|
|
218
|
+
),
|
|
215
219
|
"catalog_name": "",
|
|
216
220
|
"database_name": database_name,
|
|
217
221
|
"schema_name": schema,
|
|
@@ -221,7 +225,13 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
221
225
|
)
|
|
222
226
|
return result
|
|
223
227
|
|
|
224
|
-
def _get_ddl(
|
|
228
|
+
def _get_ddl(
|
|
229
|
+
self,
|
|
230
|
+
schema_name: str,
|
|
231
|
+
table_name: str,
|
|
232
|
+
object_type: str = "TABLE",
|
|
233
|
+
database_name: str = "",
|
|
234
|
+
) -> str:
|
|
225
235
|
"""
|
|
226
236
|
Get DDL for a table/view using pg_get_tabledef or reconstructing from metadata.
|
|
227
237
|
|
|
@@ -229,11 +239,17 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
229
239
|
schema_name: Schema name
|
|
230
240
|
table_name: Table name
|
|
231
241
|
object_type: Object type (TABLE, VIEW, MATERIALIZED VIEW)
|
|
242
|
+
database_name: Database in which to inspect the object
|
|
232
243
|
|
|
233
244
|
Returns:
|
|
234
245
|
DDL statement as string
|
|
235
246
|
"""
|
|
236
|
-
|
|
247
|
+
database_name = database_name or self.database_name
|
|
248
|
+
full_name = self.full_name(
|
|
249
|
+
database_name=database_name,
|
|
250
|
+
schema_name=schema_name,
|
|
251
|
+
table_name=table_name,
|
|
252
|
+
)
|
|
237
253
|
|
|
238
254
|
safe_schema = schema_name.replace("'", "''") if schema_name else ""
|
|
239
255
|
safe_table = table_name.replace("'", "''") if table_name else ""
|
|
@@ -243,7 +259,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
243
259
|
sql = f"""
|
|
244
260
|
SELECT pg_get_viewdef('{safe_schema}.{safe_table}'::regclass, true) as definition
|
|
245
261
|
"""
|
|
246
|
-
result = self._execute_pandas(sql)
|
|
262
|
+
result = self._execute_pandas(sql, database_name=database_name)
|
|
247
263
|
if not result.empty and result["definition"][0]:
|
|
248
264
|
return f"CREATE VIEW {full_name} AS\n{result['definition'][0]}"
|
|
249
265
|
return f"-- DDL not available for {full_name}"
|
|
@@ -255,14 +271,18 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
255
271
|
FROM pg_matviews
|
|
256
272
|
WHERE schemaname = '{safe_schema}' AND matviewname = '{safe_table}'
|
|
257
273
|
"""
|
|
258
|
-
result = self._execute_pandas(sql)
|
|
274
|
+
result = self._execute_pandas(sql, database_name=database_name)
|
|
259
275
|
if not result.empty and result["definition"][0]:
|
|
260
276
|
return f"CREATE MATERIALIZED VIEW {full_name} AS\n{result['definition'][0]}"
|
|
261
277
|
return f"-- DDL not available for {full_name}"
|
|
262
278
|
|
|
263
279
|
else:
|
|
264
280
|
# For tables, reconstruct DDL from column info
|
|
265
|
-
columns = self.get_schema(
|
|
281
|
+
columns = self.get_schema(
|
|
282
|
+
database_name=database_name,
|
|
283
|
+
schema_name=schema_name,
|
|
284
|
+
table_name=table_name,
|
|
285
|
+
)
|
|
266
286
|
if not columns:
|
|
267
287
|
return f"-- DDL not available for {full_name}"
|
|
268
288
|
|
|
@@ -301,7 +321,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
301
321
|
table_type: Type of object
|
|
302
322
|
tables: Optional list of specific tables to retrieve
|
|
303
323
|
catalog_name: Catalog name (unused)
|
|
304
|
-
database_name: Database name
|
|
324
|
+
database_name: Database name
|
|
305
325
|
schema_name: Schema name
|
|
306
326
|
|
|
307
327
|
Returns:
|
|
@@ -318,7 +338,12 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
318
338
|
object_type = object_type_map.get(table_type, "TABLE")
|
|
319
339
|
|
|
320
340
|
for meta in self._get_metadata(table_type, catalog_name, database_name, schema_name):
|
|
321
|
-
|
|
341
|
+
metadata_database = meta["database_name"]
|
|
342
|
+
full_name = self.full_name(
|
|
343
|
+
database_name=metadata_database,
|
|
344
|
+
schema_name=meta["schema_name"],
|
|
345
|
+
table_name=meta["table_name"],
|
|
346
|
+
)
|
|
322
347
|
|
|
323
348
|
# Skip if not in filter list
|
|
324
349
|
if filter_tables and full_name not in filter_tables:
|
|
@@ -326,7 +351,19 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
326
351
|
|
|
327
352
|
# Get DDL
|
|
328
353
|
try:
|
|
329
|
-
|
|
354
|
+
# Keep the legacy three-argument _get_ddl dispatch compatible
|
|
355
|
+
# with independently released PostgreSQL subclasses. The
|
|
356
|
+
# ContextVar is task-local and makes the target database visible
|
|
357
|
+
# to both the base implementation and subclass metadata queries.
|
|
358
|
+
token = self._database_var.set(metadata_database)
|
|
359
|
+
try:
|
|
360
|
+
ddl = self._get_ddl(
|
|
361
|
+
meta["schema_name"],
|
|
362
|
+
meta["table_name"],
|
|
363
|
+
object_type,
|
|
364
|
+
)
|
|
365
|
+
finally:
|
|
366
|
+
self._database_var.reset(token)
|
|
330
367
|
except Exception as e:
|
|
331
368
|
logger.warning(f"Could not get DDL for {full_name}: {e}")
|
|
332
369
|
ddl = f"-- DDL not available for {meta['table_name']}"
|
|
@@ -408,7 +445,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
408
445
|
|
|
409
446
|
Args:
|
|
410
447
|
catalog_name: Catalog name (unused)
|
|
411
|
-
database_name: Database name
|
|
448
|
+
database_name: Database name
|
|
412
449
|
schema_name: Schema name
|
|
413
450
|
table_name: Table name
|
|
414
451
|
|
|
@@ -469,9 +506,9 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
469
506
|
ORDER BY c.table_schema, c.table_name, c.ordinal_position
|
|
470
507
|
"""
|
|
471
508
|
|
|
472
|
-
query_result = self._execute_pandas(_build_sql(False))
|
|
509
|
+
query_result = self._execute_pandas(_build_sql(False), database_name=database_name)
|
|
473
510
|
if len(query_result) == 0:
|
|
474
|
-
query_result = self._execute_pandas(_build_sql(True))
|
|
511
|
+
query_result = self._execute_pandas(_build_sql(True), database_name=database_name)
|
|
475
512
|
self._raise_if_ambiguous_table(query_result, schema_name, table_name)
|
|
476
513
|
|
|
477
514
|
result = []
|
|
@@ -543,7 +580,7 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
543
580
|
database_name = database_name or self.database_name
|
|
544
581
|
safe_db = database_name.replace("'", "''") if database_name else ""
|
|
545
582
|
sql = f"SELECT schema_name FROM information_schema.schemata WHERE catalog_name = '{safe_db}'"
|
|
546
|
-
result = self._execute_pandas(sql)
|
|
583
|
+
result = self._execute_pandas(sql, database_name=database_name)
|
|
547
584
|
schemas = result["schema_name"].tolist()
|
|
548
585
|
|
|
549
586
|
if not include_sys:
|
|
@@ -672,15 +709,23 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
672
709
|
# If specific tables provided, query those
|
|
673
710
|
if tables:
|
|
674
711
|
for table_name in tables:
|
|
675
|
-
full_name = self.full_name(
|
|
712
|
+
full_name = self.full_name(
|
|
713
|
+
database_name=database_name,
|
|
714
|
+
schema_name=schema_name,
|
|
715
|
+
table_name=table_name,
|
|
716
|
+
)
|
|
676
717
|
sql = f"SELECT * FROM {full_name} LIMIT {top_n}"
|
|
677
|
-
df = self._execute_pandas(sql)
|
|
718
|
+
df = self._execute_pandas(sql, database_name=database_name)
|
|
678
719
|
if not df.empty:
|
|
679
720
|
result.append(
|
|
680
721
|
{
|
|
681
|
-
"identifier": self.identifier(
|
|
722
|
+
"identifier": self.identifier(
|
|
723
|
+
database_name=database_name,
|
|
724
|
+
schema_name=schema_name,
|
|
725
|
+
table_name=table_name,
|
|
726
|
+
),
|
|
682
727
|
"catalog_name": "",
|
|
683
|
-
"database_name": self.database_name,
|
|
728
|
+
"database_name": database_name or self.database_name,
|
|
684
729
|
"schema_name": schema_name,
|
|
685
730
|
"table_name": table_name,
|
|
686
731
|
"sample_rows": df.to_csv(index=False),
|
|
@@ -691,15 +736,20 @@ class PostgreSQLConnector(SQLAlchemyConnector, MigrationTargetMixin):
|
|
|
691
736
|
# Otherwise get metadata and query all tables
|
|
692
737
|
metadata = self._get_metadata(table_type, "", database_name, schema_name)
|
|
693
738
|
for meta in metadata:
|
|
694
|
-
|
|
739
|
+
metadata_database = meta["database_name"]
|
|
740
|
+
full_name = self.full_name(
|
|
741
|
+
database_name=metadata_database,
|
|
742
|
+
schema_name=meta["schema_name"],
|
|
743
|
+
table_name=meta["table_name"],
|
|
744
|
+
)
|
|
695
745
|
sql = f"SELECT * FROM {full_name} LIMIT {top_n}"
|
|
696
|
-
df = self._execute_pandas(sql)
|
|
746
|
+
df = self._execute_pandas(sql, database_name=metadata_database)
|
|
697
747
|
if not df.empty:
|
|
698
748
|
result.append(
|
|
699
749
|
{
|
|
700
750
|
"identifier": meta["identifier"],
|
|
701
751
|
"catalog_name": "",
|
|
702
|
-
"database_name":
|
|
752
|
+
"database_name": metadata_database,
|
|
703
753
|
"schema_name": meta["schema_name"],
|
|
704
754
|
"table_name": meta["table_name"],
|
|
705
755
|
"sample_rows": df.to_csv(index=False),
|
|
@@ -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,26 @@
|
|
|
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
|
+
# A real query, not pg_isready: pg_isready reports "accepting
|
|
15
|
+
# connections" without authenticating, so a data volume left over from
|
|
16
|
+
# different credentials would come up healthy and fail only at test time.
|
|
17
|
+
test: ["CMD-SHELL", "psql -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\" -c 'SELECT 1' >/dev/null 2>&1"]
|
|
18
|
+
interval: 10s
|
|
19
|
+
timeout: 5s
|
|
20
|
+
retries: 5
|
|
21
|
+
start_period: 30s
|
|
22
|
+
volumes:
|
|
23
|
+
- postgres_data:/var/lib/postgresql/data
|
|
24
|
+
|
|
25
|
+
volumes:
|
|
26
|
+
postgres_data:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "datus-postgresql"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.9"
|
|
4
4
|
description = "PostgreSQL database adapter for Datus"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -18,8 +18,8 @@ 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.7",
|
|
22
|
+
"datus-sqlalchemy>=0.1.8",
|
|
23
23
|
"psycopg2-binary>=2.9.11",
|
|
24
24
|
"pydantic>=2.0.0",
|
|
25
25
|
]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright 2025-present DatusAI, Inc.
|
|
3
|
+
# Licensed under the Apache License, Version 2.0.
|
|
4
|
+
# See http://www.apache.org/licenses/LICENSE-2.0 for details.
|
|
5
|
+
|
|
6
|
+
"""Initialize TPC-H sample data in PostgreSQL for Datus integration testing.
|
|
7
|
+
|
|
8
|
+
Creates the five TPC-H tables (region, nation, customer, orders, supplier) and
|
|
9
|
+
populates them with the shared dataset used by the integration suite. The DDL
|
|
10
|
+
and rows come from ``datus_postgresql.tpch_data`` — this script never holds a
|
|
11
|
+
second copy.
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
python scripts/init_tpch_data.py \\
|
|
15
|
+
--host localhost --port 5432 \\
|
|
16
|
+
--username test_user --password test_password \\
|
|
17
|
+
--database test --schema public
|
|
18
|
+
|
|
19
|
+
# Drop existing tables first, then recreate
|
|
20
|
+
python scripts/init_tpch_data.py --drop
|
|
21
|
+
|
|
22
|
+
Environment variables (used as defaults):
|
|
23
|
+
POSTGRESQL_HOST, POSTGRESQL_PORT, POSTGRESQL_USER, POSTGRESQL_PASSWORD,
|
|
24
|
+
POSTGRESQL_DATABASE, POSTGRESQL_SCHEMA
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import sys
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def main():
|
|
34
|
+
parser = argparse.ArgumentParser(description="Initialize TPC-H data in PostgreSQL")
|
|
35
|
+
parser.add_argument("--host", default=os.getenv("POSTGRESQL_HOST", "localhost"))
|
|
36
|
+
parser.add_argument("--port", type=int, default=int(os.getenv("POSTGRESQL_PORT", "5432")))
|
|
37
|
+
parser.add_argument("--username", default=os.getenv("POSTGRESQL_USER", "test_user"))
|
|
38
|
+
parser.add_argument("--password", default=os.getenv("POSTGRESQL_PASSWORD", "test_password"))
|
|
39
|
+
parser.add_argument("--database", default=os.getenv("POSTGRESQL_DATABASE", "test"))
|
|
40
|
+
parser.add_argument("--schema", default=os.getenv("POSTGRESQL_SCHEMA", "public"))
|
|
41
|
+
parser.add_argument("--drop", action="store_true", help="Drop existing tables before creating")
|
|
42
|
+
args = parser.parse_args()
|
|
43
|
+
|
|
44
|
+
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.schema):
|
|
45
|
+
print("ERROR: --schema must be a valid SQL identifier (letters, digits, underscores).")
|
|
46
|
+
sys.exit(1)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
from datus_postgresql import PostgreSQLConfig, PostgreSQLConnector
|
|
50
|
+
from datus_postgresql.tpch_data import ROW_COUNTS, TPCH_DATA, TPCH_DDL, TPCH_TABLES
|
|
51
|
+
except ImportError:
|
|
52
|
+
print("ERROR: datus-postgresql is not installed.")
|
|
53
|
+
print(" pip install -e ../datus-postgresql")
|
|
54
|
+
sys.exit(1)
|
|
55
|
+
|
|
56
|
+
config = PostgreSQLConfig(
|
|
57
|
+
host=args.host,
|
|
58
|
+
port=args.port,
|
|
59
|
+
username=args.username,
|
|
60
|
+
password=args.password,
|
|
61
|
+
database=args.database,
|
|
62
|
+
schema_name=args.schema,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
conn = None
|
|
66
|
+
schema = args.schema
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
conn = PostgreSQLConnector(config)
|
|
70
|
+
if not conn.test_connection():
|
|
71
|
+
print("ERROR: Connection test failed.")
|
|
72
|
+
sys.exit(1)
|
|
73
|
+
print(f"Connected to PostgreSQL at {args.host}:{args.port}/{args.database}")
|
|
74
|
+
|
|
75
|
+
# Statements are unqualified; the connector applies `SET search_path`
|
|
76
|
+
# from schema_name to every statement.
|
|
77
|
+
if args.drop:
|
|
78
|
+
print("\nDropping existing TPC-H tables...")
|
|
79
|
+
for table in reversed(TPCH_TABLES):
|
|
80
|
+
conn.execute_ddl(f'DROP TABLE IF EXISTS "{schema}"."{table}" CASCADE')
|
|
81
|
+
print(f" Dropped {table}")
|
|
82
|
+
|
|
83
|
+
print("\nCreating TPC-H tables...")
|
|
84
|
+
for i, ddl in enumerate(TPCH_DDL):
|
|
85
|
+
result = conn.execute_ddl(ddl)
|
|
86
|
+
if not result.success:
|
|
87
|
+
print(f" Error creating {TPCH_TABLES[i]}: {result.error}")
|
|
88
|
+
sys.exit(1)
|
|
89
|
+
print(f" Created {TPCH_TABLES[i]}")
|
|
90
|
+
|
|
91
|
+
# ON CONFLICT DO NOTHING keeps a re-run without --drop idempotent.
|
|
92
|
+
print("\nInserting TPC-H data...")
|
|
93
|
+
for i, insert_sql in enumerate(TPCH_DATA):
|
|
94
|
+
result = conn.execute_insert(f"{insert_sql.rstrip()} ON CONFLICT DO NOTHING")
|
|
95
|
+
if not result.success:
|
|
96
|
+
print(f" Error inserting into {TPCH_TABLES[i]}: {result.error}")
|
|
97
|
+
sys.exit(1)
|
|
98
|
+
print(f" Inserted {ROW_COUNTS[i]} rows into {TPCH_TABLES[i]}")
|
|
99
|
+
|
|
100
|
+
print("\nVerification:")
|
|
101
|
+
has_mismatch = False
|
|
102
|
+
for i, table in enumerate(TPCH_TABLES):
|
|
103
|
+
result = conn.execute(
|
|
104
|
+
{"sql_query": f'SELECT COUNT(*) AS cnt FROM "{schema}"."{table}"'},
|
|
105
|
+
result_format="list",
|
|
106
|
+
)
|
|
107
|
+
count = result.sql_return[0]["cnt"]
|
|
108
|
+
expected = ROW_COUNTS[i]
|
|
109
|
+
status = "OK" if count == expected else "MISMATCH"
|
|
110
|
+
if count != expected:
|
|
111
|
+
has_mismatch = True
|
|
112
|
+
print(f" {table}: {count} rows [{status}]")
|
|
113
|
+
|
|
114
|
+
if has_mismatch:
|
|
115
|
+
print("\nVerification failed. Re-run with --drop for a clean re-init.")
|
|
116
|
+
sys.exit(2)
|
|
117
|
+
|
|
118
|
+
print("\nTPC-H data initialization complete!")
|
|
119
|
+
|
|
120
|
+
finally:
|
|
121
|
+
if conn is not None:
|
|
122
|
+
try:
|
|
123
|
+
conn.close()
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
main()
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
import os
|
|
6
|
+
from typing import Generator
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from datus_postgresql import PostgreSQLConfig, PostgreSQLConnector
|
|
11
|
+
from datus_postgresql.tpch_data import ROW_COUNTS, TPCH_DATA, TPCH_DDL, TPCH_TABLES
|
|
12
|
+
|
|
13
|
+
__all__ = ["ROW_COUNTS", "TPCH_DATA", "TPCH_DDL", "TPCH_TABLES"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
# Fixtures
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def config() -> PostgreSQLConfig:
|
|
23
|
+
"""Create PostgreSQL configuration for integration tests from environment or defaults."""
|
|
24
|
+
return PostgreSQLConfig(
|
|
25
|
+
host=os.getenv("POSTGRESQL_HOST", "localhost"),
|
|
26
|
+
port=int(os.getenv("POSTGRESQL_PORT", "5432")),
|
|
27
|
+
username=os.getenv("POSTGRESQL_USER", "test_user"),
|
|
28
|
+
password=os.getenv("POSTGRESQL_PASSWORD", "test_password"),
|
|
29
|
+
database=os.getenv("POSTGRESQL_DATABASE", "test"),
|
|
30
|
+
schema_name=os.getenv("POSTGRESQL_SCHEMA", "public"),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.fixture
|
|
35
|
+
def connector(config: PostgreSQLConfig) -> Generator[PostgreSQLConnector, None, None]:
|
|
36
|
+
"""Create and cleanup PostgreSQL connector for integration tests."""
|
|
37
|
+
conn = None
|
|
38
|
+
try:
|
|
39
|
+
conn = PostgreSQLConnector(config)
|
|
40
|
+
if not conn.test_connection():
|
|
41
|
+
pytest.skip("Database connection test failed")
|
|
42
|
+
yield conn
|
|
43
|
+
except Exception as e:
|
|
44
|
+
pytest.skip(f"Database not available: {e}")
|
|
45
|
+
finally:
|
|
46
|
+
if conn is not None:
|
|
47
|
+
try:
|
|
48
|
+
conn.close()
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.fixture(scope="session")
|
|
54
|
+
def tpch_setup():
|
|
55
|
+
"""Set up TPC-H tables and data for integration tests (session-scoped).
|
|
56
|
+
|
|
57
|
+
Creates tables, inserts sample data, yields for tests, then drops tables.
|
|
58
|
+
Skips all tests if the database is not available.
|
|
59
|
+
"""
|
|
60
|
+
cfg = PostgreSQLConfig(
|
|
61
|
+
host=os.getenv("POSTGRESQL_HOST", "localhost"),
|
|
62
|
+
port=int(os.getenv("POSTGRESQL_PORT", "5432")),
|
|
63
|
+
username=os.getenv("POSTGRESQL_USER", "test_user"),
|
|
64
|
+
password=os.getenv("POSTGRESQL_PASSWORD", "test_password"),
|
|
65
|
+
database=os.getenv("POSTGRESQL_DATABASE", "test"),
|
|
66
|
+
schema_name=os.getenv("POSTGRESQL_SCHEMA", "public"),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
conn = None
|
|
70
|
+
try:
|
|
71
|
+
conn = PostgreSQLConnector(cfg)
|
|
72
|
+
if not conn.test_connection():
|
|
73
|
+
pytest.skip("Database connection test failed")
|
|
74
|
+
except Exception as e:
|
|
75
|
+
pytest.skip(f"Database not available: {e}")
|
|
76
|
+
|
|
77
|
+
schema = cfg.schema_name
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
# Statements are unqualified; the connector applies `SET search_path`
|
|
81
|
+
# from cfg.schema_name to every statement.
|
|
82
|
+
for table in TPCH_TABLES:
|
|
83
|
+
conn.execute_ddl(f'DROP TABLE IF EXISTS "{schema}"."{table}" CASCADE')
|
|
84
|
+
|
|
85
|
+
for i, ddl in enumerate(TPCH_DDL):
|
|
86
|
+
result = conn.execute_ddl(ddl)
|
|
87
|
+
if not result.success:
|
|
88
|
+
pytest.fail(f"Failed to create {TPCH_TABLES[i]}: {result.error}")
|
|
89
|
+
|
|
90
|
+
for i, insert_sql in enumerate(TPCH_DATA):
|
|
91
|
+
result = conn.execute_insert(insert_sql)
|
|
92
|
+
if not result.success:
|
|
93
|
+
pytest.fail(f"Failed to load {TPCH_TABLES[i]}: {result.error}")
|
|
94
|
+
|
|
95
|
+
yield conn
|
|
96
|
+
|
|
97
|
+
finally:
|
|
98
|
+
# Cleanup: drop tables in reverse order (foreign key safety)
|
|
99
|
+
for table in reversed(TPCH_TABLES):
|
|
100
|
+
try:
|
|
101
|
+
conn.execute_ddl(f'DROP TABLE IF EXISTS "{schema}"."{table}" CASCADE')
|
|
102
|
+
except Exception:
|
|
103
|
+
pass
|
|
104
|
+
try:
|
|
105
|
+
conn.close()
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|