Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions examples/loader-connectorx/.env.example
Original file line number Diff line number Diff line change
@@ -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"
10 changes: 10 additions & 0 deletions examples/loader-connectorx/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.env
.venv/
node_modules/
dist/
src/.observablehq/
__pycache__/
*.pyc
data/*.db
data/*.sqlite
package-lock.json
76 changes: 76 additions & 0 deletions examples/loader-connectorx/README.md
Original file line number Diff line number Diff line change
@@ -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 <http://localhost:3000>.

## 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.
4 changes: 4 additions & 0 deletions examples/loader-connectorx/observablehq.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
title: "ConnectorX data loader",
root: "src"
};
21 changes: 21 additions & 0 deletions examples/loader-connectorx/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
3 changes: 3 additions & 0 deletions examples/loader-connectorx/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
connectorx>=0.4.6
pyarrow
python-dotenv
56 changes: 56 additions & 0 deletions examples/loader-connectorx/scripts/seed_sqlite.py
Original file line number Diff line number Diff line change
@@ -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)
165 changes: 165 additions & 0 deletions examples/loader-connectorx/src/data/connectorx_helper.py
Original file line number Diff line number Diff line change
@@ -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()
Loading