From 47aca82e517fe1a4b6ee4f9308226fd2d218e6f9 Mon Sep 17 00:00:00 2001 From: Giacomo Saccaggi Date: Wed, 2 Dec 2026 12:29:32 +0100 Subject: [PATCH] Add ConnectorX data loader example --- examples/README.md | 1 + examples/loader-connectorx/.env.example | 22 +++ examples/loader-connectorx/.gitignore | 10 ++ examples/loader-connectorx/README.md | 76 ++++++++ .../loader-connectorx/observablehq.config.js | 4 + examples/loader-connectorx/package.json | 21 +++ examples/loader-connectorx/requirements.txt | 3 + .../loader-connectorx/scripts/seed_sqlite.py | 56 ++++++ .../src/data/connectorx_helper.py | 165 ++++++++++++++++++ .../src/data/orders.parquet.py | 67 +++++++ examples/loader-connectorx/src/index.md | 91 ++++++++++ 11 files changed, 516 insertions(+) create mode 100644 examples/loader-connectorx/.env.example create mode 100644 examples/loader-connectorx/.gitignore create mode 100644 examples/loader-connectorx/README.md create mode 100644 examples/loader-connectorx/observablehq.config.js create mode 100644 examples/loader-connectorx/package.json create mode 100644 examples/loader-connectorx/requirements.txt create mode 100644 examples/loader-connectorx/scripts/seed_sqlite.py create mode 100644 examples/loader-connectorx/src/data/connectorx_helper.py create mode 100644 examples/loader-connectorx/src/data/orders.parquet.py create mode 100644 examples/loader-connectorx/src/index.md diff --git a/examples/README.md b/examples/README.md index 22a5f461d..57cd609ba 100644 --- a/examples/README.md +++ b/examples/README.md @@ -57,6 +57,7 @@ - [`loader-bigquery`](https://observablehq.observablehq.cloud/framework-example-loader-google-bigquery/) - Load data from Google BigQuery - [`loader-canvas-to-png`](https://observablehq.observablehq.cloud/framework-example-loader-canvas-to-png/) - Generate PNG using node-canvas - [`loader-census`](https://observablehq.observablehq.cloud/framework-example-loader-census/) - Load and transform shapefiles from the U.S. Census Bureau +- [`loader-connectorx`](./loader-connectorx) - Load SQL database data (Trino, PostgreSQL, SQLite, and more) to Apache Parquet with ConnectorX. - [`loader-databricks`](https://observablehq.observablehq.cloud/framework-example-loader-databricks/) - Load data from Databricks - [`loader-duckdb`](https://observablehq.observablehq.cloud/framework-example-loader-duckdb/) - Process data with DuckDB - [`loader-elasticsearch`](https://observablehq.observablehq.cloud/framework-example-loader-elasticsearch/) - Load data from Elasticsearch diff --git a/examples/loader-connectorx/.env.example b/examples/loader-connectorx/.env.example new file mode 100644 index 000000000..021253223 --- /dev/null +++ b/examples/loader-connectorx/.env.example @@ -0,0 +1,22 @@ +# ConnectorX connection URI (uncomment ONE source below) + +# --- Local reproducible demo (run `python3 scripts/seed_sqlite.py` first) --- +CONNECTORX_URI="sqlite://data/demo.db" + +# --- Trino over HTTPS (basic auth requires TLS on Trino) --- +# CONNECTORX_URI="trino+https://username:password@trino.example.com:8443/tpch" +# Self-signed TLS certificate on Trino (supported in connectorx>=0.4.6): +# CONNECTORX_URI="trino+https://username:password@trino.example.com:8443/tpch?verify=false" +# Trino over HTTP without TLS (no basic auth): +# CONNECTORX_URI="trino+http://localhost:8080/tpch" + +# --- PostgreSQL / Amazon Redshift --- +# CONNECTORX_URI="postgresql://username:password@localhost:5432/mydb?sslmode=require" +# CONNECTORX_URI="redshift://username:password@cluster.example.com:5439/mydb" + +# --- Optional: Parquet compression (zstd, snappy, gzip, brotli, lz4_raw, none) --- +CONNECTORX_PARQUET_COMPRESSION="zstd" + +# --- Optional: Parallel partitioning (non-NULL numeric column, no LIMIT+ORDER BY) --- +# CONNECTORX_PARTITION_ON="order_id" +# CONNECTORX_PARTITION_NUM="4" diff --git a/examples/loader-connectorx/.gitignore b/examples/loader-connectorx/.gitignore new file mode 100644 index 000000000..93fd91bb5 --- /dev/null +++ b/examples/loader-connectorx/.gitignore @@ -0,0 +1,10 @@ +.env +.venv/ +node_modules/ +dist/ +src/.observablehq/ +__pycache__/ +*.pyc +data/*.db +data/*.sqlite +package-lock.json diff --git a/examples/loader-connectorx/README.md b/examples/loader-connectorx/README.md new file mode 100644 index 000000000..796a8f384 --- /dev/null +++ b/examples/loader-connectorx/README.md @@ -0,0 +1,76 @@ +[Framework examples →](../) + +# ConnectorX data loader + +This Observable Framework example demonstrates how to write a Python data loader that uses [ConnectorX](https://github.com/sfu-db/connector-x) to query SQL databases and output an [Apache Parquet](https://parquet.apache.org/) file using [PyArrow](https://pypi.org/project/pyarrow/). The loader lives in [`src/data/orders.parquet.py`](./src/data/orders.parquet.py). + +ConnectorX supports Trino, PostgreSQL, Redshift, MySQL, SQL Server, Oracle, BigQuery, ClickHouse, and SQLite. This example ships with a local SQLite demo database for zero-configuration local development. + +## Prerequisites + +- [Node.js](https://nodejs.org/) ≥ 18 +- Python ≥ 3.11 (ConnectorX 0.4.6 requires ≥ 3.10; 3.11+ recommended) +- `venv` (stdlib) or [`uv`](https://github.com/astral-sh/uv) + +## Quickstart — local SQLite demo + +```bash +# 1. Create a virtual environment and install dependencies +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements.txt + +# 2. Seed the demo database and configure the environment +python3 scripts/seed_sqlite.py +cp .env.example .env + +# 3. Install Node.js dependencies and start the dev server +npm install +npm run dev +``` + +The dev server runs at . + +## Trino + +Set `CONNECTORX_URI` in your `.env` file to one of the following: + +```dotenv +# HTTPS with basic auth (requires TLS on the Trino server) +CONNECTORX_URI="trino+https://username:password@trino.example.com:8443/tpch" + +# HTTPS with self-signed certificate (connectorx>=0.4.6) +CONNECTORX_URI="trino+https://username:password@trino.example.com:8443/tpch?verify=false" + +# HTTP without TLS (no basic auth supported) +CONNECTORX_URI="trino+http://localhost:8080/tpch" +``` + +> **Note:** Trino basic auth requires HTTPS. HTTP connections do not support username/password. + +**Known caveats in connectorx 0.4.6** (fixed on `main` after 0.4.6): +- `#953`: URL-decoded credentials in Trino URIs may cause auth failures. +- `#954`: `BIGINT` columns decoded as `i64` instead of `i128` on some Trino versions. + +## Other supported databases + +| Database | URI scheme | +|----------|-----------| +| PostgreSQL | `postgresql://user:pass@host:5432/db` | +| Amazon Redshift | `redshift://user:pass@host:5439/db` | +| MySQL | `mysql://user:pass@host:3306/db` | +| SQL Server | `mssql://user:pass@host:1433/db` | +| Oracle | `oracle://user:pass@host:1521/db` | +| Google BigQuery | `bigquery://project/dataset` | +| ClickHouse | `clickhouse://user:pass@host:9000/db` | +| SQLite (local) | `sqlite://path/to/file.db` | + +## Parallel partitioning + +Set `CONNECTORX_PARTITION_ON` to a **non-NULL numeric column** and `CONNECTORX_PARTITION_NUM` to the desired number of partitions: + +```dotenv +CONNECTORX_PARTITION_ON="order_id" +CONNECTORX_PARTITION_NUM="4" +``` + +> **Important:** Do not combine `partition_on` with `LIMIT` + `ORDER BY` — this is a known ConnectorX bug (`#486`). The loader automatically removes `ORDER BY` when `partition_on` is set. Never use a nullable column for partitioning. diff --git a/examples/loader-connectorx/observablehq.config.js b/examples/loader-connectorx/observablehq.config.js new file mode 100644 index 000000000..53b336f4d --- /dev/null +++ b/examples/loader-connectorx/observablehq.config.js @@ -0,0 +1,4 @@ +export default { + title: "ConnectorX data loader", + root: "src" +}; diff --git a/examples/loader-connectorx/package.json b/examples/loader-connectorx/package.json new file mode 100644 index 000000000..64f020495 --- /dev/null +++ b/examples/loader-connectorx/package.json @@ -0,0 +1,21 @@ +{ + "type": "module", + "private": true, + "name": "framework-example-loader-connectorx", + "description": "Load SQL database data with ConnectorX and output Apache Parquet", + "scripts": { + "clean": "rimraf src/.observablehq/cache", + "build": "observable build", + "dev": "observable preview", + "observable": "observable" + }, + "dependencies": { + "@observablehq/framework": "^1.7.0" + }, + "devDependencies": { + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">=18" + } +} diff --git a/examples/loader-connectorx/requirements.txt b/examples/loader-connectorx/requirements.txt new file mode 100644 index 000000000..264b8182a --- /dev/null +++ b/examples/loader-connectorx/requirements.txt @@ -0,0 +1,3 @@ +connectorx>=0.4.6 +pyarrow +python-dotenv diff --git a/examples/loader-connectorx/scripts/seed_sqlite.py b/examples/loader-connectorx/scripts/seed_sqlite.py new file mode 100644 index 000000000..253950480 --- /dev/null +++ b/examples/loader-connectorx/scripts/seed_sqlite.py @@ -0,0 +1,56 @@ +import random +import sqlite3 +import sys +from datetime import datetime, timedelta +from pathlib import Path + +random.seed(42) + +DB_PATH = Path(__file__).resolve().parent.parent / "data" / "demo.db" +DB_PATH.parent.mkdir(parents=True, exist_ok=True) + +REGIONS = ["EMEA", "AMER", "APAC"] +CATEGORIES = ["Cloud", "Analytics", "Storage", "Compute"] + +con = sqlite3.connect(DB_PATH) +cur = con.cursor() +cur.execute("DROP TABLE IF EXISTS orders") +cur.execute( + """ + CREATE TABLE orders ( + order_id INTEGER PRIMARY KEY NOT NULL, + order_date TEXT NOT NULL, + region TEXT NOT NULL, + category TEXT NOT NULL, + revenue REAL NOT NULL, + units INTEGER NOT NULL + ) +""" +) + +START = datetime(2025, 1, 1) +END = datetime(2025, 12, 31, 23, 59, 59) +span_seconds = int((END - START).total_seconds()) + +rows = [] +for i in range(1, 601): + dt = START + timedelta(seconds=random.randint(0, span_seconds)) + rows.append( + ( + i, + dt.strftime("%Y-%m-%d %H:%M:%S"), + random.choice(REGIONS), + random.choice(CATEGORIES), + round(random.uniform(100.0, 50000.0), 2), + random.randint(1, 500), + ) + ) + +cur.executemany( + "INSERT INTO orders (order_id, order_date, region, category, revenue, units) VALUES (?,?,?,?,?,?)", + rows, +) +con.commit() +con.close() + +print(f"Created {DB_PATH} with {len(rows)} rows", file=sys.stderr) diff --git a/examples/loader-connectorx/src/data/connectorx_helper.py b/examples/loader-connectorx/src/data/connectorx_helper.py new file mode 100644 index 000000000..f114d58a0 --- /dev/null +++ b/examples/loader-connectorx/src/data/connectorx_helper.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import json +import os +import re +import sys +import urllib.parse +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any +from uuid import UUID + +import connectorx as cx +import pyarrow as pa +import pyarrow.csv as pcsv +import pyarrow.ipc as pa_ipc +import pyarrow.parquet as pq +from dotenv import load_dotenv + +_VALID_COMPRESSIONS = {"zstd", "snappy", "gzip", "brotli", "lz4_raw", "none"} + +# Matches scheme://user:password@host patterns for regex-based redaction fallback +_PASSWORD_RE = re.compile(r"(://[^:/?#]+:)([^@/?#]+)(@)") + + +def _redact(text: str) -> str: + """Apply regex-based password redaction to any string.""" + return _PASSWORD_RE.sub(r"\1***\3", text) + + +def mask_uri(uri: str) -> str: + """Replace the password in a connection URI with *** for safe logging.""" + try: + parsed = urllib.parse.urlsplit(uri) + if parsed.password: + return uri.replace(f":{parsed.password}@", ":***@") + return uri + except Exception: + return _redact(uri) + + +def normalize_conn_uri(uri: str, project_root: Path) -> str: + """Resolve sqlite:// relative paths against project_root; pass other schemes through unchanged.""" + if not uri.startswith("sqlite://"): + return uri + raw_path = uri[len("sqlite://"):] + if os.name == "nt": + # Avoid double-encoding already-percent-encoded Windows paths + if "%" in raw_path: + return uri + p = Path(raw_path) + if not p.is_absolute(): + p = (project_root / p).resolve() + return "sqlite://" + urllib.parse.quote(str(p)) + p = Path(raw_path) + if not p.is_absolute(): + p = (project_root / p).resolve() + # Percent-encode the path so ConnectorX handles spaces consistently in both + # plain and partition_on modes (ConnectorX re-encodes URIs during partitioning, + # causing unencoded spaces to become literal %20 in the filesystem path). + return "sqlite://" + urllib.parse.quote(str(p), safe="/") + + +def load_conn_uri(env_var: str = "CONNECTORX_URI") -> str: + """Load and normalize the connection URI from environment / .env file.""" + project_root = Path(__file__).resolve().parents[2] + load_dotenv(project_root / ".env", override=False) + raw_uri = os.environ.get(env_var, "").strip() + if not raw_uri: + print( + f"Error: environment variable {env_var!r} is not set.\n" + "Copy .env.example to .env and set your database URI, " + "or export the variable before running.", + file=sys.stderr, + ) + sys.exit(1) + return normalize_conn_uri(raw_uri, project_root) + + +def read_arrow( + conn_uri: str, + query: str, + *, + partition_on: str | None = None, + partition_num: int | None = None, + partition_range: tuple[int, int] | None = None, + protocol: str | None = None, +) -> pa.Table: + """Execute a SQL query via ConnectorX and return an Arrow table.""" + kwargs: dict[str, Any] = {"return_type": "arrow"} + if partition_on is not None: + kwargs["partition_on"] = partition_on + if partition_num is not None: + kwargs["partition_num"] = partition_num + if partition_range is not None: + kwargs["partition_range"] = partition_range + if protocol is not None: + kwargs["protocol"] = protocol + try: + return cx.read_sql(conn_uri, query, **kwargs) + except Exception as e: + masked_conn = mask_uri(conn_uri) + err_msg = str(e) + # Strip raw password from exception text so it never reaches stderr + try: + parsed = urllib.parse.urlsplit(conn_uri) + if parsed.password: + err_msg = err_msg.replace(parsed.password, "***") + except Exception: + pass + err_msg = _redact(err_msg) + print( + f"ConnectorX query failed on {masked_conn!r}:\n{err_msg}", + file=sys.stderr, + ) + sys.exit(1) + + +def write_parquet_stdout(table: pa.Table, compression: str = "zstd") -> None: + """Write an Arrow table as Parquet to stdout via a seekable buffer.""" + compression = compression.lower() + if compression not in _VALID_COMPRESSIONS: + raise ValueError( + f"Unsupported Parquet compression {compression!r}. " + f"Choose from: {sorted(_VALID_COMPRESSIONS)}" + ) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, compression=None if compression == "none" else compression) + sys.stdout.buffer.write(sink.getvalue().to_pybytes()) + sys.stdout.buffer.flush() + + +def write_arrow_ipc_stdout(table: pa.Table) -> None: + """Write an Arrow table as Arrow IPC stream to stdout.""" + sink = pa.BufferOutputStream() + with pa_ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + sys.stdout.buffer.write(sink.getvalue().to_pybytes()) + sys.stdout.buffer.flush() + + +def write_csv_stdout(table: pa.Table) -> None: + """Write an Arrow table as CSV to stdout.""" + sink = pa.BufferOutputStream() + pcsv.write_csv(table, sink) + sys.stdout.buffer.write(sink.getvalue().to_pybytes()) + sys.stdout.buffer.flush() + + +def _json_default(obj: Any) -> Any: + if isinstance(obj, (datetime, date)): + return obj.isoformat() + if isinstance(obj, Decimal): + return float(obj) + if isinstance(obj, UUID): + return str(obj) + return str(obj) + + +def write_json_stdout(table: pa.Table) -> None: + """Write an Arrow table as JSON array to stdout.""" + data = json.dumps(table.to_pylist(), default=_json_default) + sys.stdout.buffer.write(data.encode("utf-8")) + sys.stdout.buffer.flush() diff --git a/examples/loader-connectorx/src/data/orders.parquet.py b/examples/loader-connectorx/src/data/orders.parquet.py new file mode 100644 index 000000000..ad8c5c143 --- /dev/null +++ b/examples/loader-connectorx/src/data/orders.parquet.py @@ -0,0 +1,67 @@ +import os +import sys +import urllib.parse +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from connectorx_helper import load_conn_uri, read_arrow, write_parquet_stdout + +conn_uri = load_conn_uri() + +compression = os.environ.get("CONNECTORX_PARQUET_COMPRESSION", "zstd") + +partition_on = os.environ.get("CONNECTORX_PARTITION_ON") or None + +partition_num: int | None = None +raw_partition_num = os.environ.get("CONNECTORX_PARTITION_NUM", "").strip() +if raw_partition_num: + try: + partition_num = int(raw_partition_num) + if partition_num <= 0: + raise ValueError("must be positive") + except ValueError as e: + print( + f"Error: CONNECTORX_PARTITION_NUM={raw_partition_num!r} is invalid: {e}", + file=sys.stderr, + ) + sys.exit(1) + +# ConnectorX re-encodes SQLite URIs internally during partition splits and then +# passes the percent-encoded string as a literal filesystem path, which breaks on +# paths containing spaces. Fall back to non-partitioned mode with a clear warning. +if partition_on and conn_uri.startswith("sqlite://"): + decoded_path = urllib.parse.unquote(conn_uri[len("sqlite://"):]) + if " " in decoded_path: + print( + "Warning: ConnectorX does not support partition_on for SQLite databases " + "whose path contains spaces (re-encoding bug). " + "Falling back to non-partitioned mode.", + file=sys.stderr, + ) + partition_on = None + partition_num = None + +custom_query = os.environ.get("CONNECTORX_QUERY", "").strip() +if custom_query: + query = custom_query +elif partition_on: + # No ORDER BY when partitioning — avoids ConnectorX bug #486 + query = ( + "SELECT order_id, order_date, region, category, revenue, units " + "FROM orders" + ) +else: + query = ( + "SELECT order_id, order_date, region, category, revenue, units " + "FROM orders ORDER BY order_date" + ) + +table = read_arrow( + conn_uri, + query, + partition_on=partition_on, + partition_num=partition_num, +) + +write_parquet_stdout(table, compression=compression) diff --git a/examples/loader-connectorx/src/index.md b/examples/loader-connectorx/src/index.md new file mode 100644 index 000000000..d8b1ec837 --- /dev/null +++ b/examples/loader-connectorx/src/index.md @@ -0,0 +1,91 @@ +--- +title: ConnectorX data loader +sql: + orders: ./data/orders.parquet +--- + +# ConnectorX data loader + +Here's a Python data loader that uses [ConnectorX](https://github.com/sfu-db/connector-x) to query a SQL database and write the result as a ZSTD-compressed [Apache Parquet](https://parquet.apache.org/) file to standard output at build time. + +```python +# src/data/orders.parquet.py (simplified) +import connectorx as cx +import pyarrow as pa +import pyarrow.parquet as pq +import sys + +table = cx.read_sql(conn_uri, query, return_type="arrow") + +sink = pa.BufferOutputStream() +pq.write_table(table, sink, compression="zstd") +sys.stdout.buffer.write(sink.getvalue().to_pybytes()) +sys.stdout.buffer.flush() +``` + +ConnectorX supports **Trino**, **PostgreSQL**, **Redshift**, **MySQL**, **SQL Server**, **Oracle**, **BigQuery**, **ClickHouse**, and **SQLite** — all producing the same Arrow-native output with no pandas dependency. + +
+ +To run this data loader you'll need Python ≥ 3.11 and the packages in `requirements.txt` installed in a virtual environment. See the README for setup instructions. + +
+ +## Filter by region + +```js +const region = view(Inputs.select(["All", "EMEA", "AMER", "APAC"], {label: "Region"})); +``` + +```sql id=monthly +SELECT + date_trunc('month', order_date) AS month, + category, + SUM(revenue) AS total_revenue, + SUM(units) AS total_units +FROM orders +WHERE ${region} = 'All' OR region = ${region} +GROUP BY 1, 2 +ORDER BY 1, 2 +``` + +```js +Plot.plot({ + title: "Monthly revenue by category", + x: {label: "Month"}, + y: {label: "Revenue (USD)", grid: true}, + color: {legend: true}, + marks: [ + Plot.barY(monthly, {x: "month", y: "total_revenue", fill: "category", tip: true}), + Plot.ruleY([0]) + ] +}) +``` + +## Orders table + +The data loader lives in `src/data/orders.parquet.py`. We load it via `FileAttachment` and display it as a table. + +```js +const orders = await FileAttachment("./data/orders.parquet").parquet(); +Inputs.table(orders, { + format: { + order_date: (d) => new Date(d).toISOString().slice(0, 10), + revenue: (d) => `$${d.toFixed(2)}` + } +}) +``` + +## Configuration + +Copy `.env.example` to `.env` and set your database URI: + +```sh +# Local SQLite demo +CONNECTORX_URI="sqlite://data/demo.db" + +# Trino over HTTPS with self-signed certificate +CONNECTORX_URI="trino+https://username:password@trino.example.com:8443/tpch?verify=false" +``` + +The `.env` file is listed in `.gitignore` and will never be committed.