|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +from urllib.parse import urlparse |
| 7 | + |
| 8 | +import duckdb |
| 9 | +import psycopg |
| 10 | +from psycopg import sql |
| 11 | + |
| 12 | +DEFAULTS: dict[str, str] = { |
| 13 | + "DUCKLAKE_CATALOG_DSN": "ducklake:postgres:dbname=ducklake_catalog host=localhost user=posthog password=posthog", |
| 14 | + "DUCKLAKE_DATA_BUCKET": "ducklake-dev", |
| 15 | + "DUCKLAKE_DATA_ENDPOINT": "http://localhost:19000", |
| 16 | + "DUCKLAKE_S3_ACCESS_KEY": "object_storage_root_user", |
| 17 | + "DUCKLAKE_S3_SECRET_KEY": "object_storage_root_password", |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +def get_config() -> dict[str, str]: |
| 22 | + return {key: os.environ.get(key, default) or default for key, default in DEFAULTS.items()} |
| 23 | + |
| 24 | + |
| 25 | +def escape(value: str) -> str: |
| 26 | + return value.replace("'", "''") |
| 27 | + |
| 28 | + |
| 29 | +def normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]: |
| 30 | + value = (raw_endpoint or "").strip() |
| 31 | + if not value: |
| 32 | + value = DEFAULTS["DUCKLAKE_DATA_ENDPOINT"] |
| 33 | + |
| 34 | + if "://" in value: |
| 35 | + parsed = urlparse(value) |
| 36 | + endpoint = parsed.netloc or parsed.path |
| 37 | + use_ssl = parsed.scheme.lower() == "https" |
| 38 | + else: |
| 39 | + endpoint = value |
| 40 | + use_ssl = False |
| 41 | + |
| 42 | + endpoint = endpoint.rstrip("/") or "localhost:19000" |
| 43 | + return endpoint, use_ssl |
| 44 | + |
| 45 | + |
| 46 | +def configure_connection( |
| 47 | + conn: duckdb.DuckDBPyConnection, |
| 48 | + config: dict[str, str], |
| 49 | + *, |
| 50 | + install_extension: bool, |
| 51 | +) -> None: |
| 52 | + if install_extension: |
| 53 | + conn.sql("INSTALL ducklake") |
| 54 | + conn.sql("LOAD ducklake") |
| 55 | + |
| 56 | + endpoint, use_ssl = normalize_endpoint(config["DUCKLAKE_DATA_ENDPOINT"]) |
| 57 | + conn.sql(f"SET s3_endpoint='{escape(endpoint)}'") |
| 58 | + conn.sql(f"SET s3_use_ssl={'true' if use_ssl else 'false'}") |
| 59 | + conn.sql(f"SET s3_access_key_id='{escape(config['DUCKLAKE_S3_ACCESS_KEY'])}'") |
| 60 | + conn.sql(f"SET s3_secret_access_key='{escape(config['DUCKLAKE_S3_SECRET_KEY'])}'") |
| 61 | + |
| 62 | + |
| 63 | +def attach_catalog( |
| 64 | + conn: duckdb.DuckDBPyConnection, |
| 65 | + config: dict[str, str], |
| 66 | + *, |
| 67 | + alias: str = "ducklake_dev", |
| 68 | +) -> None: |
| 69 | + if not alias.replace("_", "a").isalnum(): |
| 70 | + raise ValueError(f"Unsupported DuckLake alias '{alias}'") |
| 71 | + |
| 72 | + data_path = f"s3://{config['DUCKLAKE_DATA_BUCKET'].rstrip('/')}/" |
| 73 | + conn.sql(f"ATTACH '{escape(config['DUCKLAKE_CATALOG_DSN'])}' " f"AS {alias} (DATA_PATH '{escape(data_path)}')") |
| 74 | + |
| 75 | + |
| 76 | +def run_smoke_check(conn: duckdb.DuckDBPyConnection, *, alias: str = "ducklake_dev") -> None: |
| 77 | + conn.sql(f"SHOW TABLES FROM {alias}") |
| 78 | + |
| 79 | + |
| 80 | +def _strip_postgres_prefix(raw_dsn: str) -> str: |
| 81 | + for prefix in ("ducklake:postgres:", "postgres:"): |
| 82 | + if raw_dsn.startswith(prefix): |
| 83 | + return raw_dsn[len(prefix) :] |
| 84 | + return raw_dsn |
| 85 | + |
| 86 | + |
| 87 | +def parse_postgres_dsn(raw_dsn: str) -> dict[str, str]: |
| 88 | + cleaned = _strip_postgres_prefix(raw_dsn or "") |
| 89 | + params: dict[str, str] = {} |
| 90 | + for chunk in cleaned.split(): |
| 91 | + if "=" not in chunk: |
| 92 | + continue |
| 93 | + key, value = chunk.split("=", 1) |
| 94 | + params[key] = value.strip("'\"") |
| 95 | + return params |
| 96 | + |
| 97 | + |
| 98 | +def ensure_ducklake_catalog(config: dict[str, str]) -> None: |
| 99 | + params = parse_postgres_dsn(config["DUCKLAKE_CATALOG_DSN"]) |
| 100 | + target_db = params.get("dbname") |
| 101 | + if not target_db: |
| 102 | + raise ValueError("DUCKLAKE_CATALOG_DSN must include a dbname value") |
| 103 | + |
| 104 | + conn_kwargs = { |
| 105 | + "dbname": params.get("maintenance_db") or "postgres", |
| 106 | + "host": params.get("host", "localhost"), |
| 107 | + "port": int(params.get("port", "5432")), |
| 108 | + "user": params.get("user", "posthog"), |
| 109 | + "password": params.get("password", "posthog"), |
| 110 | + "autocommit": True, |
| 111 | + } |
| 112 | + |
| 113 | + try: |
| 114 | + with psycopg.connect(**conn_kwargs) as conn: |
| 115 | + with conn.cursor() as cur: |
| 116 | + cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,)) |
| 117 | + if cur.fetchone(): |
| 118 | + return |
| 119 | + |
| 120 | + cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(target_db))) |
| 121 | + owner = params.get("user") |
| 122 | + if owner: |
| 123 | + cur.execute( |
| 124 | + sql.SQL("GRANT ALL PRIVILEGES ON DATABASE {} TO {}").format( |
| 125 | + sql.Identifier(target_db), |
| 126 | + sql.Identifier(owner), |
| 127 | + ) |
| 128 | + ) |
| 129 | + except psycopg.OperationalError as exc: # pragma: no cover - depends on PG state |
| 130 | + raise RuntimeError("Unable to ensure DuckLake catalog exists. Is Postgres running and accessible?") from exc |
| 131 | + |
| 132 | + |
| 133 | +def initialize_ducklake(config: dict[str, str], *, alias: str = "ducklake_dev") -> bool: |
| 134 | + conn = duckdb.connect() |
| 135 | + try: |
| 136 | + ensure_ducklake_catalog(config) |
| 137 | + configure_connection(conn, config, install_extension=True) |
| 138 | + try: |
| 139 | + attach_catalog(conn, config, alias=alias) |
| 140 | + attached = True |
| 141 | + except duckdb.CatalogException as exc: |
| 142 | + if alias in str(exc): |
| 143 | + attached = False |
| 144 | + else: |
| 145 | + raise |
| 146 | + run_smoke_check(conn, alias=alias) |
| 147 | + return attached |
| 148 | + finally: |
| 149 | + conn.close() |
| 150 | + |
| 151 | + |
| 152 | +__all__ = [ |
| 153 | + "attach_catalog", |
| 154 | + "configure_connection", |
| 155 | + "escape", |
| 156 | + "get_config", |
| 157 | + "ensure_ducklake_catalog", |
| 158 | + "initialize_ducklake", |
| 159 | + "normalize_endpoint", |
| 160 | + "parse_postgres_dsn", |
| 161 | + "run_smoke_check", |
| 162 | +] |
0 commit comments