This reference covers the JavaScript API surface. For the query-string/object language used by jQl, see the dedicated jQL reference.

Getting started

jdb(name, version)

jdb(name, version)
ArgumentTypeRequired
namestringYes
versionnumberYes

Returns a builder with .open(config), plus .isClientMode() and .requiresLogin() for opting into those modes before opening.

.open(config) → jDB Promise
jdb('myapp', 1)
    .open({ storage: 'indexeddb' })
    .onCreate(function (e, next) {
        e.result.createTbl('users', [{ id: { type: 'NUMBER', AUTO_INCREMENT: 1 }, name: { type: 'VARCHAR' } }]);
        next();
    })
    .onUpgrade(function (e, next) {
        next();
    })
    .onSuccess(function (e) {
        var db = e.result; // DatabaseInstance
    })
    .onError(function (e) {
        console.error(e.message);
    });

onCreate fires the first time a database is opened; onUpgrade fires when an existing database is opened with a higher version. Both receive next() to call once setup is done. onSuccess/onError (or .then(success, error)) resolve with { result, message, type }, where result is the DatabaseInstance you'll use for everything else.

Config options

KeyTypeDefaultNotes
storagestringmemorymemory, localstorage, sessionStorage, indexeddb, sql or flatfile.
livebooleanfalseAuto-sync writes to serviceHost as they happen.
serviceHoststringnullBase URL for server sync/API calls. Also what enables db.clientService.
interceptorobjectnullHook called for every outgoing request (e.g. to attach auth headers).
$ajaxnullCustom transport, replacing the built-in XHR wrapper.
schemaPathstringnullLocal or remote path to load table schemas from.
useFrontendOnlySchemafalsetrue, or { loadData, maximumRetries, ttl }.
alwaysCheckSchemabooleanfalseDevelopment-only: re-check schema on every open.
ignoreSyncbooleanfalseAlso accepts an array of table names to exclude from syncing.
enableSocketbooleanfalseUse WebSockets for realtime updates.
waitApiToLoadbooleantrueBlock opening until custom API mappings resolve.
keystringnullEncryption key.

isClientMode()

Marks the connection as client-facing (production) before .open(), disabling debugging affordances.

jdb('myapp', 1).isClientMode().open({ storage: 'indexeddb' });

requiresLogin()

Opens in a restricted login mode: the resolved instance only exposes api(), close() and jQl() until the app authenticates and re-opens normally.

jdb('myapp', 1).requiresLogin().open({ serviceHost: 'https://api.example.com' });

jDB promises

.open() returns a jDB Promise: .onSuccess(fn), .onError(fn), .then(success, error), .catch(fn) and .finally(fn), plus the .onCreate/.onUpgrade event hooks shown above. Most instance methods (transaction, jQl, batchTransaction, storeProc().execute) return standard native Promises instead — check the signature on each method below.

Database instance

db.createTbl(name, columns, additionalConfig, ignoreInstance)

→ { state, result, errorCode, message }
ArgumentTypeRequiredNotes
namestringYes
columnsarrayNoArray of column definition objects.
additionalConfigobjectNoMerged onto the table's internal definition (e.g. alias, policies).
ignoreInstancebooleanNoSkip building a TableInstance and just return the raw response.
db.createTbl('users', [{
    id: { type: 'NUMBER', AUTO_INCREMENT: 1 },
    email: { type: 'VARCHAR' }
}]);

db.table(name)

→ TableInstance

Looks up an existing table. See Table instance below.

db.transaction(table, mode)

→ TableTransaction
ArgumentTypeNotes
tablestring | arrayA table name, or ["a as x", "b as y"] for a multi-table (join) transaction.
modestringread (default), write/writeonly, or readwrite.

Read-mode transactions expose select/qsl; write-mode transactions expose insert/insertReplace/update/delete. See Transaction instance below.

db.transaction('users', 'writeonly')
    .insert({ name: 'Ada' })
    .execute()
    .then(res => console.log(res));

db.batchTransaction(transactions, rollBackOnError)

→ Promise
ArgumentTypeNotes
transactionsarrayArray of { type, data, query, table, hardInsert }, where type is insert, update or delete.
rollBackOnErrorbooleanDefault false.
db.batchTransaction([
    { type: 'insert', table: 'users', data: { name: 'Ada' } },
    { type: 'update', table: 'users', query: { id: 1 }, data: { role: 'admin' } }
], true);

db.export(table, type, title)

→ { initialize() }
ArgumentTypeDefaultNotes
tablestring—"all" for every table.
typestringcsvcsv, html, jql or json.
titlestring—
db.export('users', 'json').initialize();

db.import(table, isSchema, handler)

→ { selectFile(), fromFile(file), fromText(content, type) }
ArgumentTypeNotes
tablestringTarget table for a data-only (non-schema) import.
isSchemabooleanDefault true.
handlerobject{ logService, onselect }.
db.import('users', false).selectFile()
    .then(res => console.log(res.result.message));

