Skip to content

k.DB ​

Database operations — unified interface for site built-in and external databases

Execution ContextPrerequisitesTypical Use
Server-side KScript (k.api, <script env="server">, scheduled jobs)Built-in indexedDb/keyValue/sqlite/sequenceDb work out of the box; external DBs require connection stringsPick the right store: indexedDb for object tables, sqlite/sql for SQL, keyValue for short strings, sequenceDb for append logs

Quick Start ​

Use k.DB.sql (which defaults to the site's built-in SQLite when no external relational DB is configured) to list tables and run a parameterized query:

js
k.api.get(() => {
    const tables = k.DB.sql.getTables()
    const rows = k.DB.sql.query("SELECT @n AS n", { n: 1 })
    return { tables, rows }
})

Quick Reference ​

Method / PropertyDescriptionReturns
indexedDbSite dynamic tables (admin schema + dynamic add columns + 99-entry logs)k.DB.indexedDb
keyValueLightweight string key-value store (4096-byte value limit, schemaless)k.DB.keyValue
sqliteBuilt-in relational SQLite database (handwritten SQL, transactions, attach)k.DB.sqlite
sequenceDbSite-local sequential key-value store (1-based numeric keys & range scans)k.DB.sequenceDb
sqlRelational entry routed by the site's Default database setting (defaults to SQLite)IRelationalDatabase
mysqlExternal MySQL database (requires connection string; throws if unconfigured)MysqlDatabase
sqlServerExternal SQL Server database (requires connection string; same API as mysql)SqlServerDatabase
mongoExternal MongoDB database (exposes runCommand and IDatabase)MongoDatabase
redisExternal Redis connection (getDatabase(db) exposes 13 string operations)RedisConnection

Selection Guide ​

ScenarioRecommended EntryNotes
Admin-visible tables, object CRUD, and change historyk.DB.indexedDbBest for dynamic fields, table relations, and getLogs() audit snapshots
Simple flags, counters, or small JSON configs (<= 4096 bytes)k.DB.keyValueSchemaless string key-value pairs with zero table setup
Handwritten SQL, JOINs, transactions, or cross-site queriesk.DB.sqliteBuilt-in relational SQLite with @param binding and same-org attach()
Append-heavy logs, event streams, or numeric-key range scansk.DB.sequenceDbLocal .data files optimized for sequential appends and range/findAll
Switchable SQLite / MySQL / SQL Server by site default settingk.DB.sqlKeeps relational SQL portable across environments
External MySQL / SQL Server / MongoDB / Redisk.DB.{mysql,sqlServer,mongo,redis}Requires connection strings in Integrations · Database

Overview ​

k.DB provides access to Kooboo's built-in databases and external database/cache integrations:

  • IndexedDB (site dynamic tables) — Create tables in IndexedDB Tables and access them in scripts via k.DB.indexedDb.{tableName}
  • KeyValue (site key-value store) — Lightweight string key-value storage via k.DB.keyValue
  • SQLite — Works out of the box with no configuration via k.DB.sqlite
  • SequenceDb (sequential key-value store) — Site-local sequential data files working out of the box via k.DB.sequenceDb
  • Default relational entry (k.DB.sql) — Automatically routes based on the site's Default database setting; defaults to SQLite when no external relational database is configured
  • MySQL / SQL Server / MongoDB / Redis — Requires configuring connection strings in Integrations · Database (admin table views: MySQL Tables, SQL Server Tables)

Default Relational Entry (k.DB.sql) ​

k.DB.sql resolves to the relational database selected by the site's Default database setting (Auto / Sqlite / Mysql / SqlServer). On a site without MySQL or SQL Server connection strings configured (default Auto mode), k.DB.sql resolves to the site's SQLite database and supports shared relational methods such as getTables(), getTable(), query(), execute(), operators(), and procedure():

js
k.api.get(() => {
    const tables = k.DB.sql.getTables()
    const rows = k.DB.sql.query("SELECT 1 AS n")
    return { tables, rows }
})

Multi-database configuration note

When the site's default database is Auto and both MySQL and SQL Server connection strings are configured, accessing k.DB.sql throws an error asking you to select the default database explicitly in site settings.

External Database & Cache Prerequisites ​

Before using k.DB.mysql, k.DB.sqlServer, k.DB.mongo, or k.DB.redis, configure the corresponding connection string in Integrations · Database:

EntryTypePrerequisites & Behavior
k.DB.mysqlMysqlDatabaseRequires a MySQL connection string; accessing the property without one throws an initialization error. Supports getTables, getTable, query, execute, get, value, procedure, transaction, and operators.
k.DB.sqlServerSqlServerDatabaseRequires a SQL Server connection string; accessing the property without one throws an initialization error. Shares the same relational API as k.DB.mysql.
k.DB.mongoMongoDatabaseRequires a MongoDB connection string; accessing the property without one throws an initialization error. Implements IDatabase (getTables, getTable, operators) and adds runCommand(commandObject).
k.DB.redisRedisConnectionRequires a Redis connection string; calling k.DB.redis.getDatabase(db) without one throws an initialization error. RedisDatabase exposes 13 string operations (stringGet, stringSet, stringDelete, etc.).

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KDB {
    /** Site IndexedDB dynamic tables (table name as property) */
    indexedDb: IDatabase;
    /** Site key-value storage */
    keyValue: kKeyValue;
    /** Site built-in SQLite database */
    sqlite: SqliteDatabase;
    /** Site-local sequential key-value database */
    sequenceDb: KWormDb;
    /** Relational database entry selected by site default database setting */
    sql: IRelationalDatabase;
    /** External MySQL database (requires connection string) */
    mysql: MysqlDatabase;
    /** External SQL Server database (requires connection string) */
    sqlServer: SqlServerDatabase;
    /** External MongoDB database (requires connection string) */
    mongo: MongoDatabase;
    /** External Redis connection (requires connection string) */
    redis: RedisConnection;
}

interface IRelationalDatabase extends IDatabase {
    query(sql: string, param?: any): IDynamicTableObject[];
    execute(sql: string, param?: any): number;
    procedure(sql: string, param?: any): any;
}

interface SqliteDatabase extends IRelationalDatabase, IDatabase {
    getTables(): string[];
    attach(siteNameOrId: string, alias?: string): SqliteDatabase;
    getTable(name: string): ITable;
    query(sql: string, param?: any): IDynamicTableObject[];
    query<T>(sql: string, param?: any): T;
    get(sql: string, param?: any): IDynamicTableObject;
    get<T>(sql: string, param?: any): T;
    value(sql: string, param?: any): any;
    value<T>(sql: string, param?: any): T;
    execute(sql: string, param?: any): number;
    procedure(sql: string, param?: any): any;
    operators(): Operators;
    transaction(action: Function): void;
}

interface MongoDatabase extends IDatabase {
    getTables(): string[];
    getTable(name: string): ITable;
    operators(): Operators;
    runCommand(commandObject: CommandObject): CommandResult;
}

interface RedisConnection {
    getDatabase(db: number): RedisDatabase;
}

interface RedisDatabase {
    stringAppend(key: string, value: string): number;
    stringDecrement(key: string, value?: number): number;
    stringDelete(key: string): boolean;
    stringGet(key: string): string;
    stringGetDelete(key: string): string;
    stringGetWithExpiry(key: string): ValueWithExpiry;
    stringGetSetExpiry(key: string, expirySeconds: number): string;
    stringGetRange(key: string, start: number, end: number): string;
    stringGetSet(key: string, value: string): string;
    stringIncrement(key: string, value?: number): number;
    stringSet(key: string, value: string, expirySeconds?: number): boolean;
    stringSetRange(key: string, offset: number, value: string): string;
    stringLength(key: string): number;
}