platybus-postgres 0.1.1__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.
- platybus_postgres-0.1.1/.gitignore +46 -0
- platybus_postgres-0.1.1/LICENSE +21 -0
- platybus_postgres-0.1.1/PKG-INFO +41 -0
- platybus_postgres-0.1.1/README.md +16 -0
- platybus_postgres-0.1.1/pyproject.toml +43 -0
- platybus_postgres-0.1.1/src/platybus_postgres/__init__.py +86 -0
- platybus_postgres-0.1.1/src/platybus_postgres/connector.py +145 -0
- platybus_postgres-0.1.1/src/platybus_postgres/py.typed +0 -0
- platybus_postgres-0.1.1/src/platybus_postgres/store.py +231 -0
- platybus_postgres-0.1.1/src/platybus_postgres/types.py +68 -0
- platybus_postgres-0.1.1/tests/test_postgres_store.py +234 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
.venv/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
*.egg-info/
|
|
8
|
+
.pytest_cache/
|
|
9
|
+
.mypy_cache/
|
|
10
|
+
.ruff_cache/
|
|
11
|
+
.coverage
|
|
12
|
+
htmlcov/
|
|
13
|
+
|
|
14
|
+
# Node
|
|
15
|
+
web/node_modules/
|
|
16
|
+
web/dist/
|
|
17
|
+
src/platybus/server/static/
|
|
18
|
+
web/*.tsbuildinfo
|
|
19
|
+
# Playwright artifacts
|
|
20
|
+
web/playwright-report/
|
|
21
|
+
web/test-results/
|
|
22
|
+
web/blob-report/
|
|
23
|
+
web/playwright/.cache/
|
|
24
|
+
|
|
25
|
+
# Platybus local state and demos
|
|
26
|
+
.platybus/
|
|
27
|
+
.tmp/
|
|
28
|
+
*.duckdb
|
|
29
|
+
*.duckdb.wal
|
|
30
|
+
|
|
31
|
+
# Secrets
|
|
32
|
+
.env
|
|
33
|
+
.env.*
|
|
34
|
+
!.env.example
|
|
35
|
+
|
|
36
|
+
# Editors / OS
|
|
37
|
+
.idea/
|
|
38
|
+
.vscode/
|
|
39
|
+
.DS_Store
|
|
40
|
+
Thumbs.db
|
|
41
|
+
|
|
42
|
+
# Claude Code local settings
|
|
43
|
+
.claude/settings.local.json
|
|
44
|
+
.claude
|
|
45
|
+
# MkDocs output
|
|
46
|
+
site/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yaroslav Ozerov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: platybus-postgres
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Platybus plugin: PostgreSQL connector (DuckDB postgres extension).
|
|
5
|
+
Project-URL: Homepage, https://github.com/RobbyTheFish/platybus
|
|
6
|
+
Project-URL: Documentation, https://robbythefish.github.io/platybus/
|
|
7
|
+
Project-URL: Repository, https://github.com/RobbyTheFish/platybus
|
|
8
|
+
Project-URL: Issues, https://github.com/RobbyTheFish/platybus/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Yaroslav Ozerov
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: duckdb,platybus,platybus-plugin,postgres,postgresql,warehouse
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: platybus>=0.1.1
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# platybus-postgres
|
|
27
|
+
|
|
28
|
+
PostgreSQL connector and warehouse store (DuckDB postgres extension).
|
|
29
|
+
|
|
30
|
+
A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
|
|
31
|
+
a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
|
|
32
|
+
ETL, dbt and dashboards.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install platybus platybus-postgres
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
|
|
39
|
+
is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/stores/postgres/>).
|
|
40
|
+
|
|
41
|
+
License: MIT.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# platybus-postgres
|
|
2
|
+
|
|
3
|
+
PostgreSQL connector and warehouse store (DuckDB postgres extension).
|
|
4
|
+
|
|
5
|
+
A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
|
|
6
|
+
a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
|
|
7
|
+
ETL, dbt and dashboards.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install platybus platybus-postgres
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
|
|
14
|
+
is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/stores/postgres/>).
|
|
15
|
+
|
|
16
|
+
License: MIT.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "platybus-postgres"
|
|
3
|
+
version = "0.1.1" # x-release-please-version
|
|
4
|
+
description = "Platybus plugin: PostgreSQL connector (DuckDB postgres extension)."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Yaroslav Ozerov" }]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
keywords = ["platybus", "platybus-plugin", "duckdb", "postgres", "postgresql", "warehouse"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Topic :: Database",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"platybus>=0.1.1", # x-release-please-version
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/RobbyTheFish/platybus"
|
|
27
|
+
Documentation = "https://robbythefish.github.io/platybus/"
|
|
28
|
+
Repository = "https://github.com/RobbyTheFish/platybus"
|
|
29
|
+
Issues = "https://github.com/RobbyTheFish/platybus/issues"
|
|
30
|
+
Changelog = "https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md"
|
|
31
|
+
|
|
32
|
+
[project.entry-points."platybus.plugins"]
|
|
33
|
+
postgres = "platybus_postgres:plugin"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling>=1.26"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/platybus_postgres"]
|
|
41
|
+
|
|
42
|
+
[tool.uv.sources]
|
|
43
|
+
platybus = { workspace = true }
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Platybus plugin: PostgreSQL as a source (connector) and as a warehouse (store)."""
|
|
2
|
+
|
|
3
|
+
from platybus.plugins import ConnectorSpec, FormField, Plugin
|
|
4
|
+
from platybus.sandbox.base import SANDBOX_PASSWORD, SANDBOX_USER
|
|
5
|
+
from platybus.sandbox.builtin import POSTGRES_PORT, POSTGRES_PROJECT_DB, POSTGRES_SOURCE_DB
|
|
6
|
+
from platybus.stores import SandboxPreset, StoreSpec
|
|
7
|
+
from platybus_postgres.connector import PostgresConnector
|
|
8
|
+
from platybus_postgres.store import PostgresSettings, PostgresStore, postgres_store
|
|
9
|
+
|
|
10
|
+
SANDBOX_HOST = "127.0.0.1"
|
|
11
|
+
|
|
12
|
+
plugin = Plugin(
|
|
13
|
+
name="postgres",
|
|
14
|
+
kind="connector",
|
|
15
|
+
title="PostgreSQL",
|
|
16
|
+
description="PostgreSQL through the DuckDB postgres extension: a read-only source "
|
|
17
|
+
"(connector, with pushdown) and a read-write warehouse (store).",
|
|
18
|
+
connectors=(
|
|
19
|
+
ConnectorSpec(
|
|
20
|
+
cls=PostgresConnector,
|
|
21
|
+
key="postgres",
|
|
22
|
+
title="PostgreSQL",
|
|
23
|
+
description="Tables are queried as <connection>.<schema>.<table>.",
|
|
24
|
+
fields=(
|
|
25
|
+
FormField("host", "Host", "host", required=True, placeholder="db.example.com"),
|
|
26
|
+
FormField("port", "Port", "port", kind="number", default="5432"),
|
|
27
|
+
FormField("database", "Database", "path", required=True),
|
|
28
|
+
FormField("username", "User", "username"),
|
|
29
|
+
FormField("password", "Password", "password", kind="password", secret=True),
|
|
30
|
+
FormField(
|
|
31
|
+
"sslmode",
|
|
32
|
+
"SSL mode",
|
|
33
|
+
"query:sslmode",
|
|
34
|
+
kind="select",
|
|
35
|
+
options=("disable", "allow", "prefer", "require", "verify-ca", "verify-full"),
|
|
36
|
+
),
|
|
37
|
+
FormField(
|
|
38
|
+
"schema",
|
|
39
|
+
"Default schema",
|
|
40
|
+
"query:schema",
|
|
41
|
+
placeholder="public",
|
|
42
|
+
help="Schema used for unqualified table names in extracts.",
|
|
43
|
+
),
|
|
44
|
+
),
|
|
45
|
+
sandbox=SandboxPreset(
|
|
46
|
+
services=("postgres",),
|
|
47
|
+
settings={
|
|
48
|
+
"host": SANDBOX_HOST,
|
|
49
|
+
"port": str(POSTGRES_PORT),
|
|
50
|
+
"database": POSTGRES_SOURCE_DB,
|
|
51
|
+
"username": SANDBOX_USER,
|
|
52
|
+
"password": SANDBOX_PASSWORD,
|
|
53
|
+
},
|
|
54
|
+
),
|
|
55
|
+
),
|
|
56
|
+
),
|
|
57
|
+
stores=(
|
|
58
|
+
StoreSpec(
|
|
59
|
+
key="postgres",
|
|
60
|
+
title="PostgreSQL",
|
|
61
|
+
category="warehouse",
|
|
62
|
+
factory=postgres_store,
|
|
63
|
+
description="Tables in a PostgreSQL database, written by DuckDB: any Postgres "
|
|
64
|
+
"client can read them. No views through DuckDB (view models become tables), "
|
|
65
|
+
"no snapshots.",
|
|
66
|
+
settings_model=PostgresSettings,
|
|
67
|
+
capabilities=PostgresStore.capabilities,
|
|
68
|
+
# Both transform engines are verified on this store (integration tests).
|
|
69
|
+
transforms=("sql", "dbt"),
|
|
70
|
+
# One database per project (wh_<project>), created on first attach.
|
|
71
|
+
sandbox=SandboxPreset(
|
|
72
|
+
services=("postgres",),
|
|
73
|
+
settings={
|
|
74
|
+
"host": SANDBOX_HOST,
|
|
75
|
+
"port": POSTGRES_PORT,
|
|
76
|
+
"database": POSTGRES_PROJECT_DB,
|
|
77
|
+
"user": SANDBOX_USER,
|
|
78
|
+
"password": SANDBOX_PASSWORD,
|
|
79
|
+
"create_database": True,
|
|
80
|
+
},
|
|
81
|
+
),
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
__all__ = ["PostgresConnector", "PostgresSettings", "PostgresStore", "plugin"]
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""PostgreSQL connector (strategy *attach*, DuckDB ``postgres`` extension).
|
|
2
|
+
|
|
3
|
+
URL::
|
|
4
|
+
|
|
5
|
+
postgres://user:${PG_PASSWORD}@host:5432/dbname?sslmode=require&schema=public
|
|
6
|
+
|
|
7
|
+
Credentials go into a DuckDB secret (never into the ATTACH path, which is visible in
|
|
8
|
+
``duckdb_databases()``); other query parameters are libpq options.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import ClassVar
|
|
15
|
+
|
|
16
|
+
import duckdb
|
|
17
|
+
|
|
18
|
+
from platybus.connectors.base import ParsedUrl, ReadRequest
|
|
19
|
+
from platybus.connectors.common import Dialect, wrap_with_filter
|
|
20
|
+
from platybus.connectors.database import DatabaseConnector, secret_name
|
|
21
|
+
from platybus.errors import ConfigError
|
|
22
|
+
from platybus.sqlutil import quote_ident, quote_literal
|
|
23
|
+
|
|
24
|
+
#: libpq keywords accepted as URL query parameters.
|
|
25
|
+
LIBPQ_OPTIONS = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"sslmode",
|
|
28
|
+
"sslrootcert",
|
|
29
|
+
"sslcert",
|
|
30
|
+
"sslkey",
|
|
31
|
+
"sslcrl",
|
|
32
|
+
"connect_timeout",
|
|
33
|
+
"application_name",
|
|
34
|
+
"options",
|
|
35
|
+
"target_session_attrs",
|
|
36
|
+
"keepalives",
|
|
37
|
+
"keepalives_idle",
|
|
38
|
+
"gssencmode",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
#: Options consumed by Platybus/DuckDB itself.
|
|
42
|
+
PLATYBUS_OPTIONS = frozenset({"schema"})
|
|
43
|
+
DEFAULT_CONNECT_TIMEOUT = "10"
|
|
44
|
+
DEFAULT_PORT = 5432
|
|
45
|
+
|
|
46
|
+
#: DuckDB's connect error quotes the ATTACH path, i.e. only the libpq options (host,
|
|
47
|
+
#: port and database come from the secret): ``Unable to connect to Postgres at
|
|
48
|
+
#: "connect_timeout=10": ...``.
|
|
49
|
+
_UNABLE = re.compile(r'(Unable to connect to Postgres at )".*?"(?=:\s|$)', re.DOTALL)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pg_target(host: str | None, port: int | str | None, database: str) -> str:
|
|
53
|
+
"""``host:port/database`` of a server, for messages (never credentials)."""
|
|
54
|
+
name = host or "localhost"
|
|
55
|
+
if ":" in name:
|
|
56
|
+
name = f"[{name}]"
|
|
57
|
+
return f"{name}:{port or DEFAULT_PORT}/{database}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def explain_error(message: str, target: str) -> str:
|
|
61
|
+
"""A driver error that names the server (``host:port/database``) it failed on."""
|
|
62
|
+
explained, count = _UNABLE.subn(lambda m: m.group(1) + target, message, count=1)
|
|
63
|
+
return explained if count else message
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def libpq_value(value: str) -> str:
|
|
67
|
+
"""Quote a libpq keyword/value DSN value when needed."""
|
|
68
|
+
if value and all(c.isalnum() or c in "._-/:" for c in value):
|
|
69
|
+
return value
|
|
70
|
+
return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class PostgresConnector(DatabaseConnector):
|
|
74
|
+
"""Attach a PostgreSQL database read-only; queries run remotely via ``postgres_query``."""
|
|
75
|
+
|
|
76
|
+
scheme: ClassVar[tuple[str, ...]] = ("postgres", "postgresql")
|
|
77
|
+
extension = "postgres"
|
|
78
|
+
dialect: ClassVar[Dialect] = "postgres"
|
|
79
|
+
default_schema = "public"
|
|
80
|
+
|
|
81
|
+
def __init__(self, name: str, url: ParsedUrl) -> None:
|
|
82
|
+
super().__init__(name, url)
|
|
83
|
+
url.require_known_options(set(LIBPQ_OPTIONS | PLATYBUS_OPTIONS))
|
|
84
|
+
if not url.path.strip("/"):
|
|
85
|
+
raise ConfigError(f"{url.masked}: database name is missing (postgres://host/db)")
|
|
86
|
+
if "/" in url.path.strip("/"):
|
|
87
|
+
raise ConfigError(f"{url.masked}: expected a single database name in the path")
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def database(self) -> str:
|
|
91
|
+
return self.url.path.strip("/")
|
|
92
|
+
|
|
93
|
+
def _schema_for(self) -> str:
|
|
94
|
+
return self.url.option("schema") or self.default_schema
|
|
95
|
+
|
|
96
|
+
def dsn_options(self) -> str:
|
|
97
|
+
"""Non-secret libpq options for the ATTACH path (``sslmode=require ...``)."""
|
|
98
|
+
opts = {k: v for k, v in self.url.params.items() if k in LIBPQ_OPTIONS}
|
|
99
|
+
opts.setdefault("connect_timeout", DEFAULT_CONNECT_TIMEOUT)
|
|
100
|
+
return " ".join(f"{k}={libpq_value(v)}" for k, v in sorted(opts.items()))
|
|
101
|
+
|
|
102
|
+
def secret_sql(self, alias: str) -> str:
|
|
103
|
+
options = ["TYPE postgres", f"DATABASE {quote_literal(self.database)}"]
|
|
104
|
+
if self.url.host:
|
|
105
|
+
options.append(f"HOST {quote_literal(self.url.host)}")
|
|
106
|
+
if self.url.port:
|
|
107
|
+
options.append(f"PORT {int(self.url.port)}")
|
|
108
|
+
if self.url.username:
|
|
109
|
+
options.append(f"USER {quote_literal(self.url.username)}")
|
|
110
|
+
if self.url.password:
|
|
111
|
+
options.append(f"PASSWORD {quote_literal(self.url.password)}")
|
|
112
|
+
return f"CREATE OR REPLACE SECRET {quote_ident(secret_name(alias))} ({', '.join(options)})"
|
|
113
|
+
|
|
114
|
+
def attach_sql(self, alias: str) -> str:
|
|
115
|
+
options = ["TYPE postgres", f"SECRET {quote_ident(secret_name(alias))}", "READ_ONLY"]
|
|
116
|
+
schema = self.url.option("schema")
|
|
117
|
+
if schema:
|
|
118
|
+
options.append(f"SCHEMA {quote_literal(schema)}")
|
|
119
|
+
return (
|
|
120
|
+
f"ATTACH {quote_literal(self.dsn_options())} AS {quote_ident(alias)} "
|
|
121
|
+
f"({', '.join(options)})"
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def target(self) -> str:
|
|
126
|
+
"""``host:port/database``, for messages."""
|
|
127
|
+
return pg_target(self.url.host, self.url.port, self.database)
|
|
128
|
+
|
|
129
|
+
def _attach_as(self, con: duckdb.DuckDBPyConnection, alias: str) -> None:
|
|
130
|
+
con.execute(self.secret_sql(alias))
|
|
131
|
+
try:
|
|
132
|
+
con.execute(self.attach_sql(alias))
|
|
133
|
+
except duckdb.Error as exc:
|
|
134
|
+
raise type(exc)(explain_error(str(exc), self.target)) from None
|
|
135
|
+
|
|
136
|
+
def _probe(self, con: duckdb.DuckDBPyConnection, alias: str) -> str:
|
|
137
|
+
row = con.execute(
|
|
138
|
+
f"SELECT * FROM postgres_query({quote_literal(alias)}, 'select version()')"
|
|
139
|
+
).fetchone()
|
|
140
|
+
version = str(row[0]).split(",", 1)[0] if row else "PostgreSQL"
|
|
141
|
+
return f"connected: {version}"
|
|
142
|
+
|
|
143
|
+
def _query_sql(self, query: str, request: ReadRequest) -> str:
|
|
144
|
+
remote = wrap_with_filter(query, request.cursor, self.dialect)
|
|
145
|
+
return f"select * from postgres_query({quote_literal(self.name)}, {quote_literal(remote)})"
|
|
File without changes
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""PostgreSQL as a warehouse store (DuckDB ``postgres`` extension, read-write attach).
|
|
2
|
+
|
|
3
|
+
DuckDB stays the engine: it reads sources, runs the transformations and writes the
|
|
4
|
+
result into Postgres tables through the attached catalog. ``stores.yml``::
|
|
5
|
+
|
|
6
|
+
default: wh
|
|
7
|
+
stores:
|
|
8
|
+
wh:
|
|
9
|
+
type: postgres
|
|
10
|
+
host: db.example.com
|
|
11
|
+
database: warehouse
|
|
12
|
+
user: platybus
|
|
13
|
+
password: ${WH_PASSWORD}
|
|
14
|
+
|
|
15
|
+
The password lives in a DuckDB secret, never in the ATTACH path (which is visible in
|
|
16
|
+
``duckdb_databases()``). See docs/stores/postgres.md for the type mapping and limits.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import contextlib
|
|
22
|
+
from typing import Annotated, Literal
|
|
23
|
+
|
|
24
|
+
import duckdb
|
|
25
|
+
from pydantic import Field
|
|
26
|
+
|
|
27
|
+
from platybus.catalog.ducklake import load_extension
|
|
28
|
+
from platybus.config.base import StrictModel
|
|
29
|
+
from platybus.config.secrets import redact
|
|
30
|
+
from platybus.errors import CatalogError
|
|
31
|
+
from platybus.log import get_logger
|
|
32
|
+
from platybus.sqlutil import quote_ident, quote_literal
|
|
33
|
+
from platybus.stores import BaseStore, StoreBackend, StoreCapabilities, StoreContext
|
|
34
|
+
from platybus_postgres.connector import (
|
|
35
|
+
DEFAULT_CONNECT_TIMEOUT,
|
|
36
|
+
explain_error,
|
|
37
|
+
libpq_value,
|
|
38
|
+
pg_target,
|
|
39
|
+
)
|
|
40
|
+
from platybus_postgres.types import storable_type
|
|
41
|
+
|
|
42
|
+
log = get_logger(__name__)
|
|
43
|
+
|
|
44
|
+
EXTENSION = "postgres"
|
|
45
|
+
#: Postgres system schemas: listed by ``duckdb_tables()`` but not user data.
|
|
46
|
+
SYSTEM_SCHEMAS = frozenset({"information_schema", "pg_catalog", "pg_toast"})
|
|
47
|
+
|
|
48
|
+
SslMode = Literal["disable", "allow", "prefer", "require", "verify-ca", "verify-full"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class PostgresSettings(StrictModel):
|
|
52
|
+
"""Settings of a ``postgres`` store."""
|
|
53
|
+
|
|
54
|
+
host: str = Field(..., min_length=1, description="Server host name or IP address.")
|
|
55
|
+
port: Annotated[int, Field(ge=1, le=65535)] = Field(5432, description="Server port.")
|
|
56
|
+
database: str = Field(
|
|
57
|
+
...,
|
|
58
|
+
min_length=1,
|
|
59
|
+
description="Database that holds the tables (it must exist, see create_database).",
|
|
60
|
+
)
|
|
61
|
+
user: str | None = Field(
|
|
62
|
+
None, description="Role to connect as; it needs CREATE on the database."
|
|
63
|
+
)
|
|
64
|
+
password: str | None = Field(
|
|
65
|
+
None, description="Password. Stored in .env and referenced as ${VAR}."
|
|
66
|
+
)
|
|
67
|
+
sslmode: SslMode | None = Field(
|
|
68
|
+
None, description="libpq sslmode (default: prefer). Use require or stricter off-host."
|
|
69
|
+
)
|
|
70
|
+
connect_timeout: Annotated[int, Field(ge=1, le=600)] = Field(
|
|
71
|
+
int(DEFAULT_CONNECT_TIMEOUT), description="Seconds to wait for a connection."
|
|
72
|
+
)
|
|
73
|
+
create_database: bool = Field(
|
|
74
|
+
False,
|
|
75
|
+
description="Create the database when it does not exist (the user needs CREATEDB). "
|
|
76
|
+
"The sandbox preset uses it to give every project its own database.",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def secret_name(store: str) -> str:
|
|
81
|
+
"""Name of the DuckDB secret holding the credentials of store ``store``."""
|
|
82
|
+
return f"platybus_store_{store}"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
#: Database every Postgres server has; used to create the store's database.
|
|
86
|
+
MAINTENANCE_DB = "postgres"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def pg_ident(name: str) -> str:
|
|
90
|
+
"""A Postgres identifier in double quotes (for SQL run inside Postgres)."""
|
|
91
|
+
return '"' + name.replace('"', '""') + '"'
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class PostgresStore(BaseStore):
|
|
95
|
+
"""A PostgreSQL database attached read-write as a DuckDB catalog.
|
|
96
|
+
|
|
97
|
+
Tables are plain Postgres tables, usable by any other Postgres client. Views cannot
|
|
98
|
+
be created through DuckDB (the statement would carry DuckDB's catalog-qualified
|
|
99
|
+
names), so ``view`` models are materialized as tables.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
type = "postgres"
|
|
103
|
+
capabilities = StoreCapabilities(replace_table=True, views=False, merge=True, snapshots=False)
|
|
104
|
+
hidden_schemas = SYSTEM_SCHEMAS
|
|
105
|
+
|
|
106
|
+
def __init__(self, name: str, settings: PostgresSettings) -> None:
|
|
107
|
+
super().__init__(name)
|
|
108
|
+
self.settings = settings
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------ statements
|
|
111
|
+
def dsn_options(self) -> str:
|
|
112
|
+
"""Non-secret libpq options for the ATTACH path (visible in ``duckdb_databases()``)."""
|
|
113
|
+
options = {"connect_timeout": str(self.settings.connect_timeout)}
|
|
114
|
+
if self.settings.sslmode:
|
|
115
|
+
options["sslmode"] = self.settings.sslmode
|
|
116
|
+
return " ".join(f"{k}={libpq_value(v)}" for k, v in sorted(options.items()))
|
|
117
|
+
|
|
118
|
+
def secret_sql(self, *, database: str | None = None, secret: str | None = None) -> str:
|
|
119
|
+
s = self.settings
|
|
120
|
+
options = [
|
|
121
|
+
"TYPE postgres",
|
|
122
|
+
f"HOST {quote_literal(s.host)}",
|
|
123
|
+
f"PORT {int(s.port)}",
|
|
124
|
+
f"DATABASE {quote_literal(database or s.database)}",
|
|
125
|
+
]
|
|
126
|
+
if s.user:
|
|
127
|
+
options.append(f"USER {quote_literal(s.user)}")
|
|
128
|
+
if s.password:
|
|
129
|
+
options.append(f"PASSWORD {quote_literal(s.password)}")
|
|
130
|
+
name = quote_ident(secret or secret_name(self.name))
|
|
131
|
+
return f"CREATE OR REPLACE SECRET {name} ({', '.join(options)})"
|
|
132
|
+
|
|
133
|
+
def attach_statement(self) -> str:
|
|
134
|
+
return (
|
|
135
|
+
f"ATTACH IF NOT EXISTS {quote_literal(self.dsn_options())} AS {quote_ident(self.name)} "
|
|
136
|
+
f"(TYPE postgres, SECRET {quote_ident(secret_name(self.name))})"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def attach_sql(self) -> list[str]:
|
|
140
|
+
return [
|
|
141
|
+
f"INSTALL {EXTENSION}",
|
|
142
|
+
f"LOAD {EXTENSION}",
|
|
143
|
+
self.secret_sql(),
|
|
144
|
+
self.attach_statement(),
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
def ensure_database(self, con: duckdb.DuckDBPyConnection) -> bool:
|
|
148
|
+
"""Create the database if it does not exist; ``True`` if it was created.
|
|
149
|
+
|
|
150
|
+
Connects to the server's maintenance database under a throwaway alias.
|
|
151
|
+
``CREATE DATABASE`` cannot run in a transaction, hence ``use_transaction``.
|
|
152
|
+
"""
|
|
153
|
+
database = self.settings.database
|
|
154
|
+
alias = f"platybus_admin_{self.name}"
|
|
155
|
+
con.execute(self.secret_sql(database=MAINTENANCE_DB, secret=alias))
|
|
156
|
+
try:
|
|
157
|
+
con.execute(
|
|
158
|
+
f"ATTACH {quote_literal(self.dsn_options())} AS {quote_ident(alias)} "
|
|
159
|
+
f"(TYPE postgres, SECRET {quote_ident(alias)})"
|
|
160
|
+
)
|
|
161
|
+
probe = f"select 1 from pg_database where datname = {quote_literal(database)}"
|
|
162
|
+
found = con.execute(
|
|
163
|
+
f"SELECT * FROM postgres_query({quote_literal(alias)}, {quote_literal(probe)})"
|
|
164
|
+
).fetchall()
|
|
165
|
+
if found:
|
|
166
|
+
return False
|
|
167
|
+
create = f"CREATE DATABASE {pg_ident(database)}"
|
|
168
|
+
try:
|
|
169
|
+
con.execute(
|
|
170
|
+
f"CALL postgres_execute({quote_literal(alias)}, {quote_literal(create)}, "
|
|
171
|
+
"use_transaction := false)"
|
|
172
|
+
)
|
|
173
|
+
except duckdb.Error as exc:
|
|
174
|
+
if "already exists" in str(exc): # created concurrently: fine
|
|
175
|
+
return False
|
|
176
|
+
raise
|
|
177
|
+
log.info("postgres database created", store=self.name, database=database)
|
|
178
|
+
return True
|
|
179
|
+
finally:
|
|
180
|
+
with contextlib.suppress(duckdb.Error):
|
|
181
|
+
con.execute(f"DETACH DATABASE IF EXISTS {quote_ident(alias)}")
|
|
182
|
+
with contextlib.suppress(duckdb.Error):
|
|
183
|
+
con.execute(f"DROP SECRET IF EXISTS {quote_ident(alias)}")
|
|
184
|
+
|
|
185
|
+
# ------------------------------------------------------------------ StoreBackend
|
|
186
|
+
def attach(self, con: duckdb.DuckDBPyConnection) -> None:
|
|
187
|
+
load_extension(con, EXTENSION)
|
|
188
|
+
try:
|
|
189
|
+
if self.settings.create_database:
|
|
190
|
+
self.ensure_database(con)
|
|
191
|
+
con.execute(self.secret_sql())
|
|
192
|
+
con.execute(self.attach_statement())
|
|
193
|
+
except duckdb.Error as exc:
|
|
194
|
+
message = redact(explain_error(str(exc), self.target), self.secrets())
|
|
195
|
+
raise CatalogError(
|
|
196
|
+
f"cannot attach PostgreSQL store '{self.name}' ({self.location}): {message}"
|
|
197
|
+
) from None
|
|
198
|
+
|
|
199
|
+
def refresh(self, con: duckdb.DuckDBPyConnection) -> None:
|
|
200
|
+
"""Forget cached schema and table lists, e.g. after another process (the dbt
|
|
201
|
+
worker, any Postgres client) changed the database."""
|
|
202
|
+
con.execute("CALL pg_clear_cache()")
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def target(self) -> str:
|
|
206
|
+
"""``host:port/database``, for messages."""
|
|
207
|
+
return pg_target(self.settings.host, self.settings.port, self.settings.database)
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def location(self) -> str:
|
|
211
|
+
s = self.settings
|
|
212
|
+
host = f"[{s.host}]" if ":" in s.host else s.host
|
|
213
|
+
return f"postgres://{host}:{s.port}/{s.database}"
|
|
214
|
+
|
|
215
|
+
def describe(self) -> dict[str, str]:
|
|
216
|
+
facts = {"catalog": "postgres", "location": self.location}
|
|
217
|
+
if self.settings.user:
|
|
218
|
+
facts["user"] = self.settings.user
|
|
219
|
+
return facts
|
|
220
|
+
|
|
221
|
+
def secrets(self) -> list[str]:
|
|
222
|
+
return [self.settings.password] if self.settings.password else []
|
|
223
|
+
|
|
224
|
+
def storable_type(self, duckdb_type: str) -> str:
|
|
225
|
+
"""Cast for columns Postgres cannot hold as they are (:class:`TypeMapper`)."""
|
|
226
|
+
return storable_type(duckdb_type)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def postgres_store(context: StoreContext) -> StoreBackend:
|
|
230
|
+
settings = PostgresSettings.model_validate(dict(context.settings))
|
|
231
|
+
return PostgresStore(context.name, settings)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Mapping of DuckDB column types onto what DuckDB can write to a PostgreSQL table.
|
|
2
|
+
|
|
3
|
+
The DuckDB ``postgres`` extension maps most types itself, but some it cannot write or
|
|
4
|
+
writes lossily:
|
|
5
|
+
|
|
6
|
+
- ``HUGEINT`` becomes ``double precision`` (``sum()`` of a ``BIGINT`` is a ``HUGEINT``,
|
|
7
|
+
so totals silently lose precision) and ``UHUGEINT`` becomes text;
|
|
8
|
+
- ``ENUM`` and ``STRUCT`` are rejected (Postgres needs *named* enum and composite types);
|
|
9
|
+
- ``MAP`` and ``UNION`` become DuckDB's display text (``{k=1}``), which nothing parses;
|
|
10
|
+
- nested lists become multidimensional arrays, which Postgres requires to be
|
|
11
|
+
rectangular.
|
|
12
|
+
|
|
13
|
+
So the ETL casts such columns before they reach the store (see
|
|
14
|
+
:class:`platybus.stores.base.TypeMapper`): integers to ``DECIMAL(38,0)`` (Postgres
|
|
15
|
+
``numeric(38,0)``, read back exactly), enums to ``VARCHAR``, and nested values to ``JSON``
|
|
16
|
+
(a Postgres ``json`` column, read back as JSON text).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
|
|
23
|
+
#: A type name ends here; a struct field *name* is followed by a space and its type.
|
|
24
|
+
_END = r"(?=\s*(?:,|\)|\[|$))"
|
|
25
|
+
|
|
26
|
+
#: (pattern, replacement), applied in order to an upper-case DuckDB type string.
|
|
27
|
+
_RULES: tuple[tuple[re.Pattern[str], str], ...] = (
|
|
28
|
+
# ENUM('a', 'b') would need a named Postgres enum type: keep the labels as text.
|
|
29
|
+
(re.compile(r"\bENUM\((?:'(?:[^']|'')*'(?:\s*,\s*)?)*\)"), "VARCHAR"),
|
|
30
|
+
# Fixed-size arrays become lists (Postgres arrays have no fixed size).
|
|
31
|
+
(re.compile(r"\[\d+\]"), "[]"),
|
|
32
|
+
# Exact integers wider than BIGINT: numeric(38,0) instead of double precision / text.
|
|
33
|
+
(re.compile(r"\bU?HUGEINT\b" + _END), "DECIMAL(38,0)"),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_QUOTED = re.compile(r'("(?:[^"]|"")*")')
|
|
37
|
+
#: Nested values Postgres has no unnamed type for: the whole column is stored as JSON.
|
|
38
|
+
_NESTED = re.compile(r"\b(?:STRUCT|MAP|UNION)\(")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def storable_type(duckdb_type: str) -> str:
|
|
42
|
+
"""The type a column of ``duckdb_type`` gets in a PostgreSQL table.
|
|
43
|
+
|
|
44
|
+
Types that are fine as they are come back unchanged; quoted struct field names are
|
|
45
|
+
left alone.
|
|
46
|
+
|
|
47
|
+
>>> storable_type("HUGEINT")
|
|
48
|
+
'DECIMAL(38,0)'
|
|
49
|
+
>>> storable_type("ENUM('a', 'b')[]")
|
|
50
|
+
'VARCHAR[]'
|
|
51
|
+
>>> storable_type("STRUCT(a INTEGER)[]")
|
|
52
|
+
'JSON'
|
|
53
|
+
>>> storable_type("INTEGER[3]")
|
|
54
|
+
'INTEGER[]'
|
|
55
|
+
"""
|
|
56
|
+
parts = _QUOTED.split(duckdb_type)
|
|
57
|
+
unquoted = parts[::2] # odd items are quoted identifiers
|
|
58
|
+
if any(_NESTED.search(part) for part in unquoted):
|
|
59
|
+
return "JSON"
|
|
60
|
+
for index in range(0, len(parts), 2):
|
|
61
|
+
text = parts[index]
|
|
62
|
+
for pattern, replacement in _RULES:
|
|
63
|
+
text = pattern.sub(replacement, text)
|
|
64
|
+
parts[index] = text
|
|
65
|
+
result = "".join(parts)
|
|
66
|
+
if result.endswith("[][]"): # ragged lists of lists are not Postgres arrays
|
|
67
|
+
return "JSON"
|
|
68
|
+
return result
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""PostgreSQL warehouse store without a server (the server tests are integration tests:
|
|
2
|
+
tests/integration/stores/test_postgres_store.py)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import duckdb
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from platybus.config import load_project
|
|
12
|
+
from platybus.errors import CatalogError, ConfigError
|
|
13
|
+
from platybus.etl.sql import storable_select
|
|
14
|
+
from platybus.plugins import get_plugin
|
|
15
|
+
from platybus.sandbox.base import SANDBOX_PASSWORD, SANDBOX_USER
|
|
16
|
+
from platybus.sandbox.builtin import POSTGRES_PORT, POSTGRES_SOURCE_DB
|
|
17
|
+
from platybus.stores import (
|
|
18
|
+
StoreCapabilities,
|
|
19
|
+
TableWriter,
|
|
20
|
+
TypeMapper,
|
|
21
|
+
create_store,
|
|
22
|
+
manage,
|
|
23
|
+
store_spec,
|
|
24
|
+
)
|
|
25
|
+
from platybus_postgres.connector import explain_error, pg_target
|
|
26
|
+
from platybus_postgres.store import SYSTEM_SCHEMAS, PostgresSettings, PostgresStore, secret_name
|
|
27
|
+
from platybus_postgres.types import storable_type
|
|
28
|
+
|
|
29
|
+
PASSWORD = "Pg-s3cret'word"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def make_store(**settings: object) -> PostgresStore:
|
|
33
|
+
values: dict[str, object] = {
|
|
34
|
+
"host": "db.internal",
|
|
35
|
+
"database": "dwh",
|
|
36
|
+
"user": "builder",
|
|
37
|
+
"password": PASSWORD,
|
|
38
|
+
**settings,
|
|
39
|
+
}
|
|
40
|
+
return PostgresStore("wh", PostgresSettings.model_validate(values))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_store_type_is_registered_with_its_sandbox_preset() -> None:
|
|
44
|
+
spec = store_spec("postgres")
|
|
45
|
+
assert spec.category == "warehouse"
|
|
46
|
+
assert spec.capabilities == StoreCapabilities(
|
|
47
|
+
replace_table=True, views=False, merge=True, snapshots=False
|
|
48
|
+
)
|
|
49
|
+
assert spec.transforms == ("sql", "dbt")
|
|
50
|
+
assert spec.sandbox is not None and spec.sandbox.services == ("postgres",)
|
|
51
|
+
# one database per project, created on first use
|
|
52
|
+
assert spec.sandbox.settings_for("jaffle-shop") == {
|
|
53
|
+
"host": "127.0.0.1",
|
|
54
|
+
"port": POSTGRES_PORT,
|
|
55
|
+
"database": "wh_jaffle_shop",
|
|
56
|
+
"user": SANDBOX_USER,
|
|
57
|
+
"password": SANDBOX_PASSWORD,
|
|
58
|
+
"create_database": True,
|
|
59
|
+
}
|
|
60
|
+
assert spec.sandbox.settings_for("other")["database"] == "wh_other"
|
|
61
|
+
PostgresSettings.model_validate(spec.sandbox.settings_for("p")) # a valid configuration
|
|
62
|
+
(connector,) = get_plugin("postgres", "connector").connectors
|
|
63
|
+
assert connector.sandbox is not None
|
|
64
|
+
# the sample source is shared on purpose: it is read-only
|
|
65
|
+
assert connector.sandbox.settings_for("p")["database"] == POSTGRES_SOURCE_DB
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_ensure_database_statements() -> None:
|
|
69
|
+
"""``create_database`` creates the database through the maintenance database, outside a
|
|
70
|
+
transaction (the server side is tested in tests/integration/sandbox)."""
|
|
71
|
+
store = make_store(database='new"db', create_database=True)
|
|
72
|
+
statements: list[str] = []
|
|
73
|
+
|
|
74
|
+
class Recorder:
|
|
75
|
+
def execute(self, sql: str) -> Recorder:
|
|
76
|
+
statements.append(sql)
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
def fetchall(self) -> list[tuple[int]]:
|
|
80
|
+
return []
|
|
81
|
+
|
|
82
|
+
assert store.ensure_database(Recorder()) is True # type: ignore[arg-type]
|
|
83
|
+
secret, attach, probe, create, detach, drop = statements
|
|
84
|
+
assert "DATABASE 'postgres'" in secret and '"platybus_admin_wh"' in secret
|
|
85
|
+
assert attach.startswith("ATTACH 'connect_timeout=10'") and PASSWORD not in attach
|
|
86
|
+
assert probe.endswith("'select 1 from pg_database where datname = ''new\"db''')")
|
|
87
|
+
assert create == (
|
|
88
|
+
"CALL postgres_execute('platybus_admin_wh', 'CREATE DATABASE \"new\"\"db\"', "
|
|
89
|
+
"use_transaction := false)"
|
|
90
|
+
)
|
|
91
|
+
assert detach.startswith("DETACH") and drop.startswith("DROP SECRET")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_attach_sql_keeps_the_password_in_a_secret() -> None:
|
|
95
|
+
store = make_store(sslmode="require")
|
|
96
|
+
install, load, secret, attach = store.attach_sql()
|
|
97
|
+
assert (install, load) == ("INSTALL postgres", "LOAD postgres")
|
|
98
|
+
assert secret.startswith(f'CREATE OR REPLACE SECRET "{secret_name("wh")}" (TYPE postgres')
|
|
99
|
+
assert "PASSWORD 'Pg-s3cret''word'" in secret # quoted as a SQL literal
|
|
100
|
+
assert "HOST 'db.internal'" in secret and "PORT 5432" in secret
|
|
101
|
+
# the ATTACH path is visible in duckdb_databases(): no credentials in it
|
|
102
|
+
assert PASSWORD not in attach and "builder" not in attach
|
|
103
|
+
assert attach == (
|
|
104
|
+
"ATTACH IF NOT EXISTS 'connect_timeout=10 sslmode=require' AS \"wh\" "
|
|
105
|
+
f'(TYPE postgres, SECRET "{secret_name("wh")}")'
|
|
106
|
+
)
|
|
107
|
+
assert "PERSISTENT" not in secret # an in-memory secret, never written to disk
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_describe_and_secrets() -> None:
|
|
111
|
+
store = make_store()
|
|
112
|
+
assert store.describe() == {
|
|
113
|
+
"catalog": "postgres",
|
|
114
|
+
"location": "postgres://db.internal:5432/dwh",
|
|
115
|
+
"user": "builder",
|
|
116
|
+
}
|
|
117
|
+
assert PASSWORD not in repr(store.describe())
|
|
118
|
+
assert store.secrets() == [PASSWORD]
|
|
119
|
+
assert make_store(password=None).secrets() == []
|
|
120
|
+
assert make_store(host="::1").location == "postgres://[::1]:5432/dwh"
|
|
121
|
+
assert store.hidden_schemas == SYSTEM_SCHEMAS
|
|
122
|
+
assert {"information_schema", "pg_catalog", "pg_toast"} == SYSTEM_SCHEMAS
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_settings_validation() -> None:
|
|
126
|
+
with pytest.raises(ValueError, match="database"):
|
|
127
|
+
PostgresSettings.model_validate({"host": "h"})
|
|
128
|
+
with pytest.raises(ValueError, match="sslmode"):
|
|
129
|
+
PostgresSettings.model_validate({"host": "h", "database": "d", "sslmode": "sometimes"})
|
|
130
|
+
with pytest.raises(ValueError, match="port"):
|
|
131
|
+
PostgresSettings.model_validate({"host": "h", "database": "d", "port": 70000})
|
|
132
|
+
assert PostgresSettings.model_validate({"host": "h", "database": "d"}).port == 5432
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_attach_failure_is_a_redacted_catalog_error() -> None:
|
|
136
|
+
# Nothing listens on port 1: the attach fails fast with the driver's message.
|
|
137
|
+
store = make_store(host="127.0.0.1", port=1, connect_timeout=2)
|
|
138
|
+
con = duckdb.connect()
|
|
139
|
+
try:
|
|
140
|
+
with pytest.raises(CatalogError, match="cannot attach PostgreSQL store 'wh'") as err:
|
|
141
|
+
store.attach(con)
|
|
142
|
+
finally:
|
|
143
|
+
con.close()
|
|
144
|
+
assert PASSWORD not in err.value.message
|
|
145
|
+
assert "postgres://127.0.0.1:1/dwh" in err.value.message
|
|
146
|
+
# Regression: the driver's text named only the libpq options of the ATTACH path.
|
|
147
|
+
assert "Unable to connect to Postgres at 127.0.0.1:1/dwh" in err.value.message
|
|
148
|
+
assert '"connect_timeout=' not in err.value.message
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@pytest.mark.parametrize(
|
|
152
|
+
("message", "explained"),
|
|
153
|
+
[
|
|
154
|
+
(
|
|
155
|
+
'IO Error: Unable to connect to Postgres at "connect_timeout=10": timeout expired',
|
|
156
|
+
"IO Error: Unable to connect to Postgres at db.internal:5432/dwh: timeout expired",
|
|
157
|
+
),
|
|
158
|
+
(
|
|
159
|
+
'IO Error: Unable to connect to Postgres at "connect_timeout=10 sslmode=require '
|
|
160
|
+
"sslrootcert='C:/a b/ca.pem'\": could not translate host name",
|
|
161
|
+
"IO Error: Unable to connect to Postgres at db.internal:5432/dwh: "
|
|
162
|
+
"could not translate host name",
|
|
163
|
+
),
|
|
164
|
+
("Catalog Error: Table x does not exist", "Catalog Error: Table x does not exist"),
|
|
165
|
+
],
|
|
166
|
+
)
|
|
167
|
+
def test_explain_error_names_the_server(message: str, explained: str) -> None:
|
|
168
|
+
assert explain_error(message, pg_target("db.internal", None, "dwh")) == explained
|
|
169
|
+
assert pg_target("::1", 6543, "d") == "[::1]:6543/d"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def test_add_store_moves_the_password_to_dotenv(tmp_path: Path) -> None:
|
|
173
|
+
root = tmp_path / "p"
|
|
174
|
+
root.mkdir()
|
|
175
|
+
(root / "platybus.yml").write_text("name: demo\n", encoding="utf-8")
|
|
176
|
+
project = load_project(root)
|
|
177
|
+
manage.add_store(
|
|
178
|
+
project, "wh", "postgres", {"host": "db", "database": "dwh", "password": PASSWORD}
|
|
179
|
+
)
|
|
180
|
+
text = (root / "stores.yml").read_text(encoding="utf-8")
|
|
181
|
+
assert PASSWORD not in text and "${WH_PASSWORD}" in text
|
|
182
|
+
reloaded = load_project(root)
|
|
183
|
+
backend = create_store(reloaded, "wh")
|
|
184
|
+
assert isinstance(backend, PostgresStore) and backend.settings.password == PASSWORD
|
|
185
|
+
with pytest.raises(ConfigError, match=r"store bad: invalid configuration"):
|
|
186
|
+
manage.add_store(reloaded, "bad", "postgres", {"host": "db"})
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@pytest.mark.parametrize(
|
|
190
|
+
("duckdb_type", "stored"),
|
|
191
|
+
[
|
|
192
|
+
("HUGEINT", "DECIMAL(38,0)"),
|
|
193
|
+
("UHUGEINT", "DECIMAL(38,0)"),
|
|
194
|
+
("HUGEINT[]", "DECIMAL(38,0)[]"),
|
|
195
|
+
("ENUM('a', 'b')", "VARCHAR"),
|
|
196
|
+
("ENUM('it''s', 'b')[]", "VARCHAR[]"),
|
|
197
|
+
("STRUCT(a INTEGER, b VARCHAR)", "JSON"),
|
|
198
|
+
("STRUCT(a INTEGER)[]", "JSON"),
|
|
199
|
+
("MAP(VARCHAR, INTEGER)", "JSON"),
|
|
200
|
+
("UNION(n INTEGER, s VARCHAR)", "JSON"),
|
|
201
|
+
("INTEGER[][]", "JSON"),
|
|
202
|
+
("INTEGER[3]", "INTEGER[]"),
|
|
203
|
+
# unchanged: the extension maps these itself
|
|
204
|
+
("BIGINT", "BIGINT"),
|
|
205
|
+
("DECIMAL(18,3)", "DECIMAL(18,3)"),
|
|
206
|
+
("VARCHAR[]", "VARCHAR[]"),
|
|
207
|
+
("TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE"),
|
|
208
|
+
("JSON", "JSON"),
|
|
209
|
+
],
|
|
210
|
+
)
|
|
211
|
+
def test_storable_type(duckdb_type: str, stored: str) -> None:
|
|
212
|
+
assert storable_type(duckdb_type) == stored
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_store_casts_columns_postgres_cannot_hold() -> None:
|
|
216
|
+
store = make_store()
|
|
217
|
+
assert isinstance(store, TypeMapper)
|
|
218
|
+
assert not isinstance(store, TableWriter) # CREATE OR REPLACE TABLE stays atomic
|
|
219
|
+
con = duckdb.connect()
|
|
220
|
+
con.execute("CREATE TYPE mood AS ENUM ('ok', 'meh')")
|
|
221
|
+
sql = (
|
|
222
|
+
"SELECT sum(x) AS total, 'ok'::mood AS mood, {'a': 1} AS s, MAP {'k': 1} AS m, "
|
|
223
|
+
"42 AS n FROM (SELECT 1::BIGINT AS x)"
|
|
224
|
+
)
|
|
225
|
+
cast = storable_select(con, store, sql)
|
|
226
|
+
described = con.execute(f"DESCRIBE {cast}").fetchall()
|
|
227
|
+
assert [(r[0], r[1]) for r in described] == [
|
|
228
|
+
("total", "DECIMAL(38,0)"),
|
|
229
|
+
("mood", "VARCHAR"),
|
|
230
|
+
("s", "JSON"),
|
|
231
|
+
("m", "JSON"),
|
|
232
|
+
("n", "INTEGER"),
|
|
233
|
+
]
|
|
234
|
+
assert con.execute(f"SELECT s, m FROM ({cast})").fetchone() == ('{"a":1}', '{"k":1}')
|