Files
turso/testing/sqltest/docs/cli-usage.md
Claude 6bcb8e6def sqltest: add a postgres backend that runs tests on a real PostgreSQL server
The PostgreSQL corpus must expect only what PostgreSQL itself does, but
until now it ran only against tursopg. An expectation that only tursopg
meets passed CI, and nothing showed that it was wrong.

`--backend postgres --postgres-dsn <url>` runs the tests on the server at
the URL. For each test, the backend creates a new database from
template0 and drops it after the test, so tests stay isolated when they
run in parallel. At most four CREATE DATABASE and DROP DATABASE
statements run at the same time, so a run uses at most --jobs + 4
connections. A random part in the database names lets two runs share
one server.

`@skip-if postgres "reason"` and `@skip-file-if postgres "reason"` skip
tests of Turso-specific behavior on this backend. `postgres` is parsed
from an identifier, not a keyword token, so `@backend postgres` and
names such as `setup postgres` still parse.

Tests: parser and runner unit tests for the skip condition, and the
pg-sqltests corpus against PostgreSQL 17

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R3hzXhfjBgyLPUF7vd3PHW
2026-10-15 03:04:08 +00:00

7.9 KiB

CLI Usage

This document describes the command-line interface for the test runner.

Installation

# Build from source
cargo build --release

# The binary will be at:
./target/release/sqltest

Commands

run - Execute Tests

Run SQL tests from files or directories.

sqltest run <PATHS>... [OPTIONS]

Arguments

  • <PATHS>... - One or more test files (.sqltest) or directories to scan

Options

Option Short Default Description
--backend <NAME> rust Where the tests run: rust, cli, js, tursopg, or postgres (see Backends)
--binary <PATH> tursodb Path to the tursodb CLI binary
--filter <PATTERN> -f Filter tests by name (glob pattern)
--jobs <N> -j CPU count Maximum concurrent test jobs
--output <FORMAT> -o pretty Output format: pretty or json
--timeout <SECS> 30 Timeout per query in seconds
--postgres-dsn <URL> With --backend postgres: the URL of the PostgreSQL server, for example postgres://sqltest@127.0.0.1:5432/postgres

Backends

Backend Runs the tests on
rust The Turso Rust bindings, in the runner process
cli A tursodb (or sqlite3) process that --binary names
js The Turso JavaScript bindings, in a Node.js process
tursopg A tursopg server that --binary names. The runner starts one server for each test database.
postgres The real PostgreSQL server at --postgres-dsn

Examples

# Run all tests in a directory
sqltest run sqlite/conformance/sqlite-sqltests/

# Run a specific test file
sqltest run sqlite/conformance/sqlite-sqltests/select.sqltest

# Run multiple paths
sqltest run sqlite/conformance/sqlite-sqltests/select.sqltest sqlite/conformance/sqlite-sqltests/insert/

# Custom binary path
sqltest run sqlite/conformance/sqlite-sqltests/ --binary ./target/release/tursodb

# Filter by test name
sqltest run sqlite/conformance/sqlite-sqltests/ -f "select-*"
sqltest run sqlite/conformance/sqlite-sqltests/ -f "*-join-*"

# Limit concurrent jobs
sqltest run sqlite/conformance/sqlite-sqltests/ -j 4

# JSON output for CI
sqltest run sqlite/conformance/sqlite-sqltests/ -o json

# Run the PostgreSQL corpus against a real PostgreSQL server
sqltest run postgres/conformance/pg-sqltests/ --backend postgres \
    --postgres-dsn postgres://sqltest@127.0.0.1:5432/postgres

check - Validate Syntax

Validate test file syntax without executing tests.

sqltest check <PATHS>...

Examples

# Check a single file
sqltest check sqlite/conformance/sqlite-sqltests/select.sqltest

# Check all files in a directory
sqltest check sqlite/conformance/sqlite-sqltests/

Output Formats

Pretty (Default)

Human-readable colored output with progress indication:

Running tests...

