SQLCtx supports multiple database engines for executing semantic layer queries. Connection strings are specified in your YAML configuration files or via CLI flags.

## Supported Databases

| Database | Production Ready | Notes |
|----------|:----------------:|-------|
| **DuckDB** | ✅ | Default, fully supported |
| **MotherDuck** | ✅ | Cloud DuckDB, fully supported |
| **PostgreSQL** | ✅ | Full feature support |
| **BigQuery** | ✅ | Google Cloud Platform |
| **Snowflake** | ✅ | Cloud data warehouse |
| **ClickHouse** | ✅ | OLAP database |
| **Databricks** | ✅ | Lakehouse platform |
| **Spark SQL** | ✅ | Apache Spark (via Thrift server) |

## Connection String Format

### In `sqlctx.yaml` (CLI config file)

Set a default connection for CLI commands:

```yaml doc-validate=config
# sqlctx.yaml
models_dir: ./models
connection:
  type: duckdb
  path: /path/to/database.duckdb
```

### With CLI

Override connection via `--connection` flag:

```bash doc-validate=lint
# Query command
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "postgres://localhost:5432/db"

# Workbench
sqlctx workbench models/ --connection "bigquery://project/dataset"

# PostgreSQL server
sqlctx server postgres models/ --connection "snowflake://account/db/schema"
```

## Database-Specific Configuration

### DuckDB (Default)

No installation required.

**In-memory (default):**
```text doc-validate=skip
duckdb:///:memory:
```

**Persistent file:**
```text doc-validate=skip
duckdb:///data/analytics.duckdb
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT * FROM orders" \
  --models ./models \
  --connection "duckdb:///data.duckdb"
```

**Query parameters:**

DuckDB URLs can include query parameters. `read_only=true` opens the database read-only. Any other params are passed to DuckDB config:

```text doc-validate=skip
duckdb:///data/analytics.duckdb?read_only=true
duckdb:///data/analytics.duckdb?threads=4
```

### MotherDuck

Cloud DuckDB with no additional installation required (uses DuckDB client).

**Format:**
```text doc-validate=skip
duckdb://md:database_name
```

**Example:**
```text doc-validate=skip
duckdb://md:my_analytics_db
```

**Authentication:**

Set your MotherDuck service token as an environment variable:
```bash doc-validate=lint
export MOTHERDUCK_TOKEN=your_service_token_here
```

