k.DB.indexedDb
Site IndexedDB dynamic tables — shares the same data store as IndexedDB Tables in the admin UI
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Server-side KScript (k.api, <script env="server">, scheduled jobs) | No connection string required; first access auto-creates tables; use k.DB.sqlite for SQL/JOINs or k.DB.keyValue for short strings | Admin-visible table CRUD, chained/paged queries, table relations, and 99-entry change history |
Quick Start
Insert, read back, and query records in the dynamic orders table:
k.api.post(() => {
const table = k.DB.indexedDb.orders
const id = table.add({ orderNo: "A1001", amount: 99, status: "paid" })
const row = table.get(id)
const paid = table.findAll("status == 'paid'")
return { id, row, paidCount: paid.length }
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
[tableName] / getTable(name) | Gets a dynamic table handle (auto-creates on first access) | ITable |
getTables() | Lists all dynamic table names (including internal _sys_* tables) | string[] |
operators() | Returns uppercase operator constants (EQ, GT, CONTAINS, etc.) | Operators |
table.add(value) | Inserts a record and expands table columns for undeclared fields | string | null |
table.append(value) | Inserts a record without changing schema (ignores undeclared fields) | string | null |
table.update(id, value) / table.update(value) | Updates a record by _id/primary key or by value._id | void |
table.delete(id) | Deletes a record by _id or primary key | void |
table.get(id) | Reads a single record by _id or business primary key | IDynamicTableObject | null |
table.find(...) / table.findAll(...) | Queries first/all records by condition string, field+value, or filter object | IDynamicTableObject / IDynamicTableObject[] |
table.all() / table.count(...) | Reads all rows or counts matching rows | IDynamicTableObject[] / number |
table.query(...) | Builds a chained query (where, orderBy, skip, take, count, all) | ITableQuery |
table.pagination(pageIndex, pageSize, where?) | Paged query (pageIndex starts at 1) | PaginationModel |
table.createIndex(fieldName) | Creates an additional index on a column | void |
table.getLogs(id) / table.getByLog(logId) | Reads up to 99 edit logs or retrieves a historical record snapshot | ChangeLog[] | null / IDynamicTableObject | null |
Admin schema vs. k.DB.sqlite
Column types, primary keys, unique constraints, and indexes are maintained in CMS: IndexedDB Tables. Script add() expands undeclared columns automatically, while append() ignores them. Compared with k.DB.sqlite, indexedDb targets object CRUD and change history, whereas sqlite targets SQL queries and transactions.
Accessing Tables
[tableName] / getTable() / getTables()
Access a table as a property on k.DB.indexedDb or via getTable(name). getTables() returns the list of all dynamic table names created in the current site (including internal _sys_* tables such as _sys_keyvalues).
| Method | Parameters | Required | Description |
|---|---|---|---|
getTable(name) | name: string | Yes | Target table name; auto-creates the table if missing. |
getTables() | None | — | Lists all dynamic table names (including _sys_* internal tables). |
Returns: getTable returns ITable; getTables returns string[].
k.api.get(() => {
const orders = k.DB.indexedDb.orders
const orders2 = k.DB.indexedDb.getTable("orders")
return {
sameTable: !!orders && !!orders2,
tables: k.DB.indexedDb.getTables()
}
})Writing & Updating
add(value)
Inserts a record. If the object contains fields not yet defined in the table, the table schema is automatically updated with new columns.
| Parameter | Type | Required | Description |
|---|---|---|---|
value | object | Yes | Record object to insert. Object fields map to table columns; undeclared fields trigger schema expansion. |
Returns: string | null. New record ID (Guid string), or null on failure.
const id = k.DB.indexedDb.orders.add({
orderNo: "A1001",
amount: 99
})append(value)
Similar to add(), except it does not modify the table schema for new fields; fields not declared in the table schema are ignored and not persisted.
| Parameter | Type | Required | Description |
|---|---|---|---|
value | object | Yes | Record object to insert. Fields should already be declared in the table schema. |
Returns: string | null. New record ID (Guid string), or null on failure.
const id = k.DB.indexedDb.orders.append({ orderNo: "A1002", amount: 120 })update(id, value) / update(value)
Updates a record by _id, primary key, or the _id property inside value.
| Method | Parameters | Description |
|---|---|---|
update(id, value) | id: any, value: object | Locates the record by _id or primary key and updates it with value. |
update(value) | value: object | Updates the record identified by _id in the object; without a matching _id, no record is matched or inserted. |
Returns: void.
const table = k.DB.indexedDb.orders
const id = table.add({ orderNo: "A1003", status: "new" })
table.update(id, { orderNo: "A1003", status: "paid" })
const row = table.get(id)
row.status = "shipped"
table.update(row)delete(id)
Deletes a record by _id or primary key.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | any | Yes | _id or primary key value of the record to delete. |
Returns: void.
k.DB.indexedDb.orders.delete(id)Querying
get(id)
Gets a single record by _id or business primary key; returns null when the record does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | any | Yes | _id or primary key value of the record to read. |
Returns: IDynamicTableObject | null. Matching record object, or null when not found.
const row = k.DB.indexedDb.orders.get(id)
const summary = row ? { id: row._id, orderNo: row.orderNo } : nullfind / findAll
Supports three query forms: condition strings (==, >=, >, <, <=, contains, startwith, combined with &&), field name + equality value, and filter objects built with operators() (EQ, NE, GT, GTE, LT, LTE, CONTAINS, STARTS_WITH, AND, OR).
| Overload | Parameters | Description |
|---|---|---|
find(query) / findAll(query) | query: string | Condition string (e.g. "amount >= 100 && status == 'paid'"). |
find(field, value) / findAll(field, value) | field: string, value: any | Field name and equality match value. |
find(filter) / findAll(filter) | filter: Record<string, any> | Filter object constructed using operators(). |
Returns: find returns IDynamicTableObject | null; findAll returns IDynamicTableObject[].
// 1. Condition string
const one = k.DB.indexedDb.orders.find("orderNo == 'A1001'")
const many = k.DB.indexedDb.orders.findAll("amount >= 100 && status == 'paid'")
// 2. Field name + value
const byField = k.DB.indexedDb.orders.find("orderNo", "A1001")
const manyByField = k.DB.indexedDb.orders.findAll("status", "paid")
// 3. Filter object (with operators)
const { GT, CONTAINS } = k.DB.indexedDb.operators()
const gtOne = k.DB.indexedDb.orders.find({ amount: { [GT]: 100 } })
const containsMany = k.DB.indexedDb.orders.findAll({
name: { [CONTAINS]: "kooboo" }
})all()
Returns all records in the table (use with caution on large tables).
Parameters: None.
Returns: IDynamicTableObject[]. All records in the table.
const all = k.DB.indexedDb.orders.all()count(query) / count(filter)
Returns the number of records matching the condition (backed by query().count(), so table.count(), query().count(), and pagination() totals are capped at 99,999 rows).
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes (string overload) | Condition string, e.g. status == 'paid'; pass "" to count all rows. |
filter | Record<string, any> | Yes (object overload) | Filter object, typically built with operators(). |
Returns: number. Number of matching records (up to 99999).
const n = k.DB.indexedDb.orders.count("status == 'paid'")Chained Queries, Pagination & Indexes
Chained Query (query)
Builds a chained query with filtering, sorting, skipping, and taking.
| Method | Description |
|---|---|
query() / query(string) / query(filter) | Constructs a query object |
where(string) / where(filter) | Sets the filter condition (calling .where() repeatedly overwrites the previous condition instead of AND-combining; put combined conditions in a single .where() call) |
orderBy(fieldName) / orderByDescending(fieldName) | Sorts ascending or descending by field |
skip(n) | Skips the first n records |
take(n) | Returns up to n records |
count() | Number of matching records (calls take(99999) internally, capped at 99,999 rows; watch performance on very large tables) |
all() | Returns matching records (calls take(999999) internally, capped at 999,999 rows) |
Returns: query() returns ITableQuery; terminal take / all return IDynamicTableObject[]; count() returns number.
const rows = k.DB.indexedDb.orders
.query("status == 'paid'")
.orderByDescending("amount")
.skip(0)
.take(20)pagination(pageIndex, pageSize, where?)
Pagination helper returning a PaginationModel object (pageIndex starts at 1).
| Parameter | Type | Required | Description |
|---|---|---|---|
pageIndex | number | Yes | Page number, starting at 1. |
pageSize | number | Yes | Records per page. |
where | string | No | Condition string, e.g. status == 'paid'. |
Returns: PaginationModel containing totalCount (backed by count(), capped at 99,999), totalPage, pageSize, currentPage, and list (IDynamicTableObject[]).
const page = k.DB.indexedDb.orders.pagination(1, 20, "status == 'paid'")
k.response.json(page)createIndex(fieldName)
Creates an additional index on a column (aligns with "Index" in admin Column Settings).
| Parameter | Type | Required | Description |
|---|---|---|---|
fieldName | string | Yes | Column name to index. |
Returns: void.
k.DB.indexedDb.orders.createIndex("orderNo")Change History
getLogs(id) / getByLog(logId)
Reads editing history for a record or retrieves a historical record snapshot by logId.
| Method | Parameters | Returns | Description |
|---|---|---|---|
getLogs(id) | id: any | ChangeLog[] | null | Editing history for the specified record (up to 99 entries); returns null if no logs exist. |
getByLog(logId) | logId: number | IDynamicTableObject | null | Retrieves the record snapshot for the given logId; returns null if not found. |
Returns: See the Returns column for each method above.
const table = k.DB.indexedDb.orders
const id = table.add({ orderNo: "A1009", status: "draft" })
table.update(id, { orderNo: "A1009", status: "published" })
const logs = table.getLogs(id)
if (logs && logs.length > 0) {
const oldestSnapshot = table.getByLog(logs[logs.length - 1].logId)
k.response.json(oldestSnapshot)
}Notes
- Table name: Matches admin UI rules — alphanumeric characters only, starting with a letter or number.
- add vs append: Use
add()when scripts need to add columns dynamically; useappend()when the schema is already defined in the admin UI. - System fields: Records contain
_id; engine-managed system fields such as version should not be manually overwritten. - Server-side execution: Call in
env="server"CodeBlocks, APIs, or scheduled tasks. - Large tables: Avoid calling
all()on large tables; preferpagination()orquery().skip().take().
Association Tables (Table Relations)
After configuring relationships in IndexedDB Table Relations, reading a parent record lets you access related records using the relation name (returns an array for one-to-many / many-to-many). For example, const items = order.lineItems.
TypeScript Definitions
Show full TypeScript definitions
interface IDatabase {
[key: string]: KTable;
getTable(name: string): ITable;
getTables(): string[];
operators(): Operators;
}
interface ITable {
add(value: any): any;
append(value: any): any;
update(id: any, value: any): void;
update(value: any): void;
delete(id: any): void;
get(id: any): IDynamicTableObject;
find(query: string): IDynamicTableObject;
find(fieldName: string, matchValue: any): IDynamicTableObject;
find(filter: Record<string, any>): IDynamicTableObject;
findAll(query: string): IDynamicTableObject[];
findAll(field: string, value: any): IDynamicTableObject[];
findAll(filter: Record<string, any>): IDynamicTableObject[];
all(): IDynamicTableObject[];
query(): ITableQuery;
query(query: string): ITableQuery;
query(filter: Record<string, any>): ITableQuery;
count(query: string): number;
count(filter: Record<string, any>): number;
pagination(index: number, size: number): PaginationModel;
pagination(index: number, size: number, where: string): PaginationModel;
createIndex(fieldname: string): void;
getLogs(id: any): ChangeLog[];
getByLog(LogId: number): IDynamicTableObject;
}
interface ITableQuery {
count(): number;
orderBy(fieldname: string): ITableQuery;
orderByDescending(fieldname: string): ITableQuery;
skip(skip: number): ITableQuery;
take(count: number): IDynamicTableObject[];
take<T>(count: number): T;
where(searchCondition: string): ITableQuery;
where(filter: Record<string, any>): ITableQuery;
all(): IDynamicTableObject[];
all<T>(): T;
}
interface Operators {
AND: string;
OR: string;
EQ: string;
NE: string;
GT: string;
GTE: string;
LT: string;
LTE: string;
STARTS_WITH: string;
CONTAINS: string;
}
interface PaginationModel {
totalCount: number;
totalPage: number;
pageSize: number;
currentPage: number;
list: IDynamicTableObject[];
}