Skip to content

Latest commit

 

History

History
442 lines (360 loc) · 13.5 KB

features.md

File metadata and controls

442 lines (360 loc) · 13.5 KB

Features

Shell

Run the local interactive shell with:

cargo run --bin kitesql-shell

Use a custom data directory:

cargo run --bin kitesql-shell -- --path ./tmp/kitesql-shell-data

Run a one-shot SQL check:

cargo run --bin kitesql-shell -- -e "select current_timestamp"

In interactive mode, end SQL statements with ;; an empty line also executes the buffered statement.

Built-in metacommands:

  • .help
  • .quit
  • .tables
  • .views
  • .schema <name>

PG Wire:

run cargo run --features="net" to start service

ORM Mapping: features = ["orm"]

See the ORM guide for the full ORM guide, including:

  • #[derive(Model)] usage and supported attributes
  • CRUD, DDL, and migration helpers
  • typed query builder APIs
  • public ORM structs, enums, and traits
  • related ResultIter::orm::<M>() integration

Async API on S3: features = ["slatedb-s3"]

With the async feature, the storage traits, the executor and the database API compile as async from the same source; the sync build is unchanged. The slatedb-s3 feature adds SlateDbStorage, which keeps the data in an S3 bucket through SlateDB, an LSM tree on object storage, and runs on tokio. Any process that opens the bucket path sees the same database.

use kite_sql::db::{AsyncIter, DataBaseBuilder};
use kite_sql::storage::slatedb::{S3Config, SlateDbStorage};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Credentials and region come from the `AWS_*` environment variables.
    let config = S3Config::new("my-bucket");
    let storage = SlateDbStorage::open_s3("kitesql/demo", &config, Default::default()).await?;
    let mut database = DataBaseBuilder::path(".").build_with_storage(storage.clone())?;

    database.migrate::<User>().await?;
    database.insert(&User { id: 1, name: "Alice".to_string(), age: Some(18) }).await?;
    let mut users = database.fetch::<User>().await?;
    while let Some(user) = users.next().await {
        println!("{:?}", user?);
    }
    users.done().await?;

    drop(database);
    // Flushes what is still in memory to S3.
    storage.close().await?;
    Ok(())
}

async excludes the sync storages (rocksdb, lmdb) and the shell, Python and Wasm bindings: pick one path per build. The full example is async_s3:

KITESQL_S3_BUCKET=my-bucket AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... \
cargo run --example async_s3 --no-default-features --features slatedb-s3,orm

A reopened database loads its tables with database.load(CatalogKind::Table(name)) before querying them, as async_s3 does.

By default a commit waits until its write is durable in S3. storage.await_durable(false) makes it return once the write is applied in memory; a crash may then lose the latest commits.

Reads that miss the block cache cost an S3 request each, so the cache size decides how fast queries run. SlateDbCacheOptions sizes the memory cache and adds a local disk tier:

use kite_sql::storage::slatedb::{S3Config, SlateDbCacheOptions, SlateDbDiskCache, SlateDbStorage};

let cache = SlateDbCacheOptions {
    memory_bytes: Some(4 << 30),
    disk: Some(SlateDbDiskCache {
        dir: "./slatedb-cache".into(),
        // The cache files grow as they fill, so a large capacity costs nothing up front.
        capacity_bytes: 64 << 30,
    }),
    // Keep the blocks compactions write, which otherwise leave the cache.
    cache_compaction_output: true,
};
let storage = SlateDbStorage::open_s3("kitesql/demo", &S3Config::new("my-bucket"), cache).await?;

SlateDbScanOptions sets how scans read SST blocks: 256KiB per request, 4 requests in flight and cached blocks by default.

Spill-backed Aggregation: features = ["spill"]

The native-only spill feature bounds memory usage for large grouped aggregations. It is not enabled by default and cannot be combined with wasm.

For SQL, place the optimizer hint immediately after SELECT:

SELECT /*+ FORCE_AGG_SPILL */ user_id, COUNT(*)
FROM orders
GROUP BY user_id
ORDER BY user_id;

For ORM queries, enable both orm and spill, then call force_spill() before building the projection and aggregate plan:

let grouped = database.bind(|ctx| {
    ctx.from::<Order>()?
        .force_spill()?
        .project_tuple(|e| {
            Ok(vec![e.column(Order::user_id())?, e.count_all()?])
        })?
        .group_by(|e| e.column(Order::user_id()))?
        .order_by(Order::user_id())?
        .finish()
})?;

KiteSQL still reuses an already ordered input when possible. Otherwise it adds an external sort on the group keys and executes a streaming aggregate. The hint is intended for grouped aggregates or DISTINCT; an aggregate without group keys already uses constant-size accumulator state.

