ChaiSQL Documentation

repository·main·Indexed 23 days ago

https://github.com/chaisql/chai

ChaiSQL is a modern, embedded SQL database written in pure Go that provides a PostgreSQL-inspired API. It implements the standard database/sql interface and supports both in-memory and disk-based storage. The project includes a CLI tool for interactive SQL shells, database dumping, restoration, and performance benchmarking. Key features include support for creating/dropping tables and indexes, basic SELECT queries, and a Pebble-based storage engine.

Tokens
5.6K
Snippets
8
Records
39
Agent score
82%

What's inside ChaiSQL

  1. Configure In-memory vs Disk-based databases

    main

    ChaiSQL supports both ephemeral in-memory storage and persistent disk-based storage via the connection string in sql.Open("chai", <connection_string>).

    • In-memory: Use :memory: for a database that exists only for the duration of the process.
    • Disk-based: Provide a directory name to persist data to disk.
  2. Quickstart: Use ChaiSQL in a Go application

    main

    ChaiSQL implements the standard database/sql interface. You can use it to create tables, insert data, and run queries using a PostgreSQL-inspired syntax.

    Note that you must import the driver with a blank identifier _ "github.com/chaisql/chai" to register it with the sql package.

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
    
        _ "github.com/chaisql/chai"
    )
    
    func main() {
        // Open an on-disk database called "mydb"
        db, err := sql.Open("chai", "mydb")
        if err != nil {
            log.Fatal(err)
        }
        defer db.Close()
    
        // Create schema
        _, err = db.Exec(`
            CREATE TABLE users (
                id          INTEGER PRIMARY KEY,
                name        TEXT NOT NULL UNIQUE,
                email       TEXT NOT NULL,
                age         INT  NOT NULL,
                created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        `)
        if err != nil {
            log.Fatal(err)
        }
    
        // Insert some data
        _, err = db.Exec(`
            INSERT INTO users (id, name, email, age)
            VALUES
                (1, 'Alice', 'alice@example.com', 30),
                (2, 'Bob',   'bob@example.com',   25),
                (3, 'Carol', 'carol@example.com', 40);
        `)
        if err != nil {
            log.Fatal(err)
        }
    
        // Query active adults
        rows, err := db.Query(`
            SELECT id, name, email, age
            FROM users
            WHERE age >= 18
            ORDER BY age DESC
        `)
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
    
        for rows.Next() {
            var id, age int
            var name, email string
            if err := rows.Scan(&id, &name, &email, &age); err != nil {
                log.Fatal(err)
            }
            fmt.Printf("User %d: %s (%s), %d years old\n", id, name, email, age)
        }
    }
  3. Install ChaiSQL driver and CLI

    main

    To use ChaiSQL in your Go projects or via the command line, install the driver and the CLI tool using go install:

    go install github.com/chaisql/chai@latest
    go install github.com/chaisql/chai/cmd/chai@latest
  4. Chai shell command syntax and execution rules

    main

    The Chai TUI distinguishes between standard SQL queries and shell commands based on the input format:

    1. Standard SQL Queries: Must end with a semicolon (;) to be executed if they are on a single line.
    2. Shell Commands: Commands starting with a dot (.) on a single line are treated as shell-specific commands (e.g., .exit).
    3. Multi-line Queries: The shell allows multi-line input; execution is triggered by the line count and syntax rules mentioned above.
  5. Use dot-commands in the Chai shell

    main

    The Chai shell supports several built-in commands that start with a . prefix. These are used for administrative tasks rather than SQL queries.

    CommandDescription
    .helpDisplays help information
    .tablesLists all tables in the database
    .indexesLists indexes (optionally for a specific table)
    .timer on/offToggles the display of execution time for queries
    .dump [args]Dumps the database contents
    .save <path>Saves the current database to the specified path
    .schema [args]Displays the database schema
    .import <args>Imports data into the database
    .restore <path>Restores a database from a file
    .exit(Implicitly handled via TUI) Exits the shell
  6. Inspect database schema and indexes

    main

    Use the following commands to explore the structure of your database:

    • .tables: Lists all user-defined tables (filtering out internal __chai_ tables).
    • .schema [table_name]: Shows the CREATE statements used to define tables. If no table name is provided, it shows the schema for all tables.
    • .indexes [table_name]: Displays all indexes in the database. If you provide a table_name, it only shows indexes for that specific table.
  7. Use the Chai shell interactive TUI

    main

    The Chai shell provides an interactive Terminal User Interface (TUI) for executing SQL queries. It supports multi-line input, command history, and real-time query execution feedback.

    Key Interactions

    • Execute Query: Type your SQL query and press Enter.
      • For single-line commands, ensure they end with a semicolon (;) or start with a dot (.) to trigger execution.
      • For multi-line queries, the shell expands the input area as you type.
    • Command History: Use the Up and Down arrow keys to navigate through previously executed queries.
    • Exit the Shell:
      • Type exit or .exit and press Enter.
      • Press Ctrl+D when the input buffer is empty.
      • Press Ctrl+C to cancel a running query or exit.
    • Cancel Running Query: If a query is currently executing (indicated by a spinner), press Ctrl+C to cancel the execution.
  8. Use the Chai CLI

    main

    The chai command is the primary entrypoint for interacting with the ChaiSQL database. It can be used in two modes:

    1. Interactive Shell Mode: Running chai [dbpath] starts an interactive shell for the specified database.
    2. Standard Input Mode: If you pipe SQL commands into the CLI (e.g., cat queries.sql | chai [dbpath]), it executes the SQL from stdin and outputs the results to stdout, then exits.

    Available subcommands include version, dump, restore, bench, and pebble.

  9. Save and Restore the database

    main

    ChaiSQL allows you to persist your current database state to a file or restore it from a previously saved file.

    Save the database

    Use .save to write the current database content to a file. If the target file already exists, it will be overwritten.

    .save backup.sql

    Restore the database

    Use .restore to load a database from a text file (typically a file generated by .dump).

    .restore backup.sql
  10. Current SQL capabilities and limitations

    main

    ChaiSQL is designed for simpler schemas and embedded use cases.

    Supported features:

    • Creating and dropping tables & indexes (including composite indexes)
    • Inserting, updating, and deleting rows
    • Basic SELECT queries with filtering, ordering, and grouping
    • DISTINCT, UNION, and UNION ALL

    Not yet implemented:

    • Joins
    • Many advanced SQL features
    • PostgreSQL wire protocol compatibility (cannot use psql, pg_dump, or standard Postgres drivers/ORMs)
  11. Import CSV data into a table

    main

    You can import data from a CSV file into a ChaiSQL table using the .import command. The command will automatically create the table if it does not exist, using the CSV headers as column names with TEXT types.

    Syntax: .import csv <path_to_file> <table_name>

    Note: The TYPE argument must be csv (case-insensitive).