Get your token from [motherduck.com](https://motherduck.com).

**CLI example:**
```bash doc-validate=lint
export MOTHERDUCK_TOKEN=your_token
sqlctx query "SELECT * FROM orders" \
  --models ./models \
  --connection "duckdb://md:my_db"
```

**Features:**

- Cloud-native DuckDB with data persistence
- Share databases across teams
- Access from anywhere
- Same DuckDB SQL syntax and features
- Automatic scaling

**See also:** [MotherDuck example](https://github.com/sidequery/sqlctx/tree/main/examples/motherduck)

### PostgreSQL

Install: `uv add "sqlctx[postgres]"`

**Basic:**
```text doc-validate=skip
postgres://username:password@host:port/database
```

**Example:**
```text doc-validate=skip
postgres://analyst:secret@localhost:5432/analytics
```

**With SSL:**
```text doc-validate=skip
postgres://user:pass@db.example.com:5432/analytics?sslmode=require
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "postgres://analyst:secret@localhost:5432/analytics"
```

**Features:**

- Full semantic layer support
- Symmetric aggregates for fan-out joins
- Arrow format for performance

### BigQuery

Install: `uv add "sqlctx[bigquery]"`

**Format:**
```text doc-validate=skip
bigquery://project-id/dataset-id
```

**Example:**
```text doc-validate=skip
bigquery://my-gcp-project/analytics_dataset
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "bigquery://my-project/my-dataset"
```

**Authentication:**

Local development:
```bash doc-validate=lint
gcloud auth application-default login
```

Service account:
```bash doc-validate=lint
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
```

**Features:**

- Full semantic layer support
- Uses FARM_FINGERPRINT for symmetric aggregates
- Arrow format via BigQuery Storage API

### Snowflake

Install: `uv add "sqlctx[snowflake]"`

**Format:**
```text doc-validate=skip
snowflake://user:password@account/database/schema?warehouse=wh&role=role
```

**Example:**
```text doc-validate=skip
snowflake://analyst:pass@xy12345.us-east-1/ANALYTICS/PUBLIC?warehouse=COMPUTE_WH&role=ANALYST
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "snowflake://user:pass@account/db/schema?warehouse=wh"
```

**Parameters:**

- `account`: Snowflake account (e.g., `xy12345.us-east-1`)
- `database`: Database name
- `schema`: Schema name
- `warehouse`: Compute warehouse (query parameter)
- `role`: Role to use (query parameter)

**Features:**

- Full semantic layer support
- Optimized symmetric aggregates
- Arrow format for performance

### ClickHouse

Install: `uv add "sqlctx[clickhouse]"`

**Format:**
```text doc-validate=skip
clickhouse://user:password@host:port/database
```

**Example:**
```text doc-validate=skip
clickhouse://default:clickhouse@localhost:8123/default
```

**With SSL:**
```text doc-validate=skip
clickhouse://user:pass@host:8443/db?secure=true
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "clickhouse://default:clickhouse@localhost:8123/default"
```

**Features:**

- Full semantic layer support
- Uses halfMD5 for symmetric aggregates
- Optimized for OLAP workloads

### Databricks

Install: `uv add "sqlctx[databricks]"`

**Format:**
```text doc-validate=skip
databricks://token@server-hostname/http-path?catalog=catalog&schema=schema
```

**Example:**
```text doc-validate=skip
databricks://dapi12345@dbc-a1b2c3d4.cloud.databricks.com/sql/1.0/warehouses/abc123?catalog=main&schema=default
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "databricks://dapi123@server/sql/1.0/warehouses/abc?catalog=main"
```

**Parameters:**

- `token`: Personal access token (as username in URL)
- `server-hostname`: Databricks workspace URL
- `http-path`: SQL warehouse HTTP path
- `catalog`: Unity Catalog (query parameter)
- `schema`: Schema name (query parameter)

**Features:**

- Full semantic layer support
- Uses xxhash64 for symmetric aggregates
- Optimized for lakehouse queries

### Spark SQL

Install: `uv add "sqlctx[spark]"`

**Format:**
```text doc-validate=skip
spark://host:port/database
```

**Example:**
```text doc-validate=skip
spark://localhost:10000/default
```

**With authentication:**
```text doc-validate=skip
spark://username:password@host:10000/database
```

**CLI example:**
```bash doc-validate=lint
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "spark://localhost:10000/default"
```

**Requirements:**

- Spark Thrift server must be running
- Uses HiveServer2 protocol

**Features:**

- Full semantic layer support
- Uses xxhash64 for symmetric aggregates
- Compatible with Apache Spark 3.x

## Environment Variables

Store credentials in environment variables for security. Never commit credentials to version control.

Environment variables can be used in:
- **YAML configuration files** - Using `${VAR}` syntax
- **CLI flags** - Using shell variables like `$VAR`

### In YAML Files

SQLCtx supports environment variable substitution in YAML files using standard syntax:

**Syntax:**
- `${ENV_VAR}` - Substituted with environment variable value
- `${ENV_VAR:-default}` - Use default if variable not set
- `$ENV_VAR` - Simple form (uppercase variables only)

**Example YAML:**
```yaml doc-validate=semantic
# semantic_layer.yml
models:
  - name: orders
    table: ${SCHEMA_NAME:-public}.orders
    primary_key: order_id
```

**Set environment variables:**
```bash doc-validate=lint
export SCHEMA_NAME=prod
```

**Load configuration:**
```bash doc-validate=lint
sqlctx validate ./models
```

The environment variables are substituted when the YAML file is loaded.

### In CLI Flags

Use shell environment variables in CLI commands:

```bash doc-validate=lint
export DATABASE_URL=postgres://user:pass@localhost:5432/analytics

sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "$DATABASE_URL"
```

### Full Connection Strings

Store complete connection string in an environment variable:

**Example .env file:**
```bash doc-validate=lint
# PostgreSQL
DATABASE_URL=postgres://user:pass@localhost:5432/analytics

# BigQuery
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
BIGQUERY_URL=bigquery://my-project/my-dataset

# Snowflake
SNOWFLAKE_URL=snowflake://user:pass@account/db/schema?warehouse=wh

# ClickHouse
CLICKHOUSE_URL=clickhouse://user:pass@localhost:8123/default

# Databricks
DATABRICKS_URL=databricks://token@server/http-path?catalog=main

# Spark
SPARK_URL=spark://localhost:10000/default
```

**Use with CLI:**
```bash doc-validate=lint
# Load .env file (many tools auto-load)
export $(cat .env | xargs)

# Use environment variable
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "$DATABASE_URL"

sqlctx workbench models/ --connection "$SNOWFLAKE_URL"

sqlctx server postgres models/ --connection "$BIGQUERY_URL"
```

### Component Environment Variables

Build connection strings from individual components:

**Example .env file:**
```bash doc-validate=lint
# PostgreSQL components
POSTGRES_HOST=db.example.com
POSTGRES_PORT=5432
POSTGRES_USER=analyst
POSTGRES_PASSWORD=secret
POSTGRES_DB=analytics

# Snowflake components
SNOWFLAKE_ACCOUNT=xy12345.us-east-1
SNOWFLAKE_USER=analyst
SNOWFLAKE_PASSWORD=secret
SNOWFLAKE_DATABASE=ANALYTICS
SNOWFLAKE_SCHEMA=PUBLIC
SNOWFLAKE_WAREHOUSE=COMPUTE_WH

# BigQuery components
BIGQUERY_PROJECT=my-gcp-project
BIGQUERY_DATASET=analytics_dataset
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
```

**Build connection string in shell:**
```bash doc-validate=lint
# PostgreSQL
CONNECTION="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
sqlctx query "SELECT orders.revenue FROM orders" --models ./models --connection "$CONNECTION"

# Snowflake
CONNECTION="snowflake://${SNOWFLAKE_USER}:${SNOWFLAKE_PASSWORD}@${SNOWFLAKE_ACCOUNT}/${SNOWFLAKE_DATABASE}/${SNOWFLAKE_SCHEMA}?warehouse=${SNOWFLAKE_WAREHOUSE}"
sqlctx workbench models/ --connection "$CONNECTION"

# BigQuery
CONNECTION="bigquery://${BIGQUERY_PROJECT}/${BIGQUERY_DATASET}"
sqlctx server postgres models/ --connection "$CONNECTION"
```

### Security Best Practices

**Never commit credentials:**
```bash doc-validate=lint
# Add to .gitignore
echo ".env" >> .gitignore
echo "*.secrets" >> .gitignore
```

**Use secret management:**
```bash doc-validate=lint
# AWS Secrets Manager
export DATABASE_URL=$(aws secretsmanager get-secret-value \
  --secret-id prod/database-url \
  --query SecretString \
  --output text)

# Google Secret Manager
export DATABASE_URL=$(gcloud secrets versions access latest \
  --secret="database-url")

# HashiCorp Vault
export DATABASE_URL=$(vault kv get -field=url secret/database)
```

**Restrict file permissions:**
```bash doc-validate=lint
chmod 600 .env
```

### Per-Environment Configuration

**Development:**
```bash doc-validate=lint
# .env.development
DATABASE_URL=duckdb:///dev.duckdb
```

**Staging:**
```bash doc-validate=lint
# .env.staging
DATABASE_URL=postgres://user:pass@staging-db:5432/analytics
```

**Production:**
```bash doc-validate=lint
# .env.production
DATABASE_URL=snowflake://user:pass@prod-account/db/schema?warehouse=wh
```

**Load based on environment:**
```bash doc-validate=lint
ENV=${ENV:-development}
export $(cat .env.${ENV} | xargs)

sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "$DATABASE_URL"
```

## Testing Connections

Test your connection string:

```bash doc-validate=lint
# Create a simple test model
cat > test.yml <<EOF
models:
  - name: test
    sql: |
      select 1 as id, 100 as value
    primary_key: id
    metrics:
      - name: total
        agg: sum
        sql: value
EOF

# Run a query
sqlctx query "SELECT test.total FROM test" --models . --connection "duckdb:///:memory:"
# Should output: 100
```

```yaml doc-file=models/test.yml
models:
  - name: test
    sql: |
      select 1 as id, 100 as value
    primary_key: id
    metrics:
      - name: total
        agg: sum
        sql: value
```

```bash doc-test
uvx sqlctx query "SELECT test.total FROM test" --models ./models --connection "duckdb:///:memory:"
```

```csv doc-expected
total
100
```

## CLI Connection Examples

### Query Command

```bash doc-validate=lint
# DuckDB file
sqlctx query "SELECT orders.revenue FROM orders" \
  --models ./models \
  --connection "duckdb:///data.duckdb"

# PostgreSQL
sqlctx query "SELECT orders.revenue, orders.status FROM orders" \
  --models ./models \
  --connection "postgres://localhost:5432/analytics"

# BigQuery
sqlctx query "SELECT orders.revenue FROM orders WHERE orders.status = 'completed'" \
  --models ./models \
  --connection "bigquery://my-project/analytics"
```

### Workbench

```bash doc-validate=lint
# Local DuckDB
sqlctx workbench models/ --connection "duckdb:///warehouse.duckdb"

# Snowflake
sqlctx workbench models/ \
  --connection "snowflake://user:pass@account/db/schema"

# ClickHouse
sqlctx workbench models/ \
  --connection "clickhouse://localhost:8123/default"
```

### PostgreSQL Server

```bash doc-validate=lint
# Serve DuckDB over PostgreSQL protocol
sqlctx server postgres models/ \
  --connection "duckdb:///data.duckdb" \
  --port 5433

# Serve BigQuery over PostgreSQL protocol
sqlctx server postgres models/ \
  --connection "bigquery://project/dataset" \
  --port 5433 \
  --username admin \
  --password-file .secrets/pg-password
```

## Troubleshooting

### Connection Errors

**PostgreSQL:**
```
psycopg.OperationalError: connection failed
```

- Verify host, port, username, password
- Check PostgreSQL is running
- Test with `psql` first: `psql -h host -p 5432 -U user -d database`

**BigQuery:**
```
google.auth.exceptions.DefaultCredentialsError
```

- Run `gcloud auth application-default login`
- Or set `GOOGLE_APPLICATION_CREDENTIALS` environment variable

**Snowflake:**
```
snowflake.connector.errors.DatabaseError: 250001
```

- Verify account identifier format
- Check username/password
- Ensure warehouse is running

### Invalid Connection String

```
ValueError: Unsupported connection URL
```

- Check connection string format matches examples above
- Ensure required extras installed: `uv add "sqlctx[postgres]"` (replace `postgres` with your warehouse extra)

## Related Documentation

- **[Configuration](config)** - General YAML configuration options
- **[CLI](cli)** - CLI commands and flags
- **[Quickstart](getting-started)** - Installation and setup