Skip to content

k.DB.indexedDb ​

Site IndexedDB dynamic tables — shares the same data store as IndexedDB Tables in the admin UI

Execution ContextPrerequisitesTypical 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 stringsAdmin-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:

js
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 / PropertyDescriptionReturns
[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 fieldsstring | 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._idvoid
table.delete(id)Deletes a record by _id or primary keyvoid
table.get(id)Reads a single record by _id or business primary keyIDynamicTableObject | null
table.find(...) / table.findAll(...)Queries first/all records by condition string, field+value, or filter objectIDynamicTableObject / IDynamicTableObject[]
table.all() / table.count(...)Reads all rows or counts matching rowsIDynamicTableObject[] / 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 columnvoid
table.getLogs(id) / table.getByLog(logId)Reads up to 99 edit logs or retrieves a historical record snapshotChangeLog[] | 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).

MethodParametersRequiredDescription
getTable(name)name: stringYesTarget 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[].

js
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.

ParameterTypeRequiredDescription
valueobjectYesRecord 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.

js
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.

ParameterTypeRequiredDescription
valueobjectYesRecord object to insert. Fields should already be declared in the table schema.

Returns: string | null. New record ID (Guid string), or null on failure.

js
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.

MethodParametersDescription
update(id, value)id: any, value: objectLocates the record by _id or primary key and updates it with value.
update(value)value: objectUpdates the record identified by _id in the object; without a matching _id, no record is matched or inserted.

Returns: void.

js
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.

ParameterTypeRequiredDescription
idanyYes_id or primary key value of the record to delete.

Returns: void.

js
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.

ParameterTypeRequiredDescription
idanyYes_id or primary key value of the record to read.

Returns: IDynamicTableObject | null. Matching record object, or null when not found.

js
const row = k.DB.indexedDb.orders.get(id)
const summary = row ? { id: row._id, orderNo: row.orderNo } : null

find / 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).

OverloadParametersDescription
find(query) / findAll(query)query: stringCondition string (e.g. "amount >= 100 && status == 'paid'").
find(field, value) / findAll(field, value)field: string, value: anyField 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[].

js
// 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.

js
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).

ParameterTypeRequiredDescription
querystringYes (string overload)Condition string, e.g. status == 'paid'; pass "" to count all rows.
filterRecord<string, any>Yes (object overload)Filter object, typically built with operators().

Returns: number. Number of matching records (up to 99999).

js
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.

MethodDescription
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.

js
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).

ParameterTypeRequiredDescription
pageIndexnumberYesPage number, starting at 1.
pageSizenumberYesRecords per page.
wherestringNoCondition string, e.g. status == 'paid'.

Returns: PaginationModel containing totalCount (backed by count(), capped at 99,999), totalPage, pageSize, currentPage, and list (IDynamicTableObject[]).

js
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).

ParameterTypeRequiredDescription
fieldNamestringYesColumn name to index.

Returns: void.

js
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.

MethodParametersReturnsDescription
getLogs(id)id: anyChangeLog[] | nullEditing history for the specified record (up to 99 entries); returns null if no logs exist.
getByLog(logId)logId: numberIDynamicTableObject | nullRetrieves the record snapshot for the given logId; returns null if not found.

Returns: See the Returns column for each method above.

js
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 ​

  1. Table name: Matches admin UI rules — alphanumeric characters only, starting with a letter or number.
  2. add vs append: Use add() when scripts need to add columns dynamically; use append() when the schema is already defined in the admin UI.
  3. System fields: Records contain _id; engine-managed system fields such as version should not be manually overwritten.
  4. Server-side execution: Call in env="server" CodeBlocks, APIs, or scheduled tasks.
  5. Large tables: Avoid calling all() on large tables; prefer pagination() or query().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
ts
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[];
}