Skip to content

k.DB.sequenceDb ​

Site-local sequential key-value store — high-performance numeric-key sequence and log database

Execution ContextPrerequisitesTypical Use
Server-side KScript (k.api, <script env="server">, scheduled jobs)Works out of the box with no schemas or connection strings; paths must satisfy validPath; use sqlite for SQL or indexedDb for admin tablesAppend-heavy logs, event streams, and time-series records queried by 1-based numeric keys or ranges

Quick Start ​

Open a sequential database, append records with 1-based keys, scan by predicate and key count, then clean up:

js
k.api.post(() => {
    const db = k.DB.sequenceDb.openDb("demo_logs")
    const id1 = db.add({ level: "info", msg: "started" })
    const id2 = db.add({ level: "error", msg: "timeout" })
    const item = db.get(id2)
    const matches = db.findAll((row) => row.level === "error")
    const total = db.count(id1, id2)
    k.DB.sequenceDb.deleteDb("demo_logs")
    return { firstKey: id1, lastKey: id2, item, matchesCount: matches.length, total }
})

Quick Reference ​

Method / PropertyDescriptionReturns
openDb(name) / openDb(path, name, keyFieldName?)Opens or creates a local .data sequence database (cached per path)SequenceDb
deleteDb(name) / deleteDb(path, name)Closes handle, clears cache, and deletes the .data filevoid
validPath(part)Checks whether a relative path segment or database name is allowedboolean
db.firstKey / db.lastKeyRead-only smallest/largest numeric key (0 when empty)number
db.add(obj) / db.add(key, obj)Appends a record with auto 1-based key or incremental custom keynumber
db.get(id)Reads a record by numeric key (null if missing)any
db.range(lowBound, highBound, ascending)Returns records within the inclusive key rangeany[]
db.count(lowBound, highBound)Counts records within the inclusive key rangenumber
db.update(key, obj) / db.delete(key)Replaces or deletes a record by numeric keyvoid
db.find(js, ...) / db.findAll(js, ...)Scans all records or a key range using a predicate callbackany / any[]
db.close()Releases the file handle (use deleteDb() directly to remove a DB)void

Opening & Managing Databases (KWormDb) ​

openDb(name) / openDb(path, name) / openDb(path, name, keyFieldName) ​

Opens or creates a sequential database file (automatically appends .data if omitted). Open instances are reused per file path within the server process; relative path segments and name must satisfy validPath rules.

OverloadParametersDescription
openDb(name)name: stringOpens or creates a database in the site sequence-DB root folder
openDb(path, name)path: string, name: stringOpens or creates a database under the relative path subfolder
openDb(path, name, keyFieldName)path: string, name: string, keyFieldName: stringOpens or creates a database and binds keyFieldName; when calling add(key, obj) with key > 0, key is automatically written into keyFieldName on the stored object

Returns: SequenceDb — Database instance.

js
const db = k.DB.sequenceDb.openDb("app_logs")
const eventsDb = k.DB.sequenceDb.openDb("analytics", "events", "eventId")

deleteDb(name) / deleteDb(path, name) ​

Closes the database handle, removes it from the open-DB cache, and deletes the .data file from disk.

OverloadParametersDescription
deleteDb(name)name: stringDeletes the specified database in the root folder
deleteDb(path, name)path: string, name: stringDeletes the specified database under relative path

Returns: void.

js
k.DB.sequenceDb.deleteDb("app_logs")
k.DB.sequenceDb.deleteDb("analytics", "events")

validPath(part) ​

Validates whether a relative path segment or database name is allowed. Only letters, digits, -, _, ., \, /, and : are permitted, and the value must contain at least one letter or digit.

ParameterTypeRequiredDescription
partstringYesPath segment or name to validate

Returns: boolean. true if valid; otherwise false.

js
const ok = k.DB.sequenceDb.validPath("audit-events_2026")
const bad = k.DB.sequenceDb.validPath("...")

SequenceDb Properties & Methods ​

firstKey / lastKey ​

Read-only properties returning the smallest and largest numeric keys in the database, or 0 when the database is empty.

Parameters: None.

Returns: number. Smallest or largest numeric key, or 0 when empty.

js
const db = k.DB.sequenceDb.openDb("app_logs")
const first = db.firstKey
const last = db.lastKey

add(obj) / add(key, obj) ​

Appends a record and returns its numeric key (auto-generated keys are 1-based).

OverloadParametersDescription
add(obj)obj: anyAssigns an auto-incrementing 1-based integer key and inserts the record
add(key, obj)key: number, obj: anyInserts the record with a predefined incremental integer key; if keyFieldName was set on openDb and key > 0, populates that property on the stored object

Returns: number — Key of the inserted record.

js
const db = k.DB.sequenceDb.openDb("app_logs")
const k1 = db.add({ level: "info", msg: "boot" })
const k2 = db.add({ level: "warn", msg: "slow" })

