Skip to main content

Class: DatabaseURI

@divine/uri.DatabaseURI

The database URI base class defines the API for all database-specific protocols. It provides CRUD access to database rows via load, save, append, modify and remove, query for executing custom queries in a databases-specific query language (read "SQL") and watch for change data capture, provided the database and driver supports it.

Below is a list of all known supported databases:

DatabaseDatabase driver class
CockroachDBPostgresURI
H2JDBCURI†
MariaDBMySQLURI
MySQLMySQLURI
PostgreSQLPostgresURI
SQL ServerTDSURI
SQLiteSQLiteURI

† In theory, any JDBC-enabled database should have at least basic support, but our unit tests are only run against H2.

CRUD row operations with DB references​

In order to provide CRUD (create, read, update and delete) operations for database rows, DatabaseURI uses a small expression language called DB reference in the URI fragment to specify what table, rows and columns to access. A DB reference looks like this:

# table { [ keys ] } { ( columns ) } { ; scope } { ? filter } { & name = value ... }

It always starts with a hash sign, which signals the start of the URI fragment part, followed by a reference to what table to access. The table value may actually be a forward slash-separated table path, so it's possible to specify catalog and schema as well (similar to how the dot is used in SQL).

The remaining parts of the expression is optional (well, depeneding on what operation you're trying to perform).

The save operation may, depending on the actual database, require the primary key in order to work. The name of the primary key optionally follows the table name, enclosed by square brackets. keys may be a comma-separated list of columns, if the primary key spans multiple columns.

In order to limit what colomns to operate on, a list of columns, enclosed by parentheses, may then follow. The default is all columns when reading and all the columns present in the data when writing.

Next up: scope. The scope can be one of scalar (a single cell), one (a single row), unique (distinct rows) or all (multiple rows). It's specifies how data should be interpreted when reading or writing.

When reading, a filter specifies what rows to return. The filter part begins with a question mark followed by a (possible nested) expression enclosed by parentheses. Please see Filters below for the filter syntax.

Finally, one or more parameters may be specified. Currently, parameters are only defined for read operations. A parameter begins with an ampersand followed by the name of the parameter, and equals sign (=) and the value. The available parameters are offset (skip rows in the result set), count (limit the result set), sort (to specify a sort column; precede with a dash to reverse the sort order) and lock (either read or write) to lock the rows returned.

Filters​

Relational filters are written as ( relation , column , value ), where relation is one of lt (less than), le (less than or equal), eq (equal), ge (greater than or equal) and gt (greater than). These kinds of filter expressions test a column against a fixed value.

There are also boolean filters. To require two or more filters to all be true, write ( and filter1 ... filterN ). To require only one of several filters to be true, write ( or filter1 ... filterN ). It's also possible to invert a filter by writing ( not filter ).

Filters may be nested, so the following filter part of a DB reference would return all products that cost between 10 and 20 USD as well as those being completely free:

#products?(or(and(ge,amount,10)(le,amount,20))(eq,amount,0))

This syntax, while perhaps a bit exotic for both JavaScript and SQL developers, was chosen so that filters do not have to be URI-encoded when beeing included in the URI fragment.

As a general rule, filters should be kept simple with just one or two relations. Otherwise, it's probably better to simply write an SQL query instead.

Examples​

So why use DB references? Well, they can save you a lot of work! Assuming db is your DatabaseURI, here are a few examples.

Insert a row:

const user = await db.$`#users`.append<User>({ name: 'Martin', language: 'sv', country: 'se' });

Insert multiple rows:

const user = await db.$`#users`.append<User[]>([
{ name: 'Martin', language: 'sv', country: 'se' },
{ name: 'Vilgot', language: 'es', country: 'mx' }
]);

Retrieve a row:

const user = await db.$`#users;one?(eq,id,${userID})`.load<User>();

Retrieve multiple rows:

const users = await db.$`#users?(eq,country,mx)`.load<User[]>();

Update one or more rows

await db.$`#users?(eq,id,${userID})`.modify({ country: 'fi' });

Remove one or more rows:

await db.$`#users?(eq,id,${userID})`.remove();

Some databases also supports upsert semantics, which means the row will be created if it doesn't exist, or updated if it does.

const user = await db.$`#users`.save<User>({ id: 1337, name: 'Martin', language: 'sv', country: 'se' });

Depending on the database, you may have to provide the name of the primary key for this call to succeed. If the database supports upsert both with and without a primary key, it's better to omit it.

const user = await db.$`#users[id]`.save<User>({ id: 1337, name: 'Martin', language: 'sv', country: 'se' });

save, like append, also accepts an array for upserting multiple rows at once.

tip

When writing data, undefined values will map to the SQL DEFAULT keyword.

Custom SQL queries​

CRUD operations beside, the main interface to databases is the SQL query, and that's what the query method is all about. It has a few different signatures, but most common is to use it as a tagged template literal:

const [ user ] = await db.query<User[]>`select * from users where id = ${userID}`;

The query function always returns an array. The raw result set is available via the FIELDS symbol. Sessions are handled automatically and is usually not something you will have to worry about. However, since the database connections are pooled, two consecutive queries might execute on different connections. To execute multiple queries in the same session, construct DBQuery objects explicitly and pass them all to query (or use a transaction; see below):

const id = await db.query(q`insert into users (name) values ('Martin')`, q`select last_insert_id()`);

Note that the generated primary key is always available as rowKey, so this particular example is a bit silly.

Transactions​

To execute a code block inside a transaction, pass a callback to query, like this:

const orderID = await db.query(async () => {
const order = await db.$`orders`.append<Order>({ user_id: userID, date: new Date() });
const orderID = order.order_id ?? order[FIELDS][0].rowKey; // Not all drivers support `RETURNING *`
await db.$`order_lines`.append(lines.map((line) => ({ ...line, order_id: orderID }));

return orderID;
});

If the transaction fails (i.e., the callback throws an exception), the transaction will be automatically rolled back. If it returns normally, it will be committed. Transactions may be nested, in which case savepoints will be used instead. Like actual transactions, savepoints will also be rolled back if the nested callback throws.

Deadlock handling​

Sometimes, conflicting transactions will deadlock. The database drivers will automatically handle this situation for you (assuming the deadlock exception propagates back to query, of course) by restarting the transaction and invoking the callback again. The callback actually receives a retry counter as its first argument, in case you need to detect this. The first time you callback is called, this counter will be 0. Nested callbacks will receive null instead of a number.

This behaviour, as well as other transaction parameters like isolation level, may be customized by passing a DBTransactionParams object as the first argument to query, before the callback.

Deadlock handling is supported by all database drivers, and there is even custom handling for CockroachDB, which automatically increases the transaction priority on retries.

Change Data Capture​

Some drivers, like PostgresURI, also implement the watch method. Use this to listen for events from the database and stream the results in realtime to your application. The PostgresURI class supports LISTEN/NOTIFY events when using PostgreSQL and core changefeeds when using CockroachDB.

Shutting down​

Call close to terminate the connection pool. Otherwise, it may take a minute or so before all idle connections time out and Node.js exits.

Hierarchy​

  • URI

    ↳ DatabaseURI

Constructors​

constructor​

• new DatabaseURI(url?, params?)

Constructs a new URI subclass. The URI constructor is a bit unusual, as it will always return an URI subclass and never a plain URI object.

If the URI contains user information (credentials), it will be added as an AuthSelector and removed from the URI.

Parameters​

NameTypeDescription
url?string | URL | UrlThe URL to construct. If relative, it will be resolved as a file: URL relative to the current working directory. If url is a string and params is provided, the string may contain {prop} placeholders, which will then be resolved and percent-encoded against properties in params.
params?ParamsAn optional record with parameters, used in case url is a string.

Inherited from​

URI.constructor

Defined in​

uri/src/uri.ts:232

• new DatabaseURI(url?, base?, params?)

Constructs a new URI subclass. The URI constructor is a bit unusual, as it will always return an URI subclass and never a plain URI object.

If the URI contains user information (credentials), it will be added as an AuthSelector and removed from the URI.

NOTE: If base is an URI, all its selectors will be inherited by the newly constructed URI.

Parameters​

NameTypeDescription
url?string | URL | UrlThe URL to construct. If relative, it will be resolved against base. If url is a string and params are provided, the string may contain {prop} placeholders, which will then be resolved and percent-encoded against properties in params.
base?string | URL | UrlA base URL that url will be resolved relative to, in case url is relative. If base itself is relative, base will first be resolved as a file: URL relative to the current working directory. Just like url, if base is a string and params is provided, {prop} placeholders may be present in the string.
params?ParamsAn optional record with parameters, used in case url and/or base is a string.

Inherited from​

URI.constructor

Defined in​

uri/src/uri.ts:251

Properties​

href​

• Readonly href: string

This URI's string representation. Unlike in URL, this property may not be changed/updated.

Inherited from​

URI.href

Defined in​

uri/src/uri.ts:211


origin​

• Readonly origin: string

This URI's origin. Unlike in URL, this property may not be changed/updated.

Inherited from​

URI.origin

Defined in​

uri/src/uri.ts:214


protocol​

• Readonly protocol: string

This URI's protocol. Unlike in URL, this property may not be changed/updated.

Inherited from​

URI.protocol

Defined in​

uri/src/uri.ts:217


selectors​

• selectors: Object

All selectors that may apply to this URI. Use addSelector to modify this property.

Type declaration​

NameTypeDescription
auth?AuthSelector[]Authentication/Credentials selectors. See AuthSelector.
headers?HeadersSelector[]Headers selectors. See HeadersSelector.
params?ParamsSelector[]Parameter selectos. See ParamsSelector.
session?SessionSelector[]Session selectors. Only used internally.

Inherited from​

URI.selectors

Defined in​

uri/src/uri.ts:196


FIELDS​

▪ Static Readonly FIELDS: symbol = FIELDS

An alias for FIELDS.

Inherited from​

URI.FIELDS

Defined in​

uri/src/uri.ts:148


FINALIZE​

▪ Static Readonly FINALIZE: symbol = FINALIZE

An alias for FIELDS.

Inherited from​

URI.FINALIZE

Defined in​

uri/src/uri.ts:151


HEADERS​

▪ Static Readonly HEADERS: symbol = HEADERS

An alias for HEADERS.

Inherited from​

URI.HEADERS

Defined in​

uri/src/uri.ts:154


NULL​

▪ Static Readonly NULL: symbol = NULL

An alias for NULL.

Inherited from​

URI.NULL

Defined in​

uri/src/uri.ts:145


STATUS​

▪ Static Readonly STATUS: symbol = STATUS

An alias for STATUS.

Inherited from​

URI.STATUS

Defined in​

uri/src/uri.ts:157


STATUS_TEXT​

▪ Static Readonly STATUS_TEXT: symbol = STATUS_TEXT

An alias for STATUS_TEXT.

Inherited from​

URI.STATUS_TEXT

Defined in​

uri/src/uri.ts:160


VOID​

▪ Static Readonly VOID: symbol = VOID

An alias for VOID.

Inherited from​

URI.VOID

Defined in​

uri/src/uri.ts:142

Methods​

$

▸ $(strings, ...values): DatabaseURI

Constructs a new DatabaseURI, relative to this URI, from a template string, percent-encoding all arguments.

Example:

const base = new URI('sqlite:/tmp/demo.db');
const info = await base.$`#item_info?(eq,id,${item})`.load();

Throws

TypeError If the resulting URI is not actually a DatabaseURI.

Parameters​

NameTypeDescription
stringsTemplateStringsArrayThe template string array.
...valuesunknown[]The values to be encoded.

Returns​

DatabaseURI

A new DatabaseURI subclass instance.

Overrides​

URI.$

Defined in​

uri/src/protocols/database.ts:958


[asyncIterator]​

▸ [asyncIterator](): AsyncIterator<Buffer, any, undefined> & Metadata

All URIs are AsyncIterable<Buffer>. This method implements that interface by calling load(stream).

Returns​

AsyncIterator<Buffer, any, undefined> & Metadata

An AsyncIterator<Buffer> stream.

Inherited from​

URI.[asyncIterator]

Defined in​

uri/src/uri.ts:535


_createDBConnectionPool​

▸ Protected Abstract _createDBConnectionPool(params): DBConnectionPool | Promise<DBConnectionPool>

Parameters​

NameType
paramsDBParamsSelector

Returns​

DBConnectionPool | Promise<DBConnectionPool>

Defined in​

uri/src/protocols/database.ts:941


_getAuthorization​

▸ Protected _getAuthorization(req, payload?, challenges?): Promise<undefined | Authorization>

Parameters​

NameType
reqAuthSchemeRequest
payload?Buffer | AsyncIterable<Buffer>
challenges?WWWAuthenticate[]

Returns​

Promise<undefined | Authorization>

Inherited from​

URI._getAuthorization

Defined in​

uri/src/uri.ts:539


_getBestSelector​

▸ Protected _getBestSelector<T>(sels, challenge?): null | T

Type parameters​

NameType
Textends SelectorBase

Parameters​

NameType
selsundefined | T[]
challenge?WWWAuthenticate

Returns​

null | T

Inherited from​

URI._getBestSelector

Defined in​

uri/src/uri.ts:581


_guessContentType​

▸ Protected _guessContentType(knownContentType?): undefined | ContentType

Parameters​

NameType
knownContentType?string | ContentType

Returns​

undefined | ContentType

Inherited from​

URI._guessContentType

Defined in​

uri/src/uri.ts:573


_makeIOError​

▸ Protected _makeIOError(err): IOError

Parameters​

NameType
errunknown

Returns​

IOError

Inherited from​

URI._makeIOError

Defined in​

uri/src/uri.ts:577


addSelector​

▸ addSelector<T>(selector): DatabaseURI

Adds a new selector to this URI.

Selectors is a way to specify in what situations some kind of parameters or configuration is valid. When some kind of configuration is required (such as authentication of connection parameters), all registered selectors are evaluated and based on the matching score, the best selector is chosen. The more specific a selector is, the higher the score it will receive if it matches.

Based on this, it's possible to limit the scope of credentials or to configure certain HTTP headers to be sent to a specific set of servers.

It's also perfectly valid not to specify a selector for some kind of parameters. As long as there is only one kind of this configuration, it will apply unconditionally.

Throws

TypeError If the selector to add is invalid.

Type parameters​

NameType
Textends AuthSelector | HeadersSelector | ParamsSelector | SessionSelector

Parameters​

NameTypeDescription
selectorTThe selector to add.

Returns​

DatabaseURI

This URI.

Inherited from​

URI.addSelector

Defined in​

uri/src/uri.ts:311


append​

▸ append<T, D>(data, _sendCT?, _recvCT?): Promise<T & DBMetadata>

Uses the DB reference in this URI's fragment to add one or multiple rows in a table using INSERT.

Throws

IOError On I/O errors or if this URI does not have a valid DB reference fragment.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe actual type returned.
DunknownThe type of data to store.

Parameters​

NameTypeDescription
dataDThe data to add to the table.
_sendCT?string | ContentTypeMust not be used.
_recvCT?string | ContentTypeMust not be used.

Returns​

Promise<T & DBMetadata>

A row or array of rows (if the database supports it), with DBMetadata.

Overrides​

URI.append

Defined in​

uri/src/protocols/database.ts:1034


close​

▸ close(): Promise<void>

Shuts down the database connection pool.

Throws

IOError On I/O errors.

Returns​

Promise<void>

Overrides​

URI.close

Defined in​

uri/src/protocols/database.ts:1294


info​

▸ info<T>(): Promise<T & Metadata>

This method will return information about the resource this URI references, if the subclass supports it.

The actual operation depends on what kind of URI this is. See info or info for two common examples.

Throws

IOError On I/O errors or if the subclass does not support this method.

Type parameters​

NameTypeDescription
Textends DirectoryEntryThe actual type of information record returned. Must extend DirectoryEntry.

Returns​

Promise<T & Metadata>

An information record describing the resources.

Inherited from​

URI.info

Defined in​

uri/src/uri.ts:351


list​

▸ list<T>(): Promise<T[] & Metadata>

This method will return information about this URI's children/subresources, if the subclass supports it.

The actual operation depends on what kind of URI this is. See info for a common example.

Throws

IOError On I/O errors or if the subclass does not support this method.

Type parameters​

NameTypeDescription
Textends DirectoryEntryThe actual type of information record returned. Must extend DirectoryEntry.

Returns​

Promise<T[] & Metadata>

An array of information record describing the subresources.

Inherited from​

URI.list

Defined in​

uri/src/uri.ts:364


load​

▸ load<T>(_recvCT?): Promise<T & DBMetadata>

Uses the DB reference in this URI's fragment to retrieve one or multiple rows or a single cell from a table with SELECT.

Throws

IOError On I/O errors or if this URI does not have a valid DB reference fragment.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe actual type returned.

Parameters​

NameTypeDescription
_recvCT?string | ContentTypeMust not be used.

Returns​

Promise<T & DBMetadata>

A cell, row or array of rows, with DBMetadata.

Overrides​

URI.load

Defined in​

uri/src/protocols/database.ts:979


modify​

▸ modify<T, D>(data, _sendCT?, _recvCT?): Promise<T & DBMetadata>

Uses the DB reference in this URI's fragment to modify one or multiple rows in a table using UPDATE.

Throws

IOError On I/O errors or if this URI does not have a valid DB reference fragment.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectObject.
DunknownThe type of the update data.

Parameters​

NameTypeDescription
dataDThe data to update in the table.
_sendCT?string | ContentTypeMust not be used.
_recvCT?string | ContentTypeMust not be used.

Returns​

Promise<T & DBMetadata>

Object(VOID), with DBMetadata.

Overrides​

URI.modify

Defined in​

uri/src/protocols/database.ts:1052


query​

▸ query<T>(...queries): Promise<T & DBMetadata>

Executes one or more queries in the same session.

Throws

TypeError If the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends object = object[]The actual type returned. Always an array.

Parameters​

NameTypeDescription
...queriesDBQuery[]The queries to execute.

Returns​

Promise<T & DBMetadata>

An array of rows from the last query. All result sets are available as a DBResult array via FIELDS (from the DBMetadata).

Overrides​

URI.query

Defined in​

uri/src/protocols/database.ts:1084

▸ query<T>(query, ...params): Promise<T & DBMetadata>

Executes a query in the form of a template literal.

All values/parameters will either be quoted and encoded or sent separately to the database server for processing, depending on the actual database driver. Example:

const users = dbURI.query<User>[]>`select * from users where first_name = ${firstName}`;

See also q, quote, raw, join, list, values and assign for handy utility functions.

Throws

TypeError If one of the parameters is undefined or if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends object = object[]The actual type returned. Always an array.

Parameters​

NameTypeDescription
queryTemplateStringsArrayThe query as a template string array.
...paramsBasicTypes[]The query parameters. Values may be DBQuery instances or of any type supported by the database.

Returns​

Promise<T & DBMetadata>

An array of rows. The raw set is available as a DBResult array — of length 1 — via FIELDS (from the DBMetadata).

Overrides​

URI.query

Defined in​

uri/src/protocols/database.ts:1108

▸ query<T>(query, params): Promise<T & DBMetadata>

Executes a query in the form of a query string. The string may contain {prop} placeholders, which will then be resolved against properties in params.

All values/parameters will either be quoted and encoded or sent separately to the database server for processing, depending on the actual database driver. Example:

const users = dbURI.query<User>[]>('select * from users where first_name = {name}', { name: firstName });

See also q, quote, raw, join, list, values and assign for handy utility functions.

Throws

TypeError If one of the parameters is undefined or if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends object = object[]The actual type returned. Always an array.

Parameters​

NameTypeDescription
querystringThe query, with {prop} placeholders for parameters.
paramsParamsAn record with parameters, used to look up placeholders from the query. Parameters may be DBQuery instances themselves, or of any type supported by the database.

Returns​

Promise<T & DBMetadata>

An array of rows. The raw set is available as a DBResult array — of length 1 — via FIELDS (from the DBMetadata).

Overrides​

URI.query

Defined in​

uri/src/protocols/database.ts:1133

▸ query<T>(params, cb): Promise<T>

Begins a transaction and evaluates the provided callback.

If the callback returns successfully, the transaction is committed and this method returns the callback's return value; if the callback throws, the transaction is rolled back and the exception is propagated.

Transaction deadlocks are handled automatically by default. When the driver detects that a transaction was aborted because of a deadlock, it waits a little based on the backoff function, and then invokes the callback again (the retryCount argument will be 1 on the first retry and so on), up to a maximum of retries times. Only then will the deadlock exception be propagated. To this behaviour, set retry to 0.

If this method is called recursively, savepoints will be created (and rolled back) instead of transactions, and params will be silently ignored. The retryCount argument is set to null in this case.

Throws

TypeError if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Throws

unknown Any exception thrown by cb is propagated.

Type parameters​

NameDescription
TThe return type of the callback.

Parameters​

NameTypeDescription
paramsDBTransactionParamsTransaction options, specifying the number of retries on deadlocks, the backoff strategey or transaction isolation level.
cbDBCallback<T>The function to evaluate inside the transaction/savepoint.

Returns​

Promise<T>

Whatever cb returns.

Overrides​

URI.query

Defined in​

uri/src/protocols/database.ts:1159

▸ query<T>(cb): Promise<T>

Begins a transaction and evaluates the provided callback.

If the callback returns successfully, the transaction is committed and this method returns the callback's return value; if the callback throws, the transaction is rolled back and the exception is propagated.

Transaction deadlocks are handled automatically. When the driver detects that a transaction was aborted because of a deadlock, it waits a few hundred milliseconds, and then invokes the callback again (the retryCount argument will be 1 on the first retry and so on), up to a maximum of 8 times. Only then will the deadlock exception be propagated. The wait time is approximately doubled on each retry, up to around 12 seconds.

If this method is called recursively, savepoints will be created (and rolled back) instead of transactions. The retryCount argument is set to null in this case.

Throws

TypeError if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Throws

unknown Any exception thrown by cb is propagated.

Type parameters​

NameDescription
TThe return type of the callback.

Parameters​

NameTypeDescription
cbDBCallback<T>The function to evaluate inside the transaction/savepoint.

Returns​

Promise<T>

Whatever cb returns.

Overrides​

URI.query

Defined in​

uri/src/protocols/database.ts:1182


remove​

▸ remove<T>(_recvCT?): Promise<T & DBMetadata>

Uses the DB reference in this URI's fragment to remove one or multiple rows from a table using DELETE.

Throws

IOError On I/O errors or if this URI does not have a valid DB reference fragment.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectObject.

Parameters​

NameTypeDescription
_recvCT?string | ContentTypeMust not be used.

Returns​

Promise<T & DBMetadata>

Object(VOID), with DBMetadata.

Overrides​

URI.remove

Defined in​

uri/src/protocols/database.ts:1067


save​

▸ save<T, D>(data, _sendCT?, _recvCT?): Promise<T & DBMetadata>

Uses the DB reference in this URI's fragment to store one or multiple rows in a table using upsert semantics (using INSERT ... ON CONFLICT UPDATE ... or UPSERT, for instance, but this depends on the database).

Throws

IOError On I/O errors or if this URI does not have a valid DB reference fragment.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe actual type returned.
DunknownThe type of data to store.

Parameters​

NameTypeDescription
dataDThe data to store in a row (or an array of rows to store).
_sendCT?string | ContentTypeMust not be used.
_recvCT?string | ContentTypeMust not be used.

Returns​

Promise<T & DBMetadata>

A row or array of rows (if the database supports it), with DBMetadata.

Overrides​

URI.save

Defined in​

uri/src/protocols/database.ts:1016


watch​

▸ watch<T>(query): AsyncIterable<T & DBMetadata>

Opens a change data capture channel to the database and returns a stream of change events.

Example:

for await (const ev of dbURI.watch(q`listen foo`)) {
console.log('New PostgreSQL notification', ev);
}

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe type of events that will be emitted.

Parameters​

NameTypeDescription
queryDBQueryThe query that opens the change event stream.

Returns​

AsyncIterable<T & DBMetadata>

A stream of change events.

Overrides​

URI.watch

Defined in​

uri/src/protocols/database.ts:1223

▸ watch<T>(query, ...params): AsyncIterable<T & DBMetadata>

Opens a change data capture channel to the database and returns a stream of change events.

for await (const ev of dbURI.watch`experimental changefeed FOR orders`) {
console.log('New order from CockroachDB', ev);
}

Throws

TypeError If one of the parameters is undefined or if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe type of events that will be emitted.

Parameters​

NameTypeDescription
queryTemplateStringsArrayThe query that opens the change event stream.
...paramsunknown[]The query parameters. Values may be DBQuery instances or of any type supported by the database.

Returns​

AsyncIterable<T & DBMetadata>

A stream of change events.

Overrides​

URI.watch

Defined in​

uri/src/protocols/database.ts:1242

▸ watch<T>(query, params): AsyncIterable<T & DBMetadata>

Opens a change data capture channel to the database and returns a stream of change events.

for await (const ev of dbURI.watch('experimental changefeed FOR orders', {})) {
console.log('New order from CockroachDB', ev);
}

Throws

TypeError If one of the parameters is undefined or if the arguments are invalid.

Throws

IOError On I/O errors.

Throws

DBError On database/query errors.

Type parameters​

NameTypeDescription
Textends objectThe type of events that will be emitted.

Parameters​

NameTypeDescription
querystringThe query that opens the change event stream, with {prop} placeholders for parameters.
paramsParamsAn record with parameters, used to look up placeholders from the query. Parameters may be DBQuery instances themselves, or of any type supported by the database.

Returns​

AsyncIterable<T & DBMetadata>

A stream of change events.

Overrides​

URI.watch

Defined in​

uri/src/protocols/database.ts:1261


$​

▸ Static $(strings, ...values): URI

Creates a new URI from a template string, percent-encoding all arguments.

Example:

const href = URI.$`http://${host}/blobs/${blob}?as=${ct}

Parameters​

NameTypeDescription
stringsTemplateStringsArrayThe template string array.
...valuesunknown[]The values to be encoded.

Returns​

URI

A new URI subclass instance.

Inherited from​

URI.$

Defined in​

uri/src/uri.ts:187


register​

▸ Static register(protocol, uri): typeof URI

Registers a new URI protocol. All subclasses must register their URL protocol support with this method.

Parameters​

NameTypeDescription
protocolstringThe URL protocol to register. Must include the trailing colon.
uritypeof URIThe URI subclass.

Returns​

typeof URI

The URI baseclass (for chaining).

Inherited from​

URI.register

Defined in​

uri/src/uri.ts:169