Connection

class Connection()

Represents a signed, permission-checked connection to a Jnu-backed database. Instances are normally obtained via connect(), not constructed directly – connect() also downloads and attaches the database schema, which the constructor by itself doesn’t do.

Connection is an EventEmitter; see Events below for the events it emits.

Constructor

new Connection(serviceName, idKeystore);

Arguments:

  • serviceName (string) - The service whose database to connect to; must be a key in dcpConfig with a services.jnu entry. Throws if that service has no services.jnu.location.

  • idKeystore (Keystore|PrivateKey) - An already-resolved (not a Promise) Keystore or PrivateKey whose signature will authenticate every query made through this connection. Throws if its .address isn’t a valid wallet.Address.

Note

Unlike connect(), this constructor does not fetch a schema – connection.schema is undefined until something sets it. Prefer connect() unless you have a specific reason to manage the schema yourself.

Properties

config

Connection.config
Type:

object

The services.jnu fragment of dcpConfig[serviceName] this connection was constructed with.

identity

Connection.identity
Type:

Keystore|PrivateKey

The identity every query is signed with.

schema

Connection.schema
Type:

object

The database schema (tables, column types, serializers) for this connection’s service. Set by connect(); undefined on connections constructed directly.

Methods

endpointOf

endpointOf(method)

Computes the full endpoint URL for a given Jnu method name.

Arguments:
  • method (string) – The method name (e.g. ‘select’, ‘add’). Throws if empty or not a string.

Return type:

string

performQuery

performQuery(query)

Low-level method that signs query with this connection’s identity and submits it to the server, returning its result, or rejecting if the server responded with an error. The CRUD and query methods below all use this internally – most applications won’t need to call it directly.

Arguments:
  • query (object) – A prepared (not yet signed) query object, as returned by makeQuery().

Return type:

Promise<object>

Note

Signing happens here, immediately before submission (via the identity’s makeSignedMessageObject, under the hood of a shared submitSignedPost utility) – query itself, as prepared by :meth:makeQuery, is unsigned.

makeQuery

makeQuery(method, query, options, expiry)

Instance-method shorthand for the module-level jnu.makeQuery() function, using this connection. Prepares (but does not sign) a query object for performQuery().

Return type:

Promise<object>

Note

For any method other than 'schema', this throws if query is missing a table (or a tables array matched 1:1 with a prototypes array), or is missing a prototype (or prototypes).

serverRelativeTime

serverRelativeTime(interval, now)

Computes a point in time relative to the Jnu server’s clock rather than the local machine’s, for storing timestamps that need to be comparable across clients with clock skew.

Arguments:
  • interval (number) – Offset from “now”, in seconds.

  • now – Optional. The local Date/timestamp to use as “now”; defaults to the actual current time.

Return type:

number

Note

Its own source comment claims it “throws if used before schema is loaded”, but that doesn’t match the implementation: it never touches this.schema. What it actually throws on (via a lower-level dcp/utils helper) is having no cached client/server clock-offset measurement yet for this connection’s time service – which, in practice, means calling it before this connection has successfully submitted at least one query.

getPrimaryKeyColumnName

getPrimaryKeyColumnName(tableName)

Looks up the name of tableName’s primary-key column in this.schema.

Arguments:
  • tableName (string)

Return type:

string

add

add(query, options)

Inserts a row. This is an async method that returns a Promise.

Arguments:
  • query (object) – An ormdb-style query object describing what to insert (see Query Objects, below).

  • options (object) – Optional. Defaults to { variant: ‘add’ }.

Return type:

Promise<object>

change

change(query, options)

Updates row(s) matching query. This is an async method that returns a Promise.

Arguments:
  • query (object) – An ormdb-style query object.

  • options (object) – Optional. Defaults to { variant: ‘change’ }.

Return type:

Promise<object>

changeOrAdd

changeOrAdd(query)