db.sync(config)

→ Promise
KeyTypeNotes
tablestring
forceboolean
syncData

db.syncAll(stopOnFailedTransaction)

→ Promise

Pushes every table's pending (unsynced) changes to the configured serviceHost in one request. Resolves immediately with { message: 'Nothing to Sync' } if there's nothing pending.

db.schema

PublicSchema instance
MethodNotes
.export({ version, server })Generates and downloads a versioned JSON schema snapshot, from the server if server is truthy, otherwise from local storage.
.add({ schemaData })Applies a schema definition (create/alter/crud) to the database.
.getTableModel(tableName, replacerData)Returns a blank record shaped to the table's columns, with any matching keys from replacerData filled in.

db.env

ApplicationEnvInstance
MemberNotes
.logger()Returns the registered logger resolver.
.resource()Returns the database's resource manager snapshot (tables, sync state).
.usage()Returns approximate storage usage, formatted as a string (e.g. "12.40 KB").
.dataTypesGetter — the registered column data-type validators.
.requestMappingGetter — custom API route mappings for this database.

db.clientService

Only present when serviceHost is set in the config passed to .open().
MethodNotes
.getByRef(tbl, query)Fetch a single record by reference.
.getAll(tbl, query, byQueryId)Fetch every matching record.
.getOne(tbl, query)Fetch a single matching record.
.query(query, replacer, cacheOptions)Run a server-side query built with QueryBuilder syntax.
.fetch(query, replacer, cacheOptions)Like .query, against the fetch endpoint.
.getNumRows(param, tbl)Row count for a table.
.push(tbl, type, data)Push a local change to the server outside the normal sync cycle.

db.storeProc()

→ StoreProcedure
MethodNotes
.create(name, query)Registers a jQL query string under name.
.remove(name)
.execute(name, params) → PromiseRuns the registered query, substituting params into any %key% placeholders.
const proc = db.storeProc();
proc.create('activeAdmins', 'select -* -users -where(role~admin)');
proc.execute('activeAdmins').then(res => console.log(res.getResult()));

Other instance methods

MethodNotes
.info()Returns an array describing every table: records, columns, keys, policies, last modified.
.close(flag)Closes the database connection; truthy flag also drops it.
.rename(newName) → PromiseRenames the database, syncing the rename to the server first if it's ever been synced.
.truncate(syncToServer) → PromiseEmpties every table.
.drop(flag, db, localOnly)Drops a database; requires a truthy flag.
.onUpdate(realtimeConfig)Returns a realtime connector for subscribing to live change events.
.getConnector(name, config)Generic connector factory (used internally by sync/onUpdate).
.api(path, data) → PromiseCalls a registered REST endpoint. path is a route string or a full request descriptor object.

Table instance

db.table(name)

MemberNotes
.columnsGetter — a deep copy of the table's column definitions.
.getModel(data)Maps data onto the table's record shape.
.update(tableData)Merges tableData onto the table's internal definition.
.rename(newName)Renames the table.
.truncate(flag)Empties the table; requires a truthy flag.
.drop(flag)Drops the table; requires a truthy flag.

db.table(name).alter

MethodNotes
.add.column(name, config)Adds a column. name can also be an object of { columnName: config } pairs.
.add.primary(key)Marks a column as the primary key.
.add.foreign(key, tableName)Adds a foreign key relationship.
.add.index(name, setting)Adds/updates an index.
.add.mode(mode)Grants an additional allowed access mode.
.drop(columnName)Drops a column from the table and every existing row.
.rename(oldName, newName)Renames a column.
db.table('users').alter.add.column('fullName', { type: 'VARCHAR', defaultValue: 'Foo Bar' });
db.table('users').alter.drop('fullName');

Transaction instance

.insert(data, hardInsert, tableName)

Write-mode only. data is an object or array of objects. hardInsert bypasses soft-insert de-duplication.

.insertReplace(records, updateRef)

Upserts by updateRef (defaults to the table's primary key).

.update(updateRecords)

updateRecords is an array of [condition, data] pairs — one update per pair.

.delete(query, tableName)

query is a condition object; omit it to delete every row.

.select(fields, definition)

Read-mode only. definition is { where, join, limit, orderBy, groupBy, ... } — the same shape jQl's select command builds internally from its clause syntax.

.qsl()

Quick Search Language: returns dynamically generated findBy<Column>(value, fields) finders for every column on a single-table transaction, or findByColumn(columnName, value, fields) for a multi-table one.

db.transaction('users').qsl().findByEmail('ada@example.com');

.execute(disablePushToServer, fromBatch, rollbackOnError)

→ Promise

Runs every queued operation on the transaction (insert/update/delete/select calls can be chained before calling .execute() once). Also available: .dataProcessing(boolean) to toggle validation/default-value generation before inserting.