k.DB.sequenceDb
Site-local sequential key-value store — high-performance numeric-key sequence and log database
| Execution Context | Prerequisites | Typical 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 tables | Append-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:
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 / Property | Description | Returns |
|---|---|---|
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 file | void |
validPath(part) | Checks whether a relative path segment or database name is allowed | boolean |
db.firstKey / db.lastKey | Read-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 key | number |
db.get(id) | Reads a record by numeric key (null if missing) | any |
db.range(lowBound, highBound, ascending) | Returns records within the inclusive key range | any[] |
db.count(lowBound, highBound) | Counts records within the inclusive key range | number |
db.update(key, obj) / db.delete(key) | Replaces or deletes a record by numeric key | void |
db.find(js, ...) / db.findAll(js, ...) | Scans all records or a key range using a predicate callback | any / 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.
| Overload | Parameters | Description |
|---|---|---|
openDb(name) | name: string | Opens or creates a database in the site sequence-DB root folder |
openDb(path, name) | path: string, name: string | Opens or creates a database under the relative path subfolder |
openDb(path, name, keyFieldName) | path: string, name: string, keyFieldName: string | Opens 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.
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.
| Overload | Parameters | Description |
|---|---|---|
deleteDb(name) | name: string | Deletes the specified database in the root folder |
deleteDb(path, name) | path: string, name: string | Deletes the specified database under relative path |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
part | string | Yes | Path segment or name to validate |
Returns: boolean. true if valid; otherwise false.
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.
const db = k.DB.sequenceDb.openDb("app_logs")
const first = db.firstKey
const last = db.lastKeyadd(obj) / add(key, obj)
Appends a record and returns its numeric key (auto-generated keys are 1-based).
| Overload | Parameters | Description |
|---|---|---|
add(obj) | obj: any | Assigns an auto-incrementing 1-based integer key and inserts the record |
add(key, obj) | key: number, obj: any | Inserts 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.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | number | Yes | Numeric record key |
Returns: any — Record object, or null when missing or deleted.
const item = db.get(2)range(lowBound, highBound, ascending)
Returns records within the inclusive numeric key range [lowBound, highBound].
| Parameter | Type | Required | Description |
|---|---|---|---|
lowBound | number | Yes | Lower key bound |
highBound | number | Yes | Upper key bound |
ascending | boolean | Yes | true for ascending order, false for descending order |
Returns: any[] — Array of matching records.
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].
| Parameter | Type | Required | Description |
|---|---|---|---|
lowBound | number | Yes | Lower key bound |
highBound | number | Yes | Upper key bound |
Returns: number — Number of records in the range.
const total = db.count(1, 100)update(key, obj)
Replaces the record stored at the specified numeric key.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | number | Yes | Record key to update |
obj | any | Yes | Updated record object |
Returns: void.
db.update(2, { level: "warn", msg: "slow-updated" })delete(key)
Deletes the record at the specified numeric key.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | number | Yes | Record key to delete |
Returns: void.
db.delete(2)find(js) / find(js, lowKey, highKey, ascending?)
Finds the first record matching a predicate callback.
| Overload | Parameters | Description |
|---|---|---|
find(js) | js: Function | Scans all records and returns the first where js(item) returns true |
find(js, lowKey, highKey, ascending?) | js: Function, lowKey: number, highKey: number, ascending?: boolean | Scans [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.
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.
| Overload | Parameters | Description |
|---|---|---|
findAll(js) | js: Function | Scans 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?: boolean | Scans [lowKey, highKey] in the given direction (default false, descending) and returns all matches |
Returns: any[] — Array of matching records.
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.
const tempDb = k.DB.sequenceDb.openDb("temp_logs")
tempDb.close()
k.DB.sequenceDb.deleteDb("temp_logs")Notes
- Naming rules: Relative
pathandnamemust satisfyvalidPathrules or an argument validation error is thrown. - Key rules: Auto-generated keys start at
1; when usingadd(key, obj), suppliedkeyvalues must be incremental integers. - Server-side execution: Use inside
env="server"contexts (APIs, CodeBlocks, or scheduled tasks).
TypeScript Definitions
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;
}Related Docs
- k.DB Overview
- k.DB.indexedDb — Structured dynamic tables
- k.DB.keyValue — String key-value store
- k.DB.sqlite — SQLite relational database