The SQLCtx CLI provides tools for working with semantic layers from the terminal.

## Installation

```bash doc-validate=lint
uv tool install sqlctx
# Or add it to a project (run commands with uv run sqlctx):
uv add sqlctx
```

Optional commands need their extras: install `"sqlctx[workbench]"` for the terminal UI, `"sqlctx[api,mcp]"` for `serve`, `"sqlctx[serve]"` for PostgreSQL wire, `"sqlctx[mcp,charts]"` for MCP with charts, or `"sqlctx[lsp]"` for the language server. Use `uv tool install --upgrade "sqlctx[workbench]"` to add an extra to a global CLI installation.

## Quick Start

```bash doc-validate=lint
# Get version
sqlctx --version

# Launch workbench with your models
sqlctx workbench ./models

# Try the demo
sqlctx workbench --demo
```

```bash doc-test
uvx sqlctx --help
```

```text doc-expected-contains
Usage: sqlctx
```

## Commands

### `workbench`

Interactive TUI for exploring models, writing SQL queries, and visualizing results.

```bash doc-validate=lint
# Launch with your models
sqlctx workbench ./models

# Try demo mode
sqlctx workbench --demo

# With database connection
sqlctx workbench ./models --db data/warehouse.db

# Run without installing (using uvx)
uvx --from "sqlctx[workbench]" sqlctx workbench --demo
```

Options:
- `directory`: Directory containing semantic layer files (default: `.`)
- `--demo`: Use demo data
- `--connection`: Database connection string
- `--db`: Path to DuckDB database file

See [Workbench](workbench) for detailed guide.

### `query`

Execute SQL queries and output results as CSV.

```bash doc-validate=lint
# Query to stdout (SQL is first positional argument)
sqlctx query "SELECT orders.revenue, customers.region FROM orders"

# With explicit models directory
sqlctx query "SELECT * FROM orders" --models ./models

# Save to file
sqlctx query "SELECT * FROM orders" --output results.csv

# Show generated SQL without executing
sqlctx query "SELECT * FROM orders" --dry-run

# With database connection
sqlctx query "SELECT * FROM orders" --db data/warehouse.db
```

Options:
- SQL query (positional argument, required)
- `--models`, `-m`: Directory containing semantic layer files (default: `.`)
- `--output`, `-o`: Output file path (default: stdout)
- `--connection`: Database connection string
- `--db`: Path to DuckDB database file
- `--dry-run`: Show generated SQL without executing

### `validate`

Validate semantic layer definitions and show errors/warnings.

```bash doc-validate=lint
# Basic validation
sqlctx validate ./models

# Verbose output with detailed info
sqlctx validate ./models --verbose
```

Options:
- `--verbose`, `-v`: Show detailed validation results

### `info`

Display quick summary of the semantic layer.

```bash doc-validate=lint
sqlctx info ./models
```

Shows:
- Number of models
- List of models and their metrics
- Relationships between models

### `serve`

Serve the browser UI, HTTP API, and MCP endpoint together on port 4400:

```bash doc-validate=lint
uvx --from "sqlctx[api,mcp]" sqlctx serve ./models
```

The browser UI is at `/`, the API is under `/api`, and MCP is at `/mcp`. For API-only configuration, use `sqlctx server api`.

### `server postgres`

Start a PostgreSQL-compatible server for your semantic layer.

```bash doc-validate=lint
# Basic server
sqlctx server postgres ./models

# Custom port
sqlctx server postgres ./models --port 5433

# With authentication
sqlctx server postgres ./models --username admin --password-file .secrets/pg-password

# Demo mode
sqlctx server postgres --demo
```

Options:
- `directory`: Directory containing semantic layer files (default: `.`)
- `--port`, `-p`: Port to listen on (default: 5433)
- `--username`, `-u`: Username for authentication (optional)
- `--password-file`: Read the authentication password from a file (or `-` for stdin)
- `--demo`: Use demo data
- `--connection`: Database connection string
- `--db`: Path to DuckDB database file

Connect with any PostgreSQL client:

```bash doc-validate=lint
# psql
psql -h 127.0.0.1 -p 5433 -U admin -d sqlctx

# DBeaver, Tableau, Power BI, etc.
# Host: 127.0.0.1
# Port: 5433
# Database: sqlctx
```

The server exposes:
- Models as tables in `semantic_layer` schema
- Dimensions and metrics as columns
- Full semantic layer query rewriting
- PostgreSQL catalog compatibility