sqlite/conformance/sqlite-sqltests/select.sqltest
  [PASS] select-const-1                     (2ms)
  [PASS] select-users                       (5ms)
  [FAIL] select-join                        (3ms)
         expected: 1|Alice
         actual:   1|Bob
  [SKIP] select-buggy                       (known issue #123)

sqlite/conformance/sqlite-sqltests/insert.sqltest
  [PASS] insert-basic                       (4ms)
  [ERROR] insert-readonly                   (1ms)
          setup 'users' failed: table users already exists

Summary:
  4 passed, 1 failed, 1 skipped, 1 error
  Total time: 127ms

JSON

Machine-readable output for CI integration:

{
  "files": [
    {
      "path": "sqlite/conformance/sqlite-sqltests/select.sqltest",
      "results": [
        {
          "name": "select-const-1",
          "outcome": "passed",
          "duration_ms": 2
        },
        {
          "name": "select-join",
          "outcome": "failed",
          "reason": "expected: 1|Alice\nactual: 1|Bob",
          "duration_ms": 3
        }
      ],
      "duration_ms": 15
    }
  ],
  "summary": {
    "total": 6,
    "passed": 4,
    "failed": 1,
    "skipped": 1,
    "errors": 0,
    "duration_ms": 127
  }
}

Exit Codes

Code Meaning
0 All tests passed (or skipped)
1 One or more tests failed or errored
2 Invalid arguments or configuration error

Filter Patterns

The --filter option supports simple glob patterns:

Pattern Matches
select-* Tests starting with "select-"
*-test Tests ending with "-test"
*join* Tests containing "join"
select-const-1 Exact match

Environment Variables

Variable Description
TURSO_TEST_BINARY Default path to tursodb binary (overridden by --binary)
NO_COLOR Disable colored output

CI Integration

GitHub Actions

- name: Run SQL tests
  run: |
    sqltest run sqlite/conformance/sqlite-sqltests/ \
      --binary ./target/release/tursodb \
      --output json \
      > test-results.json

- name: Upload results
  uses: actions/upload-artifact@v3
  with:
    name: test-results
    path: test-results.json

Exit on First Failure

Currently, all tests run to completion. A --fail-fast option may be added in the future.

Performance Tips

  1. Increase parallelism: Use -j to match your CPU count for maximum throughput
  2. Use filters during development: Run only relevant tests with -f
  3. Prefer :memory: databases: In-memory databases are faster than temp files
  4. Batch queries in setups: Combine multiple setup statements into one block

Implementation Details

CLI Argument Parsing (src/main.rs)

Uses clap with derive macros for argument parsing:

#[derive(Parser)]
#[command(name = "sqltest")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Run { /* ... */ },
    Check { /* ... */ },
}

Main Entry Point

The main function is async using #[tokio::main]:

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    match cli.command {
        Commands::Run { .. } => run_tests(...).await,
        Commands::Check { paths } => check_files(paths),
    }
}

Output Module (src/output/)

The output module provides a trait-based abstraction for formatting:

pub trait OutputFormat {
    fn write_test(&mut self, result: &TestResult);
    fn write_file(&mut self, result: &FileResult);
    fn write_summary(&mut self, summary: &RunSummary);
    fn flush(&mut self);
}

pub enum Format {
    Pretty,
    Json,
}

Pretty Output (src/output/pretty.rs)

  • Uses colored crate for terminal colors
  • Groups output by file
  • Shows colored status symbols: green PASS, red FAIL, yellow SKIP, red bold ERROR
  • Displays failure reasons inline
  • Respects NO_COLOR environment variable

JSON Output (src/output/json.rs)

  • Uses serde and serde_json for serialization
  • Collects all results then outputs at summary time
  • Includes structured file/test/summary hierarchy
  • Skips reason field when null (using #[serde(skip_serializing_if)])

Integration Flow

1. Parse CLI arguments (clap)
2. Create CliBackend with binary path and timeout
3. Create RunnerConfig with jobs and filter
4. Create TestRunner<CliBackend>
5. Call runner.run_paths(&paths)
6. Create output formatter (Pretty or Json)
7. Write file results
8. Write summary
9. Return exit code based on success

Check Command

The check command validates syntax without running tests:

fn check_files(paths: Vec<PathBuf>) -> ExitCode {
    for path in paths {
        if path.is_dir() {
            // Glob for *.sqltest and check each
        } else {
            // Parse single file
        }
    }
    // Return success if no parse errors
}

Exit Code Handling

if summary.is_success() {
    ExitCode::SUCCESS  // 0
} else {
    ExitCode::from(1)  // 1 for test failures
}
// 2 is returned for invalid arguments (before running)