const keyedDb = k.DB.sequenceDb.openDb("analytics", "events", "eventId")
keyedDb.add(501, { title: "order-created" })

get(id) ​

Reads a single record by numeric key.

ParameterTypeRequiredDescription
idnumberYesNumeric record key

Returns: any — Record object, or null when missing or deleted.

js
const item = db.get(2)

range(lowBound, highBound, ascending) ​

Returns records within the inclusive numeric key range [lowBound, highBound].

ParameterTypeRequiredDescription
lowBoundnumberYesLower key bound
highBoundnumberYesUpper key bound
ascendingbooleanYestrue for ascending order, false for descending order

Returns: any[] — Array of matching records.

js
const ascItems = db.range(1, 100, true)
const descItems = db.range(1, 100, false)

count(lowBound, highBound) ​

Counts records within the numeric key range [lowBound, highBound].

ParameterTypeRequiredDescription
lowBoundnumberYesLower key bound
highBoundnumberYesUpper key bound

Returns: number — Number of records in the range.

js
const total = db.count(1, 100)

update(key, obj) ​

Replaces the record stored at the specified numeric key.

ParameterTypeRequiredDescription
keynumberYesRecord key to update
objanyYesUpdated record object

Returns: void.

js
db.update(2, { level: "warn", msg: "slow-updated" })

delete(key) ​

Deletes the record at the specified numeric key.

ParameterTypeRequiredDescription
keynumberYesRecord key to delete

Returns: void.

js
db.delete(2)

find(js) / find(js, lowKey, highKey, ascending?) ​

Finds the first record matching a predicate callback.

OverloadParametersDescription
find(js)js: FunctionScans all records and returns the first where js(item) returns true
find(js, lowKey, highKey, ascending?)js: Function, lowKey: number, highKey: number, ascending?: booleanScans [lowKey, highKey] in the given direction (default false, descending) and returns the first match

Callback must return a boolean

The predicate callback js(item) must return a boolean (true or false; null and undefined are treated as non-matching). Because the runtime evaluates non-null return values with C# Convert.ToBoolean(), do not return arbitrary JS truthy values such as non-empty strings or objects, which throw a conversion exception (FormatException / InvalidCastException).

Returns: any — First matching record object, or null if none matched.

js
const errItem = db.find((item) => item.level === "error")
const rangeItem = db.find((item) => item.level === "warn", 1, 10, true)

findAll(js) / findAll(js, lowKey, highKey, ascending?) ​

Finds all records matching a predicate callback. As with find(), the callback must return a boolean (true/false, or null/undefined), rather than arbitrary JS truthy values such as non-empty strings or objects.

OverloadParametersDescription
findAll(js)js: FunctionScans all records (descending by default) and returns all items where js(item) returns true
findAll(js, lowKey, highKey, ascending?)js: Function, lowKey: number, highKey: number, ascending?: booleanScans [lowKey, highKey] in the given direction (default false, descending) and returns all matches

Returns: any[] — Array of matching records.

js
const warnings = db.findAll((item) => item.level !== "info")
const ranged = db.findAll((item) => item.level !== "info", 1, 10, false)

close() ​

Disposes the underlying database file handle.

close() vs deleteDb() lifecycle

The server caches open SequenceDb instances by file path. To permanently remove a database, call deleteDb(...) directly (it closes the handle, clears the cache entry, and deletes the file). Avoid calling close() directly on a database that subsequent requests will continue accessing via openDb() without calling deleteDb() first.

Parameters: None.

Returns: void.

js
const tempDb = k.DB.sequenceDb.openDb("temp_logs")
tempDb.close()
k.DB.sequenceDb.deleteDb("temp_logs")

Notes ​

  1. Naming rules: Relative path and name must satisfy validPath rules or an argument validation error is thrown.
  2. Key rules: Auto-generated keys start at 1; when using add(key, obj), supplied key values must be incremental integers.
  3. Server-side execution: Use inside env="server" contexts (APIs, CodeBlocks, or scheduled tasks).

TypeScript Definitions ​

ts
interface KWormDb {
  openDb(name: string): SequenceDb;
  openDb(path: string, name: string): SequenceDb;
  openDb(path: string, name: string, keyFieldName: string): SequenceDb;
  deleteDb(name: string): void;
  deleteDb(path: string, name: string): void;
  validPath(part: string): boolean;
}

interface SequenceDb {
  firstKey: number;
  lastKey: number;
  add(obj: any): number;
  add(key: number, obj: any): number;
  get(id: number): any;
  range(lowBound: number, highBound: number, ascending: boolean): any[];
  update(key: number, obj: any): void;
  delete(key: number): void;
  count(lowBound: number, highBound: number): number;
  find(js: Function): any;
  find(js: Function, lowKey: number, highKey: number, ascending?: boolean): any;
  findAll(js: Function): any[];
  findAll(js: Function, lowKey: number, highKey: number, ascending?: boolean): any[];
  close(): void;
}