Skip to content

k.DB.sqlite ​

SQLite database operations — lightweight relational database requiring no configuration

Execution ContextPrerequisitesTypical Use
Server-side KScript (k.api, <script env="server">, scheduled jobs)Built-in SQLite works out of the box with no connection string; use indexedDb for object logs or k.DB.sql to follow site default DBRelational schema storage, parameterized SQL (@param), JOINs, transactions, and same-org attach()

Quick Start ​

Create a table and run a parameterized insert and select query:

js
k.api.post(() => {
    k.DB.sqlite.execute(
        "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, status INTEGER)"
    )
    const inserted = k.DB.sqlite.execute(
        "INSERT INTO users (name, status) VALUES (@name, @status)",
        { name: "kooboo", status: 1 }
    )
    const rows = k.DB.sqlite.query("SELECT id, name FROM users WHERE status = @status", { status: 1 })
    return { inserted, rows }
})

Quick Reference ​

Method / PropertyDescriptionReturns
getTables()Returns all table names in the current SQLite databasestring[]
getTable(name)Returns a lazy ITable wrapper (getLogs/getByLog always return null)ITable
query(sql, param?)Runs parameterized SQL and returns an array of row objectsIDynamicTableObject[]
get(sql, param?)Runs SQL and returns the first matching row, or nullIDynamicTableObject | null
value(sql, param?)Runs SQL and returns the first column of the first rowany
execute(sql, param?)Runs writes or DDL and returns affected row count (0 for CREATE TABLE)number
attach(siteNameOrId, alias?)Attaches another same-org site's SQLite DB for cross-site queriesSqliteDatabase
procedure(sql, param?)Inherited stored-procedure call (throws on SQLite)any
operators()Returns uppercase filter operator constants for getTable()Operators
transaction(action)Runs statements inside a transaction (commits on return, aborts on throw)void

Methods ​

getTables() ​

Returns all table names in the current SQLite database.

Parameters: None.

Returns: string[] — Array of table names.

js
k.api.get(() => {
    const tables = k.DB.sqlite.getTables()
    return { tables }
})

getTable(name) ​

Gets an ITable wrapper for the specified table for object CRUD, chained queries, or pagination.

Relational table wrapper notes

  1. getTable(name) returns a lazy table wrapper without checking whether the physical table exists (!!k.DB.sqlite.getTable(name) is always true; use getTables() to check existence).
  2. getLogs(id) and getByLog(logId) on k.DB.sqlite.getTable(name) (as well as on mysql, sqlServer, and sql tables) unconditionally return null; change logs apply only to k.DB.indexedDb.
ParameterTypeRequiredDescription
namestringYesTable name

Returns: ITable — Table object.

js
k.api.get(() => {
    const tables = k.DB.sqlite.getTables()
    const userTable = k.DB.sqlite.getTable("users")
    return {
        exists: tables.indexOf("users") >= 0,
        hasQueryMethod: typeof userTable.query === "function"
    }
})

query(sql, param?) ​

Executes a SQL query and returns an array of row objects (IDynamicTableObject[]).

ParameterTypeRequiredDescription
sqlstringYesSQL query statement
paramobjectNoOptional parameter object bound via @name placeholders (supports array expansion for IN (@ids))

Returns: IDynamicTableObject[] — Query result array; returns [] when no rows match.

js
k.api.get(() => {
    const users = k.DB.sqlite.query(
        "SELECT * FROM users WHERE status = @status",
        { status: 1 }
    )
    return { users }
})

get(sql, param?) ​

Executes a SQL query and returns the first matching row, or null when no rows match.

ParameterTypeRequiredDescription
sqlstringYesSQL query statement
paramobjectNoOptional parameter object bound via @name placeholders

Returns: IDynamicTableObject | null — First matching row object, or null when empty.

js
k.api.get(() => {
    const row = k.DB.sqlite.get(
        "SELECT @id AS id, @name AS name",
        { id: 42, name: "alpha" }
    )
    return { row }
})

value(sql, param?) ​

Executes a SQL query and returns the scalar value in the first column of the first row, or null when no rows match or the value is NULL.

ParameterTypeRequiredDescription
sqlstringYesSQL query statement
paramobjectNoOptional parameter object bound via @name placeholders

Returns: any — Scalar value from the first column of the first row, or null.

js
k.api.get(() => {
    const total = k.DB.sqlite.value("SELECT COUNT(1) FROM users")
    return { total }
})

execute(sql, param?) ​

Executes a write statement or DDL statement (such as CREATE, INSERT, UPDATE, or DELETE) and returns the number of affected rows.

