platybus-postgres 0.1.1__py3-none-any.whl
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/__init__.py +86 -0
- platybus_postgres/connector.py +145 -0
- platybus_postgres/py.typed +0 -0
- platybus_postgres/store.py +231 -0
- platybus_postgres/types.py +68 -0
- platybus_postgres-0.1.1.dist-info/METADATA +41 -0
- platybus_postgres-0.1.1.dist-info/RECORD +10 -0
- platybus_postgres-0.1.1.dist-info/WHEEL +4 -0
- platybus_postgres-0.1.1.dist-info/entry_points.txt +2 -0
- platybus_postgres-0.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -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,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,10 @@
|
|
|
1
|
+
platybus_postgres/__init__.py,sha256=UZlPMTImfhrREOlcCktANkCiFNTFyWRZ-VTHLy7-h1E,3558
|
|
2
|
+
platybus_postgres/connector.py,sha256=5M1uaybdpzJzVqUM8rgztEvxWpSmj-wcni18buN1-Xk,5635
|
|
3
|
+
platybus_postgres/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
platybus_postgres/store.py,sha256=NcrmIuORCSDWRJ9a8QNBbfKD_Y-GNDIGfUaysw9Fgqg,9122
|
|
5
|
+
platybus_postgres/types.py,sha256=BDlnn5eIdRuThilqYNas0hnDVDoqdlB6tokh-fZ5yIc,2780
|
|
6
|
+
platybus_postgres-0.1.1.dist-info/METADATA,sha256=-gT8cMPpp_5NArEBbpo_ZIX07Fb-qDvw94LHBTuDeKc,1676
|
|
7
|
+
platybus_postgres-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
platybus_postgres-0.1.1.dist-info/entry_points.txt,sha256=zu28v1Py6s0p2DiZ6x6h7WdSUP5O6wjyP9EX6zkOOgo,55
|
|
9
|
+
platybus_postgres-0.1.1.dist-info/licenses/LICENSE,sha256=1GSdi_XmZ_go3KCNsqt6OJpYJBXDmJCdR4XMnWUWTTY,1072
|
|
10
|
+
platybus_postgres-0.1.1.dist-info/RECORD,,
|
|
@@ -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.
|