Nested-loop Join Hint

Use FORCE_NEST_LOOP_JOIN to select the nested-loop implementation for joins in the current SELECT query block:

SELECT /*+ FORCE_NEST_LOOP_JOIN */ orders.id, users.name
FROM orders
JOIN users ON orders.user_id = users.id;

ORM queries can select the same implementation before adding joins:

let joined = database.bind(|ctx| {
    ctx.from::<Order>()?
        .force_nested_loop()
        .inner_join::<User, _>(|e| {
            e.column(Order::user_id())?.eq(e.column(User::id())?)
        })?
        .finish()
})?;

It avoids Hash Join's build-side tuple materialization, but may perform substantially more work on large inputs.

User-Defined Function: features = ["macros"]

scala_function!(TestFunction::test(LogicalType::Integer, LogicalType::Integer) -> LogicalType::Integer => |v1: DataValue, v2: DataValue| {
    let plus_binary_evaluator = EvaluatorFactory::binary_create(LogicalType::Integer, BinaryOperator::Plus)?;
    let value = plus_binary_evaluator.binary_eval(&v1, &v2);

    let plus_unary_evaluator = EvaluatorFactory::unary_create(LogicalType::Integer, UnaryOperator::Minus)?;
    Ok(plus_unary_evaluator.unary_eval(&value))
});

let kite_sql = DataBaseBuilder::path("./data")
    .register_scala_function(TestFunction::new())
    .build()?;

User-Defined Table Function: features = ["macros"]

table_function!(MyTableFunction::test_numbers(LogicalType::Integer) -> [c1: LogicalType::Integer, c2: LogicalType::Integer] => (|v1: DataValue| {
    let num = v1.i32().unwrap();

    Ok(Box::new((0..num)
        .into_iter()
        .map(|i| Ok(Tuple {
            id: None,
            values: vec![
                DataValue::Int32(Some(i)),
                DataValue::Int32(Some(i)),
            ]
        }))) as TableFunctionIter)
}));
let kite_sql = DataBaseBuilder::path("./data")
   .register_table_function(MyTableFunction::new())
   .build()?;

Optimizer

  • RBO
  • CBO based on RBO(Physical Selection)

Executor

  • Volcano

MVCC Transaction

  • Pessimistic (Default)
  • Optimistic
  • Isolation level: repeatable read; every statement in a transaction reads the snapshot taken when it began

Checkpoint

KiteSQL exposes checkpoint as a storage capability rather than a full backup workflow. A checkpoint only creates a consistent local snapshot directory; compressing, uploading, retaining, and pruning backups should stay in application code.

Support matrix:

  • build_optimistic() supports Database::checkpoint(...) through RocksDB's safe checkpoint API.
  • build_rocksdb() requires Cargo feature unsafe_txdb_checkpoint, which uses RocksDB's TransactionDB checkpoint API.
  • build_lmdb() and build_in_memory() do not currently expose checkpoint support.

Opt in for TransactionDB checkpoint support:

cargo check --features unsafe_txdb_checkpoint

Minimal usage:

use kite_sql::db::DataBaseBuilder;
use kite_sql::errors::DatabaseError;

fn main() -> Result<(), DatabaseError> {
    let database = DataBaseBuilder::path("./data").build_rocksdb()?;

    database.checkpoint("./backup/checkpoint-2026-03-29")?;

    Ok(())
}

If unsafe_txdb_checkpoint is not enabled, build_rocksdb() returns an explicit error instead of attempting the experimental implementation.

Field options

  • [not] null
  • unique
  • primary key

Supports index type

  • PrimaryKey
  • Unique
  • Normal
  • Composite
  • Prefix: col(n) in UNIQUE constraints and CREATE INDEX indexes the first n characters of a string or the first n bytes of a binary value. Other types and primary key prefixes are rejected. Prefix indexes cannot cover queries; equality candidates are checked against the full row.

Supports multiple primary key types

  • Tinyint
  • UTinyint
  • Smallint
  • USmallint
  • Integer
  • UInteger
  • Bigint
  • UBigint
  • Char
  • Varchar

DDL

  • Begin (Server only)
  • Commit (Server only)
  • Rollback (Server only)
  • Create
    • Table
    • Index: Unique\Normal\Composite
    • View
  • Drop
    • Table
    • Index
      • Tips: Drop Index table_name.index_name
    • View
  • Alert
    • Add Column
    • Drop Column
  • Truncate