### `server mcp`

Start a Model Context Protocol (MCP) server for AI integration.

```bash doc-validate=lint
# Serve your models
sqlctx server mcp ./models

# With DuckDB database
sqlctx server mcp ./models --db data/warehouse.db

# Demo mode
sqlctx server mcp --demo
```

Options:
- `--db`: Path to DuckDB database file
- `--demo`: Use demo data

The MCP server provides:
- `get_semantic_graph`: Discover models, fields, and relationships
- `get_models`: Get detailed model information
- `run_query`: Execute SQL queries
- `create_chart`: Generate charts from semantic queries

Configure in Claude Desktop:

```json doc-validate=lint
{
  "mcpServers": {
    "sqlctx": {
      "command": "sqlctx",
      "args": ["server", "mcp", "./models"]
    }
  }
}
```

### `migrate`

Generate model definitions from existing SQL queries or analyze query coverage.

```bash doc-validate=lint
# Generate models from SQL queries
sqlctx migrate generate queries/ --output output/

# Coverage analysis against existing models
sqlctx migrate check queries/ --models ./models --verbose
```

Options:
- `QUERIES`: SQL file or directory (defaults to project `queries/`)
- `generate --output`, `-o`: Output project root
- `check --models`, `-m`: Models used for coverage analysis
- `check --verbose`, `-v`: Detailed analysis

### `lsp`

Start the Language Server Protocol (LSP) server for SQLCtx SQL dialect.

```bash doc-validate=lint
sqlctx lsp  # Starts server on stdio
```

The LSP server provides:
- Autocompletion for MODEL, DIMENSION, METRIC, RELATIONSHIP, SEGMENT
- Context-aware property suggestions
- Validation errors from pydantic models
- Hover documentation

### `preagg`

Pre-aggregation management commands.

#### `preagg recommend`

Show pre-aggregation recommendations based on query patterns.

```bash doc-validate=lint
# From database query history
sqlctx preagg recommend --connection "bigquery://project/dataset"

# From DuckDB with options
sqlctx preagg recommend --db data.db --min-count 50 --top 10

# From SQL query files
sqlctx preagg recommend --queries queries.sql --min-score 0.5
```

Options:
- `--queries`, `-q`: Path to file/folder with SQL queries
- `--connection`: Database connection string to fetch query history
- `--db`: Path to DuckDB database file
- `--days`, `-d`: Days of query history to fetch (default: 7)
- `--limit`, `-l`: Max queries to analyze (default: 1000)
- `--min-count`: Minimum query count for recommendation (default: 10)
- `--min-score`: Minimum benefit score 0-1 (default: 0.3)
- `--top`, `-n`: Show only top N recommendations

#### `preagg apply`

Apply pre-aggregation recommendations to model YAML files.

```bash doc-validate=lint
sqlctx preagg apply ./models --connection "bigquery://project/dataset"
sqlctx preagg apply ./models --db data.db --top 5
sqlctx preagg apply ./models --queries queries.sql --dry-run
```

Options: Same as `recommend` plus:
- `directory`: Directory containing semantic layer YAML files (default: `.`)
- `--dry-run`: Show what would be added without writing files

#### `preagg refresh`

Refresh pre-aggregation tables.

```bash doc-validate=lint
sqlctx preagg refresh ./models --db data.db
sqlctx preagg refresh ./models --db data.db --model orders --mode full
sqlctx preagg refresh ./models --connection "postgres://localhost:5432/db"
```

Options:
- `directory`: Directory containing semantic layer files (default: `.`)
- `--model`, `-m`: Only refresh pre-aggregations for this model
- `--preagg`, `-p`: Only refresh this specific pre-aggregation
- `--mode`: Refresh mode: `full`, `incremental`, or `merge` (default: incremental)
- `--connection`: Database connection string
- `--db`: Path to DuckDB database file

## Configuration

The CLI can use a configuration file for default settings:

```bash doc-validate=lint
# Specify config file
sqlctx --config sqlctx.yaml COMMAND

# Or auto-discover sqlctx.yaml/sqlctx.json in current directory
```

## Shell Completion

Install completion for your shell:

```bash doc-validate=lint
sqlctx --install-completion
```

Supports bash, zsh, fish, and PowerShell.

## Next Steps

- [Workbench](workbench) - Interactive TUI guide
- [Query](query) - Query syntax reference
- [Python API](python-api) - Programmatic usage