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:
Database | Database driver class |
---|---|
CockroachDB | PostgresURI |
H2 | JDBCURI† |
MariaDB | MySQLURI |
MySQL | MySQLURI |
PostgreSQL | PostgresURI |
SQL Server | TDSURI |
SQLite | SQLiteURI |
† 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.
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
↳
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
Name | Type | Description |
---|---|---|
url? | string | URL | Url | The 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? | Params | An optional record with parameters, used in case url is a string. |
Inherited from
Defined in
• 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
Name | Type | Description |
---|---|---|
url? | string | URL | Url | The 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 | Url | A 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? | Params | An optional record with parameters, used in case url and/or base is a string. |
Inherited from
Defined in
Properties
href
• Readonly
href: string
This URI's string representation. Unlike in URL, this property may not be changed/updated.
Inherited from
Defined in
origin
• Readonly
origin: string
This URI's origin. Unlike in URL, this property may not be changed/updated.
Inherited from
Defined in
protocol
• Readonly
protocol: string
This URI's protocol. Unlike in URL, this property may not be changed/updated.
Inherited from
Defined in
selectors
• selectors: Object
All selectors that may apply to this URI. Use addSelector to modify this property.
Type declaration
Name | Type | Description |
---|---|---|
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
Defined in
FIELDS
▪ Static
Readonly
FIELDS: symbol
= FIELDS
An alias for FIELDS.
Inherited from
Defined in
FINALIZE
▪ Static
Readonly
FINALIZE: symbol
= FINALIZE
An alias for FIELDS.
Inherited from
Defined in
HEADERS
▪ Static
Readonly
HEADERS: symbol
= HEADERS
An alias for HEADERS.
Inherited from
Defined in
NULL
▪ Static
Readonly
NULL: symbol
= NULL
An alias for NULL.
Inherited from
Defined in
STATUS
▪ Static
Readonly
STATUS: symbol
= STATUS
An alias for STATUS.
Inherited from
Defined in
STATUS_TEXT
▪ Static
Readonly
STATUS_TEXT: symbol
= STATUS_TEXT
An alias for STATUS_TEXT.
Inherited from
Defined in
VOID
▪ Static
Readonly
VOID: symbol
= VOID
An alias for VOID.
Inherited from
Defined in
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
Name | Type | Description |
---|---|---|
strings | TemplateStringsArray | The template string array. |
...values | unknown [] | The values to be encoded. |
Returns
A new DatabaseURI subclass instance.
Overrides
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
Defined in
_createDBConnectionPool
▸ Protected
Abstract
_createDBConnectionPool(params
): DBConnectionPool
| Promise
<DBConnectionPool
>
Parameters
Name | Type |
---|---|
params | DBParamsSelector |
Returns
DBConnectionPool
| Promise
<DBConnectionPool
>
Defined in
uri/src/protocols/database.ts:941
_getAuthorization
▸ Protected
_getAuthorization(req
, payload?
, challenges?
): Promise
<undefined
| Authorization
>
Parameters
Name | Type |
---|---|
req | AuthSchemeRequest |
payload? | Buffer | AsyncIterable <Buffer > |
challenges? | WWWAuthenticate [] |
Returns
Promise
<undefined
| Authorization
>
Inherited from
Defined in
_getBestSelector
▸ Protected
_getBestSelector<T
>(sels
, challenge?
): null
| T
Type parameters
Name | Type |
---|---|
T | extends SelectorBase |
Parameters
Name | Type |
---|---|
sels | undefined | T [] |
challenge? | WWWAuthenticate |
Returns
null
| T
Inherited from
Defined in
_guessContentType
▸ Protected
_guessContentType(knownContentType?
): undefined
| ContentType
Parameters
Name | Type |
---|---|
knownContentType? | string | ContentType |
Returns
undefined
| ContentType
Inherited from
Defined in
_makeIOError
▸ Protected
_makeIOError(err
): IOError
Parameters
Name | Type |
---|---|
err | unknown |
Returns
Inherited from
Defined in
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
Name | Type |
---|---|
T | extends AuthSelector | HeadersSelector | ParamsSelector | SessionSelector |
Parameters
Name | Type | Description |
---|---|---|
selector | T | The selector to add. |
Returns
This URI.
Inherited from
Defined in
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
Name | Type | Description |
---|---|---|
T | extends object | The actual type returned. |
D | unknown | The type of data to store. |
Parameters
Name | Type | Description |
---|---|---|
data | D | The data to add to the table. |
_sendCT? | string | ContentType | Must not be used. |
_recvCT? | string | ContentType | Must not be used. |
Returns
Promise
<T
& DBMetadata
>
A row or array of rows (if the database supports it), with DBMetadata.
Overrides
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
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
Name | Type | Description |
---|---|---|
T | extends DirectoryEntry | The actual type of information record returned. Must extend DirectoryEntry. |
Returns
Promise
<T
& Metadata
>
An information record describing the resources.
Inherited from
Defined in
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
Name | Type | Description |
---|---|---|
T | extends DirectoryEntry | The actual type of information record returned. Must extend DirectoryEntry. |
Returns
Promise
<T
[] & Metadata
>
An array of information record describing the subresources.
Inherited from
Defined in
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
Name | Type | Description |
---|---|---|
T | extends object | The actual type returned. |
Parameters
Name | Type | Description |
---|---|---|
_recvCT? | string | ContentType | Must not be used. |
Returns
Promise
<T
& DBMetadata
>
A cell, row or array of rows, with DBMetadata.
Overrides
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
Name | Type | Description |
---|---|---|
T | extends object | Object. |
D | unknown | The type of the update data. |
Parameters
Name | Type | Description |
---|---|---|
data | D | The data to update in the table. |
_sendCT? | string | ContentType | Must not be used. |
_recvCT? | string | ContentType | Must not be used. |
Returns
Promise
<T
& DBMetadata
>
Object(VOID), with DBMetadata.
Overrides
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
Name | Type | Description |
---|---|---|
T | extends object = object [] | The actual type returned. Always an array. |
Parameters
Name | Type | Description |
---|---|---|
...queries | DBQuery [] | 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
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
Name | Type | Description |
---|---|---|
T | extends object = object [] | The actual type returned. Always an array. |
Parameters
Name | Type | Description |
---|---|---|
query | TemplateStringsArray | The query as a template string array. |
...params | BasicTypes [] | 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
Name | Type | Description |
---|---|---|
T | extends object = object [] | The actual type returned. Always an array. |
Parameters
Name | Type | Description |
---|---|---|
query | string | The query, with {prop} placeholders for parameters. |
params | Params | An 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
Name | Description |
---|---|
T | The return type of the callback. |
Parameters
Name | Type | Description |
---|---|---|
params | DBTransactionParams | Transaction options, specifying the number of retries on deadlocks, the backoff strategey or transaction isolation level. |
cb | DBCallback <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
Name | Description |
---|---|
T | The return type of the callback. |
Parameters
Name | Type | Description |
---|---|---|
cb | DBCallback <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
Name | Type | Description |
---|---|---|
T | extends object | Object. |
Parameters
Name | Type | Description |
---|---|---|
_recvCT? | string | ContentType | Must not be used. |
Returns
Promise
<T
& DBMetadata
>
Object(VOID), with DBMetadata.
Overrides
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
Name | Type | Description |
---|---|---|
T | extends object | The actual type returned. |
D | unknown | The type of data to store. |
Parameters
Name | Type | Description |
---|---|---|
data | D | The data to store in a row (or an array of rows to store). |
_sendCT? | string | ContentType | Must not be used. |
_recvCT? | string | ContentType | Must not be used. |
Returns
Promise
<T
& DBMetadata
>
A row or array of rows (if the database supports it), with DBMetadata.
Overrides
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
Name | Type | Description |
---|---|---|
T | extends object | The type of events that will be emitted. |
Parameters
Name | Type | Description |
---|---|---|
query | DBQuery | The query that opens the change event stream. |
Returns
AsyncIterable
<T
& DBMetadata
>
A stream of change events.
Overrides
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
Name | Type | Description |
---|---|---|
T | extends object | The type of events that will be emitted. |
Parameters
Name | Type | Description |
---|---|---|
query | TemplateStringsArray | The query that opens the change event stream. |
...params | unknown [] | 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
Name | Type | Description |
---|---|---|
T | extends object | The type of events that will be emitted. |
Parameters
Name | Type | Description |
---|---|---|
query | string | The query that opens the change event stream, with {prop} placeholders for parameters. |
params | Params | An 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
Name | Type | Description |
---|---|---|
strings | TemplateStringsArray | The template string array. |
...values | unknown [] | The values to be encoded. |
Returns
A new URI subclass instance.
Inherited from
Defined in
register
▸ Static
register(protocol
, uri
): typeof URI
Registers a new URI protocol. All subclasses must register their URL protocol support with this method.
Parameters
Name | Type | Description |
---|---|---|
protocol | string | The URL protocol to register. Must include the trailing colon. |
uri | typeof URI | The URI subclass. |
Returns
typeof URI
The URI baseclass (for chaining).