### Start a schema rollout migration Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes the non-destructive expansion phase ('phase = "start"') of a rollout manifest. It acquires a global lock, records progress, and advances the status to 'ready_to_complete'. This command is safe to re-run if interrupted. Template variables can be used, and the full path to the manifest can be provided. ```sh surrealkit rollout start 20260302153045__add_customer_indexes # With template variables surrealkit rollout start 20260302153045__add_customer_indexes --var env=prod # Can also pass the full path surrealkit rollout start database/rollouts/20260302153045__add_customer_indexes.toml # Status after start: # Rollout 20260302153045__add_customer_indexes is ready to complete. ``` -------------------------------- ### Create a baseline for rollouts Source: https://context7.com/surrealdb/surrealkit/llms.txt Snapshots the current schema files and catalog to establish a starting point for the rollout migration system. This command must be run once before planning migrations on an existing database. ```sh # Record the current schema state as the rollout baseline surrealkit rollout baseline # Output example: # Seeded managed entity baseline with 5 schema file(s) and 12 managed object(s). ``` -------------------------------- ### Full Schema Rollout Example Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Demonstrates a complete schema rollout process, including applying new tables and defining rollback steps. Ensure that inline SQL and file references are mutually exclusive within a single step. ```rust use surrealkit::{ EmbeddedSchemaFile, RolloutPhase, RolloutSpec, RolloutStep, RolloutStepKind, run_start_with_spec, run_complete_with_spec, schema_state::EntityKey, }; // The full desired schema after this rollout completes. static TARGET: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/person.surql", sql: "DEFINE TABLE person SCHEMALESS;" }, EmbeddedSchemaFile { path: "database/schema/account.surql", sql: "DEFINE TABLE account SCHEMALESS;" }, ]; let spec = RolloutSpec { id: "add_account".to_string(), name: "add_account".to_string(), source_schema_hash: String::new(), target_schema_hash: String::new(), compatibility: "phased".to_string(), renames: vec![], steps: vec![ // Start phase: apply the new table. RolloutStep { id: "apply".to_string(), phase: RolloutPhase::Start, kind: RolloutStepKind::ApplySchema, sql: Some("DEFINE TABLE account SCHEMALESS;".to_string()), files: vec![], expect: None, entities: vec![], idempotent: None, }, // Rollback phase: undo the start phase if needed. RolloutStep { id: "rollback".to_string(), phase: RolloutPhase::Rollback, kind: RolloutStepKind::RemoveEntities, entities: vec![ EntityKey { kind: "table".to_string(), scope: None, name: "account".to_string() }, ], files: vec![], sql: None, expect: None, idempotent: None, }, ], }; // Apply the start phase. Blocks if another rollout is already active. run_start_with_spec(&db, &spec, TARGET).await?; // ... deploy new application code, wait for traffic drain, etc. ... // Apply the complete phase, marking the rollout done. run_complete_with_spec(&db, &spec).await?; ``` -------------------------------- ### Execute Production Rollout Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Apply a production rollout in stages. First, start the non-destructive expansion phase with `surrealkit rollout start `, then complete the destructive contract phase after application cutover with `surrealkit rollout complete `. ```sh surrealkit rollout start 20260302153045__add_customer_indexes ``` ```sh surrealkit rollout complete 20260302153045__add_customer_indexes ``` -------------------------------- ### Install vite-plugin-surrealkit Source: https://github.com/surrealdb/surrealkit/blob/main/packages/vite-plugin-surrealkit/README.md Install the plugin as a development dependency using npm. ```sh npm i -D vite-plugin-surrealkit ``` -------------------------------- ### Define Table with Template Variables Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Use template variables in `.surql` files for dynamic table definitions. This example uses a `schema_prefix` variable for table naming. ```sql -- database/schema/tables.surql DEFINE TABLE ${schema_prefix}_users SCHEMAFULL; ``` -------------------------------- ### SurrealKit Example Test Suite Source: https://github.com/surrealdb/surrealkit/blob/main/README.md A TOML file defining a test suite with multiple test cases, including SQL assertions and API requests. Supports tagging tests for selective execution. ```toml name = "security_smoke" tags = ["smoke", "security"] [[cases]] name = "guest_cannot_create_order" kind = "sql_expect" actor = "guest" sql = "CREATE order CONTENT { total: 10 };" allow = false error_contains = "permission" [[cases]] name = "orders_api_returns_200" kind = "api_request" actor = "root" method = "GET" path = "/api/orders" expected_status = 200 [[cases.body_assertions]] path = "0.id" exists = true ``` -------------------------------- ### Docker Compose for SurrealDB and SurrealKit Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Integrate SurrealDB and SurrealKit within a Docker Compose setup for end-to-end testing or development environments. This configuration ensures SurrealDB is healthy before SurrealKit starts. ```yaml services: surrealdb: image: surrealdb/surrealdb:latest command: start --user root --pass root memory healthcheck: test: ["CMD", "/surreal", "is-ready"] interval: 1s timeout: 5s retries: 30 surrealkit: image: ghcr.io/surrealdb/surrealkit:latest depends_on: surrealdb: condition: service_healthy volumes: - ./database:/database:ro command: - --host=http://surrealdb:8000 - --ns=my_ns - --db=my_db - --user=root - --pass=root - sync ``` -------------------------------- ### Define Role with Template Variables Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Use template variables like `${VAR_NAME}` in `.surql` files to define dynamic values. This example shows defining a role with a username variable. ```sql -- database/schema/roles.surql DROP ROLE IF EXISTS ${talent_username}; DEFINE ROLE ${talent_username} PERMISSIONS FULL; ``` -------------------------------- ### Set Template Variables via Environment Variables Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Automatically pick up environment variables prefixed with `SURREALKIT_VAR_`. For example, `SURREALKIT_VAR_SCHEMA_PREFIX=acme` sets the `schema_prefix` variable. ```sh export SURREALKIT_VAR_SCHEMA_PREFIX=acme export SURREALKIT_VAR_TALENT_USERNAME=talent_rw surrealkit sync ``` -------------------------------- ### Programmatic Schema Rollout with Specs Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes rollout phases defined entirely in Rust code using `RolloutSpec`. Useful for programmatic migration orchestration or testing. Supports starting, completing, and rolling back phases. ```rust use surrealkit::{ EmbeddedSchemaFile, RolloutSpec, RolloutStep, RolloutPhase, RolloutStepKind, TemplateVars, run_start_with_spec, run_complete_with_spec, run_rollback_with_spec, run_sync_embedded, }; use surrealkit::schema_state::EntityKey; static SOURCE_SCHEMA: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/order.surql", sql: "DEFINE TABLE order SCHEMALESS;" }, ]; static TARGET_SCHEMA: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/order.surql", sql: "DEFINE TABLE order SCHEMALESS;" }, EmbeddedSchemaFile { path: "database/schema/invoice.surql", sql: "DEFINE TABLE invoice SCHEMALESS;" }, ]; #[tokio::main] async fn main() -> anyhow::Result<()> { let db = /* connect */; // Establish baseline run_sync_embedded(&db, SOURCE_SCHEMA).await?; // Define the rollout in code let spec = RolloutSpec { id: "add_invoice_table".to_string(), name: "Add invoice table".to_string(), source_schema_hash: String::new(), // skip hash check target_schema_hash: String::new(), compatibility: "phased".to_string(), renames: vec![], steps: vec![ RolloutStep { id: "apply_invoice".to_string(), phase: RolloutPhase::Start, kind: RolloutStepKind::ApplySchema, files: vec![], sql: Some("DEFINE TABLE invoice SCHEMALESS;".to_string()), expect: None, entities: vec![], idempotent: None, }, RolloutStep { id: "rollback_invoice".to_string(), phase: RolloutPhase::Rollback, kind: RolloutStepKind::RemoveEntities, files: vec![], sql: None, expect: None, entities: vec![EntityKey { kind: "table".to_string(), scope: None, name: "invoice".to_string() }], idempotent: None, }, ], }; let vars = TemplateVars::default(); // Start phase (non-destructive expansion) run_start_with_spec(&db, &spec, TARGET_SCHEMA, &vars).await?; // status is now "ready_to_complete" // After application cutover, run complete phase run_complete_with_spec(&db, &spec, &vars).await?; // status is now "completed" // OR: roll back if needed // run_rollback_with_spec(&db, &spec, &vars).await?; Ok(()) } ``` -------------------------------- ### Initialize a new SurrealKit project Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Use the `surrealkit init` command to create a new project directory with the necessary scaffolding for schema management. ```sh surrealkit init ``` -------------------------------- ### Initialize a new SurrealKit project Source: https://context7.com/surrealdb/surrealkit/llms.txt Scaffolds a new project directory structure with subdirectories for schema, seed, rollouts, snapshots, and tests, along with a project configuration file. ```sh surrealkit init # Creates: # database/schema/ -- place .surql schema definition files here # database/seed/ -- .surql data seed files # database/rollouts/ -- generated rollout manifest .toml files # database/snapshots/ -- schema_snapshot.json and catalog_snapshot.json # database/tests/ -- suites/ directory and config.toml # surrealkit.toml -- project config (variables, etc.) ``` -------------------------------- ### Connect to SurrealDB with Configuration Overrides Source: https://context7.com/surrealdb/surrealkit/llms.txt Build a database configuration from environment variables and CLI overrides, then connect and authenticate to SurrealDB. Supports various authentication levels. ```rust use surrealkit::{DbCfg, DbOverrides, connect}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Resolution order: CLI overrides > SURREALDB_* env vars > DATABASE_* env vars > defaults let overrides = DbOverrides { host: Some("http://db.internal:8000".to_string()), ns: Some("production".to_string()), db: Some("myapp".to_string()), user: None, // falls back to SURREALDB_USER or "root" pass: None, // falls back to SURREALDB_PASSWORD or "root" auth_level: Some("root".to_string()), // "root" | "namespace"/"ns" | "database"/"db" }; let cfg = DbCfg::from_env(None, &overrides)?; let db = connect(&cfg).await?; // db is a Surreal with ns/db already selected // Use with any surrealkit library function surrealkit::run_setup(&db).await?; Ok(()) } ``` -------------------------------- ### DbCfg and connect Source: https://context7.com/surrealdb/surrealkit/llms.txt Build a database configuration from environment variables and CLI overrides, then connect and authenticate to SurrealDB. ```APIDOC ## Library API: `DbCfg` and `connect` Build a database configuration from environment variables and CLI overrides, then connect and authenticate to SurrealDB. ```rust use surrealkit::{DbCfg, DbOverrides, connect}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Resolution order: CLI overrides > SURREALDB_* env vars > DATABASE_* env vars > defaults let overrides = DbOverrides { host: Some("http://db.internal:8000".to_string()), ns: Some("production".to_string()), db: Some("myapp".to_string()), user: None, // falls back to SURREALDB_USER or "root" pass: None, // falls back to SURREALDB_PASSWORD or "root" auth_level: Some("root".to_string()), // "root" | "namespace"/"ns" | "database"/"db" }; let cfg = DbCfg::from_env(None, &overrides)?; let db = connect(&cfg).await?; // db is a Surreal with ns/db already selected // Use with any surrealkit library function surrealkit::run_setup(&db).await?; Ok(()) } ``` ``` -------------------------------- ### Seed Data from Directory Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Executes `.surql` files from a specified directory in lexicographical order to seed the database. Ensure the path to the directory is correct. ```rust use surrealkit::seed_from_dir; seed_from_dir(&db, std::path::Path::new("fixtures/seed")).await?; ``` -------------------------------- ### Copy Test Configuration Files Source: https://github.com/surrealdb/surrealkit/blob/main/examples/testing/README.md Copy the necessary configuration and fixture files to your test directory before running tests. ```sh cp /examples/testing/config.toml /database/tests/config.toml cp /examples/testing/suites/root_access_full_stack.toml /database/tests/suites/root_access_full_stack.toml cp /examples/testing/fixtures/root_and_access_setup.surql /database/tests/fixtures/root_and_access_setup.surql ``` -------------------------------- ### Apply Single SurrealQL File Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes a single `.surql` file directly against the connected database, supporting template variable substitution. Useful for applying specific migrations or scripts. ```sh surrealkit apply database/migrations/backfill_nulls.surql --var prefix=acme ``` -------------------------------- ### Connect to SurrealDB with Environment Configuration Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Reads connection details from environment variables and optionally overrides them with CLI arguments to establish a connection to SurrealDB. The `connect` function handles Surreal client construction and authentication. ```rust use surrealkit::{DbCfg, DbOverrides, connect}; let cfg = DbCfg::from_env(None, &DbOverrides::default())?; let db = connect(&cfg).await?; ``` -------------------------------- ### TemplateVars and build_vars Source: https://context7.com/surrealdb/surrealkit/llms.txt Build a variable map from CLI flags, `SURREALKIT_VAR_*` environment variables, and a `surrealkit.toml` config file, then apply substitution to SurrealQL strings. ```APIDOC ## Library API: `TemplateVars` and `build_vars` Build a variable map from CLI flags, `SURREALKIT_VAR_*` environment variables, and a `surrealkit.toml` config file, then apply substitution to SurrealQL strings. ```rust use surrealkit::{TemplateVars, build_vars, parse_var_flag}; use std::path::Path; fn main() -> anyhow::Result<()> { // Parse --var KEY=VALUE flags let raw: Vec<(String, String)> = vec!["PREFIX=acme", "ENV=prod"] .iter() .map(|s| parse_var_flag(s)) .collect::>()?; // Merge CLI, SURREALKIT_VAR_* env vars, and surrealkit.toml (priority: CLI > env > toml) let vars_map = build_vars(&raw, Some(Path::new("surrealkit.toml")))?; let vars = TemplateVars { vars: vars_map }; // Apply substitution let sql = "DEFINE TABLE ${prefix}_users SCHEMAFULL;"; let resolved = vars.apply(sql)?; assert_eq!(resolved, "DEFINE TABLE acme_users SCHEMAFULL;"); // Escape: $${VAR} → literal ${VAR} let escaped = vars.apply("SET note = '$${prefix} is literal';")?; assert_eq!(escaped, "SET note = '${prefix} is literal';"); // Undefined variable = hard error let result = vars.apply("${UNDEFINED_VAR}"); assert!(result.is_err()); // error: template variable 'UNDEFINED_VAR' is not defined // (set via --var UNDEFINED_VAR=VALUE, SURREALKIT_VAR_UNDEFINED_VAR env var, or surrealkit.toml [variables]) Ok(()) } ``` ``` -------------------------------- ### Generate Rollout Manifest Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Create a rollout manifest from the current desired-state diff using `surrealkit rollout plan --name `. The manifest is saved in `database/rollouts/*.toml`. ```sh surrealkit rollout plan --name add_customer_indexes ``` -------------------------------- ### Run SurrealKit Sync with Docker Source: https://context7.com/surrealdb/surrealkit/llms.txt Execute SurrealKit schema synchronization using a Docker container. Mounts the local database directory and sets necessary environment variables for SurrealDB connection. ```sh # Pull latest image docker pull ghcr.io/surrealdb/surrealkit:latest # One-shot sync docker run --rm \ -v "$(pwd)/database:/database:ro" \ -e SURREALDB_HOST=http://host.docker.internal:8000 \ -e SURREALDB_NAMESPACE=myns \ -e SURREALDB_NAME=mydb \ ghcr.io/surrealdb/surrealkit:latest sync ``` -------------------------------- ### Baseline Production Database Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Before the first rollout on a shared or production database, use `surrealkit rollout baseline` to establish a baseline state. ```sh surrealkit rollout baseline ``` -------------------------------- ### Connect to SurrealDB using CLI arguments Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Specify connection details for SurrealDB directly via command-line flags when running SurrealKit. This method takes precedence over environment variables and `.env` files. ```bash surrealkit --host http://localhost:8000 --ns my_ns --db my_db --user root --pass root sync ``` -------------------------------- ### Run SurrealKit Test Suite Source: https://github.com/surrealdb/surrealkit/blob/main/examples/testing/README.md Execute the SurrealKit test suite with specified parameters, outputting results to a JSON file. ```sh surrealkit test --suite '*root_access_full_stack*' --json-out database/tests/report.json ``` -------------------------------- ### Watch Mode for Local Development Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Enable watch mode with `surrealkit sync --watch` for continuous local development. This includes handling file deletions automatically. ```sh surrealkit sync --watch ``` -------------------------------- ### Seed SurrealDB from Directory with Template Variables Source: https://context7.com/surrealdb/surrealkit/llms.txt Programmatically seed a SurrealDB database from a directory of .surql files. Supports template variable substitution for dynamic seeding. Files are executed in alphabetical order. ```rust use std::path::Path; use std::collections::HashMap; use surrealkit::{seed_from_dir, TemplateVars}; #[tokio::main] async fn main() -> anyhow::Result<()> { let db = /* connect */; // Seed with no variables seed_from_dir(&db, Path::new("database/seed"), &TemplateVars::default()).await?; // Seed with variables let mut vars = HashMap::new(); vars.insert("ENV".to_string(), "staging".to_string()); vars.insert("ADMIN_EMAIL".to_string(), "admin@example.com".to_string()); let template_vars = TemplateVars { vars }; // Seed from a custom directory seed_from_dir(&db, Path::new("fixtures/test_data"), &template_vars).await?; // Output: // Seeding from fixtures/test_data (3 files found) // executing fixtures/test_data/01_users.surql // executing fixtures/test_data/02_products.surql // executing fixtures/test_data/03_orders.surql // Seeded 3 files Ok(()) } ``` -------------------------------- ### Runtime Schema Synchronization with run_sync_embedded Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Manually construct the schema slice using `EmbeddedSchemaFile` and synchronize it at runtime with `run_sync_embedded`. This function calls `run_setup` internally. ```rust use surrealkit::{EmbeddedSchemaFile, run_sync_embedded}; static SCHEMA: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/person.surql", sql: "DEFINE TABLE person SCHEMALESS;", }, ]; run_sync_embedded(&db, SCHEMA).await?; ``` -------------------------------- ### run_start_with_spec, run_complete_with_spec, run_rollback_with_spec Source: https://context7.com/surrealdb/surrealkit/llms.txt Functions to execute rollout phases defined entirely in Rust code via a `RolloutSpec`, bypassing the need for TOML files. This is useful for programmatic migration orchestration and testing. ```APIDOC ## Library API: `run_start_with_spec` / `run_complete_with_spec` / `run_rollback_with_spec` Execute rollout phases from a `RolloutSpec` defined entirely in Rust code, without any TOML files on disk. Useful for programmatic migration orchestration or testing. ```rust use surrealkit::{ EmbeddedSchemaFile, RolloutSpec, RolloutStep, RolloutPhase, RolloutStepKind, TemplateVars, run_start_with_spec, run_complete_with_spec, run_rollback_with_spec, run_sync_embedded, }; use surrealkit::schema_state::EntityKey; static SOURCE_SCHEMA: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/order.surql", sql: "DEFINE TABLE order SCHEMALESS;" }, ]; static TARGET_SCHEMA: &[EmbeddedSchemaFile] = &[ EmbeddedSchemaFile { path: "database/schema/order.surql", sql: "DEFINE TABLE order SCHEMALESS;" }, EmbeddedSchemaFile { path: "database/schema/invoice.surql", sql: "DEFINE TABLE invoice SCHEMALESS;" }, ]; #[tokio::main] async fn main() -> anyhow::Result<()> { let db = /* connect */; // Establish baseline run_sync_embedded(&db, SOURCE_SCHEMA).await?; // Define the rollout in code let spec = RolloutSpec { id: "add_invoice_table".to_string(), name: "Add invoice table".to_string(), source_schema_hash: String::new(), // skip hash check target_schema_hash: String::new(), compatibility: "phased".to_string(), renames: vec![], steps: vec![ RolloutStep { id: "apply_invoice".to_string(), phase: RolloutPhase::Start, kind: RolloutStepKind::ApplySchema, files: vec![], sql: Some("DEFINE TABLE invoice SCHEMALESS;".to_string()), expect: None, entities: vec![], idempotent: None, }, RolloutStep { id: "rollback_invoice".to_string(), phase: RolloutPhase::Rollback, kind: RolloutStepKind::RemoveEntities, files: vec![], sql: None, expect: None, entities: vec![EntityKey { kind: "table".to_string(), scope: None, name: "invoice".to_string() }], idempotent: None, }, ], }; let vars = TemplateVars::default(); // Start phase (non-destructive expansion) run_start_with_spec(&db, &spec, TARGET_SCHEMA, &vars).await?; // status is now "ready_to_complete" // After application cutover, run complete phase run_complete_with_spec(&db, &spec, &vars).await?; // status is now "completed" // OR: roll back if needed // run_rollback_with_spec(&db, &spec, &vars).await?; Ok(()) } ``` ``` -------------------------------- ### Add surrealkit to project Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit-macros/README.md Add the surrealkit crate to your Cargo.toml. Use `default-features = false` to omit CLI dependencies. ```toml [dependencies] surrealkit = { version = "0.6", default-features = false } ``` -------------------------------- ### Seed Database Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Run database seeding operations on demand using the `surrealkit seed` command. ```sh surrealkit seed ``` -------------------------------- ### Advanced Runtime Schema Sync with run_sync_embedded_with_opts Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Use `run_sync_embedded_with_opts` for fine-grained control over schema synchronization, including options like `prune` to remove obsolete database objects. ```rust use surrealkit::{EmbeddedSchemaFile, SyncOpts, run_sync_embedded_with_opts}; run_sync_embedded_with_opts( &db, SCHEMA, &SyncOpts { watch: false, // ignored for embedded sync debounce_ms: 0, dry_run: false, fail_fast: true, prune: true, // remove DB objects no longer in SCHEMA allow_shared_prune: false, }, ) .await?; ``` -------------------------------- ### Inspect Rollout Status Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Check the current state of rollouts stored in the database using `surrealkit rollout status`. ```sh surrealkit rollout status ``` -------------------------------- ### Configure Vite Plugin for SurrealKit Sync Source: https://context7.com/surrealdb/surrealkit/llms.txt Integrates SurrealKit schema synchronization into Vite's development workflow. Configure options like binary path, environment variables, and sync arguments. ```typescript import { defineConfig } from "vite"; import { surrealkitPlugin } from "vite-plugin-surrealkit"; export default defineConfig({ plugins: [ surrealkitPlugin({ // SurrealKit binary path (default: "surrealkit") binary: "surrealkit", // Working directory for the surrealkit process (default: Vite root) cwd: process.cwd(), // Extra env vars forwarded to the surrealkit process env: { SURREALDB_HOST: "http://localhost:8000", SURREALDB_NAME: "myapp", SURREALDB_NAMESPACE: "dev", SURREALKIT_VAR_SCHEMA_PREFIX: "dev", }, // Additional args appended after `surrealkit sync` syncArgs: ["--var", "env=development"], // Glob patterns that trigger sync (default: ["database/schema/**/*.surql"]) schemaGlobs: ["database/schema/**/*.surql"], // Run modes: "serve" (dev server), "build", or both (default: ["serve"]) include: ["serve", "build"], // Run initial sync on dev server start / build begin (default: true) runOnStartup: true, // Send full-reload to browser after successful sync (default: false) reloadOnSync: true, // Debounce window for dev file-change events in ms (default: 150) debounceMs: 300, // Logging verbosity: "silent" | "error" | "info" | "debug" (default: "info") logLevel: "info", // Fail the Vite build if sync exits non-zero (default: true) failBuildOnError: true, }), ], }); ``` -------------------------------- ### Plan a schema rollout migration Source: https://context7.com/surrealdb/surrealkit/llms.txt Diffs current schema files against a saved snapshot to generate a TOML rollout manifest. It refuses to auto-plan modified or renamed entities, requiring manual manifests for those cases. Supports dry runs. ```sh # Generate a rollout manifest surrealkit rollout plan --name add_customer_indexes ``` ```sh # Dry run: show what would be in the manifest without writing surrealkit rollout plan --name add_customer_indexes --dry-run ``` ```sh # Output: database/rollouts/20260302153045__add_customer_indexes.toml # Example manifest content: # id = "20260302153045__add_customer_indexes" # name = "add_customer_indexes" # compatibility = "phased" # source_schema_hash = "abc123..." # target_schema_hash = "def456..." # # [[steps]] # id = "apply_expand_schema" # phase = "start" # kind = "apply_schema" # files = ["database/schema/customer.surql"] # # [[steps]] # id = "remove_legacy_entities" # phase = "complete" # kind = "remove_entities" # [[steps.entities]] # kind = "field" # scope = "customer" # name = "legacy_column" ``` -------------------------------- ### seed_from_dir Source: https://context7.com/surrealdb/surrealkit/llms.txt Programmatically seed a SurrealDB database from a directory of .surql files, with template variable substitution. Files are executed in alphabetical order. ```APIDOC ## Library API: `seed_from_dir` Programmatically seed a SurrealDB database from a directory of `.surql` files, with template variable substitution. Files are executed in alphabetical order. ```rust use std::path::Path; use std::collections::HashMap; use surrealkit::{seed_from_dir, TemplateVars}; #[tokio::main] async fn main() -> anyhow::Result<()> { let db = /* connect */; // Seed with no variables seed_from_dir(&db, Path::new("database/seed"), &TemplateVars::default()).await?; // Seed with variables let mut vars = HashMap::new(); vars.insert("ENV".to_string(), "staging".to_string()); vars.insert("ADMIN_EMAIL".to_string(), "admin@example.com".to_string()); let template_vars = TemplateVars { vars }; // Seed from a custom directory seed_from_dir(&db, Path::new("fixtures/test_data"), &template_vars).await?; // Output: // Seeding from fixtures/test_data (3 files found) // executing fixtures/test_data/01_users.surql // executing fixtures/test_data/02_products.surql // executing fixtures/test_data/03_orders.surql // Seeded 3 files Ok(()) } ``` ``` -------------------------------- ### Run SurrealKit via Docker Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Execute SurrealKit commands using a Docker container, mounting the local database directory for access. This is useful for CI/CD pipelines or isolated environments. ```sh docker pull ghcr.io/surrealdb/surrealkit:latest docker run --rm -v "$(pwd)/database:/database:ro" ghcr.io/surrealdb/surrealkit:latest \ --host http://host.docker.internal:8000 --ns my_ns --db my_db sync ``` -------------------------------- ### Check All Rollout Statuses Source: https://context7.com/surrealdb/surrealkit/llms.txt Alias for `surrealkit rollout status` without a selector, listing all rollout records from the database. Provides a consolidated view of all deployment rollouts. ```sh surrealkit status ``` -------------------------------- ### SurrealKit Test Global Configuration Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Define default test settings in `database/tests/config.toml`. Supports environment variable fallbacks for base URL and timeout. ```toml [defaults] timeout_ms = 10000 base_url = "http://localhost:8000" [actors.root] kind = "root" ``` -------------------------------- ### Build Template Variables for SurrealQL Substitution Source: https://context7.com/surrealdb/surrealkit/llms.txt Build a variable map from CLI flags, environment variables, and config files for SurrealQL string substitution. Supports escaping with $${VAR} and errors on undefined variables. ```rust use surrealkit::{TemplateVars, build_vars, parse_var_flag}; use std::path::Path; fn main() -> anyhow::Result<()> { // Parse --var KEY=VALUE flags let raw: Vec<(String, String)> = vec!["PREFIX=acme", "ENV=prod"] .iter() .map(|s| parse_var_flag(s)) .collect::>()?; // Merge CLI, SURREALKIT_VAR_* env vars, and surrealkit.toml (priority: CLI > env > toml) let vars_map = build_vars(&raw, Some(Path::new("surrealkit.toml")))?; let vars = TemplateVars { vars: vars_map }; // Apply substitution let sql = "DEFINE TABLE ${prefix}_users SCHEMAFULL;"; let resolved = vars.apply(sql)?; assert_eq!(resolved, "DEFINE TABLE acme_users SCHEMAFULL;"); // Escape: $${VAR} → literal ${VAR} let escaped = vars.apply("SET note = '$${prefix} is literal';")?; assert_eq!(escaped, "SET note = '${prefix} is literal';"); // Undefined variable = hard error let result = vars.apply("${UNDEFINED_VAR}"); assert!(result.is_err()); // error: template variable 'UNDEFINED_VAR' is not defined // (set via --var UNDEFINED_VAR=VALUE, SURREALKIT_VAR_UNDEFINED_VAR env var, or surrealkit.toml [variables]) Ok(()) } ``` -------------------------------- ### Compile-time Schema Embedding with embed_schema! Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Use the `embed_schema!` macro to embed `.surql` files into your binary at build time. The generated `embedded_schema::sync` function applies schema changes at runtime. ```rust surrealkit::embed_schema!(); #[tokio::main] async fn main() -> anyhow::Result<()> { let db = surrealkit::connect(&surrealkit::DbCfg::from_env(None, &Default::default())?).await?; embedded_schema::sync(&db).await?; Ok(()) } ``` ```rust surrealkit::embed_schema!("my/schema/dir"); ``` -------------------------------- ### SurrealKit Rollout Data Types Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Import necessary types for defining rollouts entirely in code, including specifications, steps, phases, step kinds, and entity keys. ```rust use surrealkit::{ RolloutPhase, RolloutSpec, RolloutStep, RolloutStepKind, schema_state::EntityKey, }; ``` -------------------------------- ### Connect to In-Process SurrealDB Source: https://github.com/surrealdb/surrealkit/blob/main/crates/surrealkit/README.md Constructs a `surrealdb::Surreal` instance directly for in-process databases like `kv-mem` or `kv-rocksdb`. This instance can then be passed to SurrealKit library functions. Ensure to use `db.use_ns` and `db.use_db` to set the namespace and database. ```rust use surrealdb::{Surreal, engine::any::connect, opt::Config}; use surrealdb::opt::capabilities::Capabilities; let db = connect(("mem://", Config::new().capabilities(Capabilities::all()))).await?; db.use_ns("my_ns").use_db("my_db").await?; surrealkit::run_sync_embedded(&db, SCHEMA).await?; ``` -------------------------------- ### Run SurrealKit Tests Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Execute the SurrealKit test runner. This command discovers and runs declarative TOML test suites. ```sh surrealkit test ``` -------------------------------- ### Docker Compose for Schema Sync Before Tests Source: https://context7.com/surrealdb/surrealkit/llms.txt Orchestrates SurrealDB, SurrealKit, and application tests using Docker Compose. Ensures schema synchronization completes successfully before running tests. ```yaml # docker-compose.yml — schema sync before running tests services: surrealdb: image: surrealdb/surrealdb:latest command: start --user root --pass root memory healthcheck: test: ["CMD", "/surreal", "is-ready"] interval: 1s timeout: 5s retries: 30 surrealkit: image: ghcr.io/surrealdb/surrealkit:latest depends_on: surrealdb: condition: service_healthy volumes: - ./database:/database:ro command: - --host=http://surrealdb:8000 - --ns=myns - --db=mydb - --user=root - --pass=root - sync # surrealkit exits on completion; compose moves on to next dependent service app_tests: image: my-test-runner depends_on: surrealkit: condition: service_completed_successfully ``` -------------------------------- ### Seed SurrealDB Database Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes `.surql` files from `database/seed/` in alphabetical order with template variable substitution. Files are executed independently to manage memory for large datasets. ```sh surrealkit seed # With variables surrealkit seed --var env=staging --var default_password=dev123 # Directory structure: # database/seed/ # 01_users.surql # 02_products.surql # 03_orders.surql # Example seed file (database/seed/01_users.surql): # CREATE user:alice SET name = 'Alice', role = '${role}'; # CREATE user:bob SET name = 'Bob', role = '${role}'; ``` -------------------------------- ### Lint Rollout Manifest Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Validate a rollout manifest without mutating the database by running `surrealkit rollout lint `. ```sh surrealkit rollout lint 20260302153045__add_customer_indexes ``` -------------------------------- ### Synchronize Local Database Schema Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Use `surrealkit sync` to reconcile local or disposable databases with changed schema files. It automatically prunes SurrealKit-managed objects deleted from `database/schema`. ```sh surrealkit sync ``` -------------------------------- ### Synchronize schema with SurrealDB Source: https://context7.com/surrealdb/surrealkit/llms.txt Applies changed .surql schema files to the database, automatically pruning deleted entities. Supports watch mode, dry runs, and skipping pruning. Connection details can be overridden via CLI flags or environment variables. Template variables can also be substituted. ```sh # Basic sync (one-shot) surrealkit sync ``` ```sh # Watch mode: polls every 1000 ms and syncs on any change surrealkit sync --watch --debounce-ms 500 ``` ```sh # Dry run: show what would change without applying surrealkit sync --dry-run ``` ```sh # Skip pruning stale managed entities surrealkit sync --no-prune ``` ```sh # Allow pruning against a shared/production database (use with caution) surrealkit sync --allow-shared-prune ``` ```sh # Override connection from CLI surrealkit --host http://localhost:8000 --ns myns --db mydb --user root --pass root sync ``` ```sh # With template variable substitution surrealkit sync --var schema_prefix=acme --var env=staging ``` ```sh # Environment variable configuration SURREALDB_HOST=http://db:8000 SURREALDB_NAME=prod SURREALDB_NAMESPACE=app \ SURREALDB_USER=root SURREALDB_PASSWORD=secret surrealkit sync ``` -------------------------------- ### Configure vite-plugin-surrealkit in vite.config.ts Source: https://github.com/surrealdb/surrealkit/blob/main/packages/vite-plugin-surrealkit/README.md Import and add the `surrealkitPlugin` to your Vite configuration. You can optionally pass arguments to `surrealkit sync` via `syncArgs`. ```ts // vite.config.ts import { defineConfig } from 'vite'; import { surrealkitPlugin } from 'vite-plugin-surrealkit'; export default defineConfig({ plugins: [ surrealkitPlugin({ // Optional: pass flags to `surrealkit sync` syncArgs: ['--allow-shared-prune'], }), ], }); ``` -------------------------------- ### Run SurrealDB Declarative Tests Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes declarative TOML test suites from `database/tests/suites/` in isolated ephemeral SurrealDB namespaces. Exits with a non-zero status code if any test case fails. ```sh # Run all suites surrealkit test # Filter by suite name glob surrealkit test --suite "security_*" # Filter by case name glob surrealkit test --case "*permission*" # Filter by tag surrealkit test --tag smoke --tag security # Parallel execution surrealkit test --parallel 4 # Fail on first failure surrealkit test --fail-fast # Generate JSON report for CI surrealkit test --json-out database/tests/report.json # Skip setup/sync/seed phases surrealkit test --no-setup --no-sync --no-seed # Keep ephemeral databases after run (for debugging) surrealkit test --keep-db # Override HTTP base URL for api_request cases surrealkit test --base-url http://localhost:3000 # Set per-case timeout surrealkit test --timeout-ms 30000 ``` -------------------------------- ### SurrealkitPluginOptions Interface Source: https://github.com/surrealdb/surrealkit/blob/main/packages/vite-plugin-surrealkit/README.md Defines the available options for configuring the `surrealkitPlugin`, including binary path, environment variables, schema globs, and run modes. ```ts type RunMode = 'serve' | 'build'; type LogLevel = 'silent' | 'error' | 'info' | 'debug'; interface SurrealkitPluginOptions { binary?: string; cwd?: string; env?: Record; syncArgs?: string[]; schemaGlobs?: string[]; include?: RunMode[]; runOnStartup?: boolean; reloadOnSync?: boolean; debounceMs?: number; logLevel?: LogLevel; failBuildOnError?: boolean; } ``` -------------------------------- ### Complete SurrealDB Rollout Phase Source: https://context7.com/surrealdb/surrealkit/llms.txt Executes the destructive contraction phase of a rollout, removing legacy entities after application cutover. This command is destructive and should be used with caution. ```sh surrealkit rollout complete 20260302153045__add_customer_indexes # Output: Completed rollout 20260302153045__add_customer_indexes. ``` -------------------------------- ### Verify Schema Metadata with schema_metadata Source: https://context7.com/surrealdb/surrealkit/llms.txt Use the `schema_metadata` test case to verify that `INFO FOR DB` or `INFO FOR TABLE` output contains expected entity names. The `contains` field accepts an array of strings to match against the output. ```toml [[cases]] name = "metadata_contains_expected_entities" kind = "schema_metadata" actor = "root" sql = "INFO FOR DB;" contains = ["customer", "fn::format_customer", "v1"] [[cases]] name = "customer_table_has_required_fields" kind = "schema_metadata" actor = "root" table = "customer" # shorthand: generates "INFO FOR TABLE customer;" contains = ["name", "age", "joined_at", "tier"] ``` -------------------------------- ### SurrealKit Actor Configurations Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Define different types of actors for testing, including database credentials, record-based access, JWT tokens, and custom headers. ```toml [actors.reader] kind = "database" namespace = "app" database = "main" username_env = "TEST_DB_READER_USER" password_env = "TEST_DB_READER_PASS" [actors.access_user] kind = "record" access = "app_access" signup_params = { email = "viewer@example.com", password = "viewer-password" } signin_params = { email = "viewer@example.com", password = "viewer-password" } [actors.jwt_actor] kind = "token" token_env = "TEST_API_JWT" [actors.custom_client] kind = "headers" headers = { "x-tenant-id" = "tenant_a" } ``` -------------------------------- ### SurrealDB Template Variable Resolution Source: https://context7.com/surrealdb/surrealkit/llms.txt Demonstrates how template variables `${VAR_NAME}` in `.surql` files are resolved. CLI flags have the highest priority, followed by environment variables, then `surrealkit.toml`. ```toml # surrealkit.toml [variables] schema_prefix = "myapp" talent_username = "talent_rw" environment = "development" ``` ```sql -- database/schema/tables.surql DEFINE TABLE ${schema_prefix}_users SCHEMAFULL; DEFINE TABLE ${schema_prefix}_orders SCHEMAFULL; -- Escape: $${MY_VAR} passes through as literal ${MY_VAR} SET note = 'literal $${schema_prefix} token'; ``` ```sh # CLI flag (highest priority) surrealkit sync --var schema_prefix=acme --var environment=prod # Environment variable (middle priority) export SURREALKIT_VAR_SCHEMA_PREFIX=acme export SURREALKIT_VAR_ENVIRONMENT=prod surrealkit sync # Undefined variables are always a hard error: # error: template variable 'SCHEMA_PREFIX' is not defined # (set via --var SCHEMA_PREFIX=VALUE, SURREALKIT_VAR_SCHEMA_PREFIX env var, or surrealkit.toml [variables]) ``` -------------------------------- ### Embed Schema with Macro Source: https://context7.com/surrealdb/surrealkit/llms.txt Uses a proc-macro to read `.surql` files from a directory at compile time, generating an `embedded_schema` module. This module provides a `SCHEMA` static and an async `sync(db)` function for applying the schema. ```rust // In your library or binary crate: use surrealkit::embed_schema; // Embed from default path "database/schema" embed_schema!(); // Or specify a custom path embed_schema!("my_app/schema"); // The macro generates: // pub mod embedded_schema { // pub static SCHEMA: &[EmbeddedSchemaFile] = &[...]; // pub async fn sync(db: &Surreal) -> anyhow::Result<()> { ... } // } #[tokio::main] async fn main() -> anyhow::Result<()> { let db = /* connect to SurrealDB */; // Apply all embedded schema files embedded_schema::sync(&db).await?; // Or access the raw files for file in embedded_schema::SCHEMA { println!("embedded: {} ({} bytes)", file.path, file.sql.len()); } Ok(()) } ``` -------------------------------- ### Check SurrealDB Rollout Status Source: https://context7.com/surrealdb/surrealkit/llms.txt Inspects rollout state persisted in the database, including step-level progress, timestamps, and errors. Useful for monitoring ongoing or completed rollouts. ```sh # List all rollouts surrealkit rollout status # Filter to one rollout surrealkit rollout status 20260302153045__add_customer_indexes # Example output: # __rollout:20260302153045__add_customer_indexes [completed] add_customer_indexes # started_at: 2026-03-02T15:30:45Z # completed_at: 2026-03-02T15:35:12Z # - apply_expand_schema [start:apply_schema] completed # - remove_legacy_entities [complete:remove_entities] completed ``` -------------------------------- ### Generate JSON Test Reports Source: https://github.com/surrealdb/surrealkit/blob/main/README.md Run SurrealKit tests and output a machine-readable JSON report to a specified file. The command exits with a non-zero status code if any tests fail. ```sh surrealkit test --json-out database/tests/report.json ```