k.DB.sqlite
SQLite database operations — lightweight relational database requiring no configuration
| Execution Context | Prerequisites | Typical 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 DB | Relational schema storage, parameterized SQL (@param), JOINs, transactions, and same-org attach() |
Quick Start
Create a table and run a parameterized insert and select query:
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 / Property | Description | Returns |
|---|---|---|
getTables() | Returns all table names in the current SQLite database | string[] |
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 objects | IDynamicTableObject[] |
get(sql, param?) | Runs SQL and returns the first matching row, or null | IDynamicTableObject | null |
value(sql, param?) | Runs SQL and returns the first column of the first row | any |
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 queries | SqliteDatabase |
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.
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
getTable(name)returns a lazy table wrapper without checking whether the physical table exists (!!k.DB.sqlite.getTable(name)is alwaystrue; usegetTables()to check existence).getLogs(id)andgetByLog(logId)onk.DB.sqlite.getTable(name)(as well as onmysql,sqlServer, andsqltables) unconditionally returnnull; change logs apply only tok.DB.indexedDb.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Table name |
Returns: ITable — Table object.
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[]).
| Parameter | Type | Required | Description |
|---|---|---|---|
sql | string | Yes | SQL query statement |
param | object | No | Optional parameter object bound via @name placeholders (supports array expansion for IN (@ids)) |
Returns: IDynamicTableObject[] — Query result array; returns [] when no rows match.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
sql | string | Yes | SQL query statement |
param | object | No | Optional parameter object bound via @name placeholders |
Returns: IDynamicTableObject | null — First matching row object, or null when empty.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
sql | string | Yes | SQL query statement |
param | object | No | Optional parameter object bound via @name placeholders |
Returns: any — Scalar value from the first column of the first row, or null.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
sql | string | Yes | Write or DDL SQL statement |
param | object | No | Optional 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).
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
siteNameOrId | string | Yes | Target site name or site ID (must belong to the current organization, and its SQLite database file must already exist) |
alias | string | No | Database 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.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
sql | string | Yes | Stored procedure name |
param | object | No | Optional parameter object |
Returns: any — Stored procedure query result.
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.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | Function | Yes | Callback function executed inside the transaction |
Returns: void.
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
k.DB.sqlite.execute(`
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
level TEXT,
message TEXT,
createdAt TEXT
)
`)Pagination Query Example
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
- Parameterized queries: Bind values using
@paramplaceholders instead of string concatenation. - Create tables first: Ensure tables exist before running business SQL queries.
- Return value semantics:
query()returns an array;get()returns the first row ornull;value()returns a scalar ornull;execute()returns the affected row count (0forCREATE TABLE). - Exception handling: Wrap database operations with
try/catchat API boundaries.
TypeScript Definitions
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;
}Related Docs
- k.DB — Database overview and entry points
- CMS: SQLite Tables — Admin table schema and CSV import
- k.DB.indexedDb — IndexedDB dynamic tables
- k.content — Content Management API