Skip to main content

Crate slabs_db

Crate slabs_db 

Source
Expand description

Raw-SQL database library for Slabs.

This crate owns the tuned SQLite WAL wrapper (Db), the optional PostgreSQL wrapper (PgDb), URL engine detection (DbEngine), framework system schemas (SYSTEM_SCHEMA_SQL, POSTGRES_SYSTEM_SCHEMA_SQL), and FTS5 query escaping (fts5_query). It also re-exports QueryBuilder for dynamic parameterized SQL.

§Owned types and system tables

Calling Db::init_system_tables, Db::migrate, or Db::migrate_dir (and the matching PgDb methods) creates these 12 framework tables if they do not exist:

  • slabs_sessions
  • slabs_magic_links
  • slabs_access_tokens
  • slabs_jobs
  • slabs_cache
  • slabs_mail_outbox
  • slabs_blobs
  • slabs_webhooks
  • slabs_webhook_deliveries
  • slabs_idempotency_keys
  • slabs_audit_log
  • slabs_incidents

§Invariants

  • Split WAL pools on file-backed SQLite: Db::reader returns a read-only pool with up to 16 connections for concurrent SELECT queries. Db::writer and Db::pool return a dedicated single-connection writer pool (max_connections(1)).
  • Explicit BEGIN IMMEDIATE transactions: Db::begin opens a BEGIN IMMEDIATE transaction on the single writer pool. Use it for multi-step mutations so SQLite acquires the write lock up front and avoids SQLITE_BUSY_SNAPSHOT lock-upgrade failures.
  • In-memory test databases share one connection: when database_url is "sqlite::memory:" or contains "mode=memory", Db::connect clones the single writer pool for Db::reader because SQLite isolates in-memory databases per connection.
  • Tuned SQLite pragmas: Db::connect sets foreign_keys = ON, synchronous = NORMAL, cache_size = -64000, temp_store = MEMORY, trusted_schema = OFF, secure_delete = ON, and busy_timeout (10s writer, 5s reader). File-backed databases also enable journal_mode = WAL and mmap_size = 268435456 (256 MiB).
  • Parameterized SQL only: always bind untrusted input with sqlx::query, sqlx::query_as, or QueryBuilder. Never interpolate user strings into SQL text.
  • FTS5 search escaping: pass untrusted search strings through fts5_query before binding to an FTS5 MATCH ? clause. It strips double quotes and wraps each whitespace token as "token"* joined with AND.

§Usage

use slabs_core::SlabResult;
use slabs_db::{fts5_query, Db};

async fn example() -> SlabResult<()> {
    let db = Db::connect("sqlite://app.db?mode=rwc").await?;
    db.init_system_tables().await?;

    // Concurrent SELECT on the read-only WAL pool.
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
        .fetch_one(db.reader())
        .await?;

    // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
    let mut tx = db.begin().await?;
    sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
        .bind("stale_key")
        .execute(&mut *tx)
        .await?;
    tx.commit().await?;

    // Safe FTS5 query construction for user input.
    if let Some(match_expr) = fts5_query("deploy \"prod\"") {
        assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
    }
    let _ = count;
    Ok(())
}

Structs§

AuditEntry
Persisted audit event row stored in slabs_audit_log.
AuditLog
Transactional audit log backed by the slabs_audit_log system table.
CursorPage
One page of cursor-paginated results.
Db
Raw-SQL SQLite database wrapper tuned for concurrent WAL workloads.
IncidentInput
Input payload for recording a deduplicated runtime incident in slabs_incidents.
IncidentRecord
Persisted runtime incident row stored in slabs_incidents.
Incidents
Deduplicated runtime incident store backed by the slabs_incidents system table.
Pagination
Query parameters for cursor-based (keyset) pagination.
PgDb
Raw-SQL PostgreSQL database wrapper for multi-node deployments.
QueryBuilder
A builder type for constructing queries at runtime.

Enums§

DbEngine
Database engine detected from a DATABASE_URL string.
IncidentOutcome
Lifecycle outcome returned when recording an incident via Incidents::record_with_outcome.

Constants§

POSTGRES_SYSTEM_SCHEMA_SQL
Framework-owned PostgreSQL DDL for the 12 system tables and their indexes.
SYSTEM_SCHEMA_SQL
Framework-owned SQLite DDL for the 12 system tables and their indexes.

Functions§

fts5_query
Converts untrusted user search text into an FTS5 prefix-AND MATCH expression.