Equivalent to change() with { variant: ‘changeOrAdd’ } (upsert).

changeMany

changeMany(query)

Equivalent to change() with { variant: ‘changeMany’ }.

delete

delete(query, options)

Deletes row(s) matching query. This is an async method that returns a Promise.

Arguments:
  • query (object) – An ormdb-style query object.

  • options (object) – Optional. Defaults to { variant: ‘delete’ }.

Return type:

Promise<object>

deleteMany

deleteMany(query)

Equivalent to delete() with { variant: ‘deleteMany’ }.

select

select(query, options)

Retrieves rows matching query. This is an async method that returns a Promise.

Arguments:
  • query (object) – An ormdb-style query object (see Query Objects, below).

  • options (object) – Optional query variant/shaping options; see search(), isearch(), count(), groupCount(), and the select* aggregate methods below for the common ones.

Return type:

Promise<ResultSet|object|number>

Note

The resolved type depends on the response shape: ordinary row-returning queries resolve with a ResultSet(). Aggregate variants (selectSum(), selectMax(), selectMin(), selectAvg()) resolve with the raw scalar value instead, since their response has no rowCount to wrap.

search / isearch

Equivalent to select() with { variant: ‘search’ }.

isearch(query)

Equivalent to select() with { variant: ‘isearch’ } (case-insensitive search).

count

count(query)
Arguments:
  • query (object)

Return type:

Promise<ResultSet|object>

Equivalent to select() with { variant: ‘count’ }.

Note

count() does not special-case its return value – it delegates straight to select(), same as search/isearch/groupCount/the select* aggregates, and resolves with whatever select() resolves with for a count-variant query.

groupCount

groupCount(query, groups)

Equivalent to select() with { variant: ‘groupCount’, groups }.

Arguments:
  • query (object)

  • groups (string[]) – Column names to group by.

selectSum / selectMax / selectMin / selectAvg

selectSum(columnName, query)

Equivalent to select() with { variant: ‘sum’, columnName }. Resolves with the raw scalar sum, not a ResultSet().

selectMax(columnName, query)

As selectSum(), with variant: ‘max’.

selectMin(columnName, query)

As selectSum(), with variant: ‘min’.

selectAvg(columnName, query)

As selectSum(), with variant: ‘avg’.

selectDistinct

selectDistinct(columnName, query)

Equivalent to select() with { variant: ‘distinct’, columnName }.

Query Objects

query arguments above follow the ormdb query model. The exact grammar is beyond the scope of this reference, but commonly used properties include:

  • table (string) - The table to operate on.

  • prototype (object) - A partial row used as a match filter (for select/change/delete) or as the row to insert (for add).

  • limit / skip (number) - Pagination.

  • order (string) - Column to sort by.

  • desc (boolean) - Sort descending instead of ascending.

Events

Connection is an EventEmitter. Handlers are attached the usual way, for example, connection.on('busy', () => { ... }).

  • busy - emitted immediately before a query is sent to the server (from performQuery()).

  • unbusy - emitted once that query’s response (success or failure) has been processed.

Note

There is currently no usable error event: the error path in performQuery() calls this.emit(error) – passing the Error instance itself as the event name, rather than this.emit('error', error) – so an ordinary connection.on('error', ...) listener will never see it. Query failures still surface correctly as rejected Promises; only the EventEmitter side-channel is affected.

Example

const jnu = require('dcp/jnu');

const db = await jnu.connect('scheduler');

const jobs = await db.select({
  table: 'jobs',
  prototype: { owner: myAddress.toString() },
  limit: 20,
  order: 'startTime',
  desc: true,
});
console.log('Found', jobs.rowCount, 'jobs');
await jobs.rows.forEach((job) => console.log(job));

const totalPaid = await db.selectSum('paidOut', {
  table: 'jobs',
  prototype: { owner: myAddress.toString() },
});
console.log('Total paid out:', totalPaid);