ParameterTypeRequiredDescription
sqlstringYesWrite or DDL SQL statement
paramobjectNoOptional parameter object bound via @name placeholders

Returns: number — Affected row count (not a general success boolean: CREATE TABLE returns 0; INSERT / UPDATE / DELETE return the number of modified rows, or 0 when no rows matched).

js
k.api.post(() => {
    const created = k.DB.sqlite.execute(
        "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"
    )
    const inserted = k.DB.sqlite.execute(
        "INSERT INTO users (name) VALUES (@name)",
        { name: "kooboo" }
    )
    return { created, inserted }
})

attach(siteNameOrId, alias?) ​

Attaches another site's SQLite database in the same organization as alias, allowing a single SQL statement to query both the current site and the attached site.

ParameterTypeRequiredDescription
siteNameOrIdstringYesTarget site name or site ID (must belong to the current organization, and its SQLite database file must already exist)
aliasstringNoDatabase alias; defaults to the sanitized site name. Must start with a letter or underscore, contain only letters, digits, and underscores, and cannot be main or temp

Returns: SqliteDatabase — Returns the current database instance for chaining (e.g. attach(...).query(...)). Unqualified table names still resolve to the current site, while attached tables are referenced as {alias}.{table}. Attachments are scoped to the current request context.

js
k.api.get(() => {
    const siteName = k.site.webSite.name
    const row = k.DB.sqlite
        .attach(siteName, "self_db")
        .get("SELECT COUNT(1) AS cnt FROM self_db.sqlite_master WHERE type='table'")
    return { siteName, tableCount: row ? row.cnt : 0 }
})

procedure(sql, param?) ​

Stored-procedure execution method inherited from the relational database interface.

Stored procedures are not supported by SQLite

SQLite does not support stored procedures (CommandType.StoredProcedure). Calling procedure() on k.DB.sqlite throws "The CommandType 'StoredProcedure' is not supported."; this method is supported on k.DB.mysql and k.DB.sqlServer.

ParameterTypeRequiredDescription
sqlstringYesStored procedure name
paramobjectNoOptional parameter object

Returns: any — Stored procedure query result.

js
k.api.get(() => {
    try {
        return k.DB.sqlite.procedure("sp_demo")
    } catch (e) {
        return { error: String(e && e.message ? e.message : e) }
    }
})

operators() ​

Returns the query operator constants (Operators) with uppercase property names (EQ, NE, GT, GTE, LT, LTE, CONTAINS, STARTS_WITH, AND, OR) for building filter objects with getTable(name).

Parameters: None.

Returns: Operators — Query operator constants object.

js
k.api.get(() => {
    const ops = k.DB.sqlite.operators()
    return { hasEQ: "EQ" in ops, eqValue: ops.EQ }
})

transaction(action) ​

Executes a set of database operations inside a transaction. Statements inside action share the same transaction context; the transaction commits when the callback returns normally and is not committed if an exception is thrown.

ParameterTypeRequiredDescription
actionFunctionYesCallback function executed inside the transaction

Returns: void.

js
k.api.post(() => {
    k.DB.sqlite.transaction(() => {
        k.DB.sqlite.execute("INSERT INTO users(name) VALUES (@name)", { name: "A" })
        k.DB.sqlite.execute("INSERT INTO users(name) VALUES (@name)", { name: "B" })
    })
    return { success: true }
})

Common Usage ​

Initialize Table Schema ​

js
k.DB.sqlite.execute(`
    CREATE TABLE IF NOT EXISTS logs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        level TEXT,
        message TEXT,
        createdAt TEXT
    )
`)

Pagination Query Example ​

js
k.api.get(() => {
    const page = 1
    const size = 20
    const offset = (page - 1) * size

    const items = k.DB.sqlite.query(
        "SELECT id, level, message, createdAt FROM logs ORDER BY id DESC LIMIT @size OFFSET @offset",
        { size, offset }
    )

    return { page, size, items }
})

Notes ​

  1. Parameterized queries: Bind values using @param placeholders instead of string concatenation.
  2. Create tables first: Ensure tables exist before running business SQL queries.
  3. Return value semantics: query() returns an array; get() returns the first row or null; value() returns a scalar or null; execute() returns the affected row count (0 for CREATE TABLE).
  4. Exception handling: Wrap database operations with try/catch at API boundaries.

TypeScript Definitions ​

ts
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): any;
    procedure(sql: string, param?: any): any;
    operators(): Operators;
    transaction(action: Function): void;
}