DQL

  • Select
    • SeqScan
    • IndexScan
    • FunctionScan
  • Where
  • Distinct
  • Alias
  • Aggregation:
    • count()
    • sum()
    • avg()
    • min()
    • max()
  • SubQuery[select/from/where]
  • Join:
    • Inner
    • Left
    • Right
    • Full
    • Cross (Natural\Using)
  • Exists
  • Group By
  • Having
  • Window functions:
    • row_number(), rank(), dense_rank()
    • count(), sum(), avg(), min(), max() with OVER
    • PARTITION BY and window ORDER BY with the default frame
    • Explicit frames, named windows, and QUALIFY are not yet supported
  • Order By
  • Limit
  • Show Tables
  • Explain
  • Describe
  • Union
  • EXCEPT
  • INTERSECT

DML

  • Insert
  • Insert Overwrite
  • Update
  • Delete
  • Analyze
  • Copy To
  • Copy From

DataTypes

  • Invalid
  • SqlNull
  • Boolean
  • Tinyint
  • UTinyint
  • Smallint
  • USmallint
  • Integer
  • UInteger
  • Bigint
  • UBigint
  • Float
  • Double
  • Char
  • Varchar
  • Date
  • DateTime
  • Time
  • TimeStamp
  • Tuple

Custom SQL Dialects

KiteSQL supports pluggable SQL dialects through the SqlDialect trait. A dialect parses SQL text into KiteSQL's own syntax tree (kite_sql::ast), so it may use any parser, and customizes how statements are typed. A Database parses and binds statements with its current dialect. The default is GenericSqlDialect, the standard behaviour, which parses with sqlparser and needs the parser feature.

Using a Custom Dialect

With the sqlite-parser feature, SqliteDialect parses SQLite syntax with SQLite's own grammar (sqlite3-parser); statements still run with KiteSQL's semantics, and SQLite syntax KiteSQL does not support is rejected.

Pass a dialect type to the builder when it is fixed at compile time:

use kite_sql::db::DataBaseBuilder;

let db = DataBaseBuilder::path("./my_db")
    .dialect(MyDialect::new())
    .build_rocksdb()?;

To pick the dialect at runtime, for example from configuration, opt in to DynDialect. It starts with the generic dialect registered and current, and forwards every hook to the current one:

use kite_sql::db::DataBaseBuilder;
use kite_sql::dialect::DynDialect;

let mut dialect = DynDialect::new();
dialect.register(MyDialect::new());
assert!(dialect.switch("my_dialect"));

let db = DataBaseBuilder::path("./my_db")
    .dialect(dialect)
    .build_rocksdb()?;

After opening a database with DynDialect, use db.switch_dialect(name) with mutable access to select another registered dialect for subsequent statements.

Implementing a Custom Dialect

Implement the SqlDialect trait to customize behavior. A dialect built on sqlparser can parse with kite_sql::parser::generic::SqlParser, map its own data types through DataTypeMapper, and rewrite the returned statements:

use kite_sql::ast::Statement;
use kite_sql::dialect::SqlDialect;
use kite_sql::errors::DatabaseError;
use kite_sql::parser::generic::{DataTypeMapper, SqlParser};
use kite_sql::types::LogicalType;
use sqlparser::ast::DataType;
use sqlparser::dialect::GenericDialect;

#[derive(Debug)]
struct MyDialect;

// Optional: map custom data types
impl DataTypeMapper for MyDialect {
    fn map_data_type(&self, data_type: &DataType) -> Option<Result<LogicalType, DatabaseError>> {
        match data_type {
            DataType::Custom(name, _) if name.to_string() == "MY_TYPE" => {
                Some(Ok(LogicalType::Integer))
            }
            _ => None,
        }
    }
}

impl SqlDialect for MyDialect {
    fn name(&self) -> &str {
        "my_dialect"
    }

    fn parse(&self, sql: &str) -> Result<Vec<Statement>, DatabaseError> {
        let statements = SqlParser::new(&GenericDialect {})
            .with_type_mapper(self)
            .parse(sql)?;
        // Optional: rewrite the statements before they are bound
        Ok(statements)
    }
}

The SqlDialect trait methods:

  • name() — Returns the dialect's unique identifier
  • parse() — Parses SQL text into KiteSQL statements; the dialect rejects syntax it does not support and may rewrite the statements
  • comparison_type() — Optional hook to pick the type both operands of a comparison (=, <>, <, <=, >, >=, IN, BETWEEN) are cast to
  • boolean_text() — Optional hook to choose the text of a boolean in CAST(.. AS CHAR) or CAST(.. AS VARCHAR) (default 'true'/'false')

DataTypeMapper::map_data_type() maps types inside expressions (CAST, typed literals); map_column_type() maps the types of column definitions and defaults to map_data_type().

By default, the GenericSqlDialect is used, which provides standard SQL behavior with no custom transformations.