Reference
Client
Creates a new Client()
instance.
-
options
– This is an optional parameter. When it is not specified the client will connect to the current EdgeDB Project instance.If this parameter is a string it can represent either a DSN or an instance name:- when the string does not start with
edgedb://
it is a name of an instance; - otherwise it specifies a single string in the connection URI format:
edgedb://user:password@host:port/database?option=value
.See the Connection Parameters docs for full details.
ConnectOptions
config; see the documentation of valid options below. - when the string does not start with
-
options.dsn
(string
) – Specifies the DSN of the instance. -
options.credentialsFile
(string
) – Path to a file containing credentials. -
options.host
(string
) – Database host address as either an IP address or a domain name. -
options.port
(number
) – Port number to connect to at the server host. -
options.user
(string
) – The name of the database role used for authentication. -
options.database
(string
) – The name of the database to connect to. -
options.password
(string
) – Password to be used for authentication, if the server requires one. -
options.tlsCAFile
(string
) – Path to a file containing the root certificate of the server. -
options.tlsSecurity
(boolean
) – Determines whether certificate and hostname verification is enabled. Valid values are'strict'
(certificate will be fully validated),'no_host_verification'
(certificate will be validated, but hostname may not match),'insecure'
(certificate not validated, self-signed certificates will be trusted), or'default'
(acts asstrict
by default, orno_host_verification
iftlsCAFile
is set).
The above connection options can also be specified by their corresponding
environment variable. If none of dsn
, credentialsFile
, host
or
port
are explicitly specified, the client will connect to your
linked project instance, if it exists. For full details, see the
Connection Parameters docs.
-
options.timeout
(number
) – Connection timeout in milliseconds. -
options.waitUntilAvailable
(number
) – If first connection fails, the number of milliseconds to keep retrying to connect (Defaults to 30 seconds). Useful if your development instance and app are started together, to allow the server time to be ready. -
options.concurrency
(number
) – The maximum number of connection theClient
will create in it’s connection pool. If not specified the concurrency will be controlled by the server. This is recommended as it allows the server to better manage the number of client connections based on it’s own available resources.
Returns an instance of Client()
.
Example:
// Use the Node.js assert library to test results.
const assert = require("assert");
const edgedb = require("edgedb");
async function main() {
const client = edgedb.createClient();
const data = await client.querySingle("select 1 + 1");
// The result is a number 2.
assert(typeof data === "number");
assert(data === 2);
}
main();
A Client
allows you to run queries on an EdgeDB instance.
Since opening connections is an expensive operation, Client
also
maintains a internal pool of connections to the instance, allowing
connections to be automatically reused, and you to run multiple queries
on the client simultaneously, enhancing the performance of
database interactions.
Client()
is not meant to be instantiated directly;
createClient()
should be used instead.
Some methods take query arguments as an args parameter. The type of the args parameter depends on the query:
-
If the query uses positional query arguments, the args parameter must be an
array
of values of the types specified by each query argument’s type cast. -
If the query uses named query arguments, the args parameter must be an
object
with property names and values corresponding to the query argument names and type casts.
If a query argument is defined as optional
, the key/value can be
either omitted from the args object or be a null
value.
Execute an EdgeQL command (or commands).
-
query
– Query text.
This method takes optional query arguments.
Example:
await client.execute(`
CREATE TYPE MyType {
CREATE PROPERTY a -> int64
};
for x in {100, 200, 300}
union (insert MyType { a := x });
`)
Run an EdgeQL query and return the results as an array. This method always returns an array.
This method takes optional query arguments.
Run a query that returns at least one element and return the result as an array.
This method takes optional query arguments.
The query must return at least one element. If the query less than one
element, a ResultCardinalityMismatchError
error is thrown.
Run an optional singleton-returning query and return the result.
This method takes optional query arguments.
The query must return no more than one element. If the query returns
more than one element, a ResultCardinalityMismatchError
error is
thrown.
Run a singleton-returning query and return the result.
This method takes optional query arguments.
The query must return exactly one element. If the query returns
more than one element, a ResultCardinalityMismatchError
error is
thrown. If the query returns an empty set, a NoDataError
error is
thrown.
Run a query and return the results as a JSON-encoded string.
This method takes optional query arguments.
Caution is advised when reading decimal
or bigint
values using this method. The JSON specification does not
have a limit on significant digits, so a decimal
or a
bigint
number can be losslessly represented in JSON.
However, JSON decoders in JavaScript will often read all
such numbers as number
values, which may result in
precision loss. If such loss is unacceptable, then
consider casting the value into str
and decoding it on
the client side into a more appropriate type, such as
BigInt.
Run a query that returns at least one element and return the result as a JSON-encoded string.
This method takes optional query arguments.
The query must return at least one element. If the query less than one
element, a ResultCardinalityMismatchError
error is thrown.
Caution is advised when reading decimal
or bigint
values using this method. The JSON specification does not
have a limit on significant digits, so a decimal
or a
bigint
number can be losslessly represented in JSON.
However, JSON decoders in JavaScript will often read all
such numbers as number
values, which may result in
precision loss. If such loss is unacceptable, then
consider casting the value into str
and decoding it on
the client side into a more appropriate type, such as
BigInt.
Run an optional singleton-returning query and return its element as a JSON-encoded string.
This method takes optional query arguments.
The query must return at most one element. If the query returns
more than one element, an ResultCardinalityMismatchError
error
is thrown.
Caution is advised when reading decimal
or bigint
values using this method. The JSON specification does not
have a limit on significant digits, so a decimal
or a
bigint
number can be losslessly represented in JSON.
However, JSON decoders in JavaScript will often read all
such numbers as number
values, which may result in
precision loss. If such loss is unacceptable, then
consider casting the value into str
and decoding it on
the client side into a more appropriate type, such as
BigInt.
Run a singleton-returning query and return its element as a JSON-encoded string.
This method takes optional query arguments.
The query must return exactly one element. If the query returns
more than one element, a ResultCardinalityMismatchError
error
is thrown. If the query returns an empty set, a NoDataError
error
is thrown.
Caution is advised when reading decimal
or bigint
values using this method. The JSON specification does not
have a limit on significant digits, so a decimal
or a
bigint
number can be losslessly represented in JSON.
However, JSON decoders in JavaScript will often read all
such numbers as number
values, which may result in
precision loss. If such loss is unacceptable, then
consider casting the value into str
and decoding it on
the client side into a more appropriate type, such as
BigInt.
Execute a retryable transaction. The Transaction
object passed to
the action function has the same execute
and query*
methods
as Client
.
This is the preferred method of initiating and running a database
transaction in a robust fashion. The transaction()
method
will attempt to re-execute the transaction body if a transient error
occurs, such as a network error or a transaction serialization error.
The number of times transaction()
will attempt to execute the
transaction, and the backoff timeout between retries can be
configured with Client.withRetryOptions()
.
See Transactions for more details.
Example:
await client.transaction(async tx => {
const value = await tx.querySingle("select Counter.value")
await tx.execute(
`update Counter set { value := <int64>$value }`,
{value: value + 1},
)
});
Note that we are executing queries on the tx
object rather
than on the original client
.
If the client does not yet have any open connections in its pool, attempts to open a connection, else returns immediately.
Since the client lazily creates new connections as needed (up to the
configured concurrency
limit), the first connection attempt will
only occur when the first query is run a client. ensureConnected
can be useful to catch any errors resulting from connection
mis-configuration by triggering the first connection attempt
explicitly.
Example:
import {createClient} from 'edgedb';
async function getClient() {
try {
return await createClient('custom_instance').ensureConnected();
} catch (err) {
// handle connection error
}
}
function main() {
const client = await getClient();
await client.query('select ...');
}
Returns a new Client
instance with the specified global values.
The globals
argument object is merged with any existing globals
defined on the current client instance.
Equivalent to using the set global
command.
Example:
const user = await client.withGlobals({
userId: '...'
}).querySingle(`
select User {name} filter .id = global userId
`);
Returns a new Client
instance with the specified module aliases.
The aliases
argument object is merged with any existing module
aliases defined on the current client instance.
If the alias name
is module
this is equivalent to using
the set module
command, otherwise it is equivalent to the
set alias
command.
Example:
const user = await client.withModuleAliases({
module: 'sys'
}).querySingle(`
select get_version_as_str()
`);
// "2.0"
Returns a new Client
instance with the specified client session
configuration. The config
argument object is merged with any
existing session config defined on the current client instance.
Equivalent to using the configure session
command. For available
configuration parameters refer to the
Config documentation.
Returns a new Client
instance with the specified retry attempts
number and backoff time function (the time that retrying methods will
wait between retry attempts, in milliseconds), where options not given
are inherited from the current client instance.
The default number of attempts is 3
. The default backoff
function returns a random time between 100 and 200ms multiplied by
2 ^ attempt number
.
The new client instance will share the same connection pool as the
client it’s created from, so calling the ensureConnected
,
close
and terminate
methods will affect all clients
sharing the pool.
Example:
import {createClient} from 'edgedb';
function main() {
const client = createClient();
// By default transactions will retry if they fail
await client.transaction(async tx => {
// ...
});
const nonRetryingClient = client.withRetryOptions({
attempts: 1
});
// This transaction will not retry
await nonRetryingClient.transaction(async tx => {
// ...
});
}
Close the client’s open connections gracefully. When a client is closed, all its underlying connections are awaited to complete their pending operations, then closed. A warning is produced if the pool takes more than 60 seconds to close.
Clients will not prevent Node.js from exiting once all of it’s
open connections are idle and Node.js has no further tasks it is
awaiting on, so it is not necessary to explicitly call close()
if it is more convenient for your application.
(This does not apply to Deno, since Deno is missing the
required API’s to unref
idle connections)
Type conversion
The client automatically converts EdgeDB types to the corresponding JavaScript types and vice versa.
The table below shows the correspondence between EdgeDB and JavaScript types.
EdgeDB Type |
JavaScript Type |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
n/a |
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
Inexact single-precision float
values may have a different
representation when decoded into a JavaScript number. This is inherent
to the implementation of limited-precision floating point types.
If you need the decimal representation to match, cast the expression
to float64
in your query.
Due to precision limitations the decimal
type cannot be decoded to a
JavaScript number. Use an explicit cast to float64
if the precision
degradation is acceptable or a cast to str
for an exact decimal
representation.
Arrays
EdgeDB array
maps onto the JavaScript Array
.
// Use the Node.js assert library to test results.
const assert = require("assert");
const edgedb = require("edgedb");
async function main() {
const client = edgedb.createClient("edgedb://edgedb@localhost/");
const data = await client.querySingle("select [1, 2, 3]");
// The result is an Array.
assert(data instanceof Array);
assert(typeof data[0] === "number");
assert(data.length === 3);
assert(data[2] === 3);
}
main();
Objects
Object
represents an object instance returned from a query. The value of an
object property or a link can be accessed through a corresponding object key:
// Use the Node.js assert library to test results.
const assert = require("assert");
const edgedb = require("edgedb");
async function main() {
const client = edgedb.createClient("edgedb://edgedb@localhost/");
const data = await client.querySingle(`
select schema::Property {
name,
annotations: {name, @value}
}
filter .name = 'listen_port'
and .source.name = 'cfg::Config'
limit 1
`);
// The property 'name' is accessible.
assert(typeof data.name === "string");
// The link 'annotaions' is accessible and is a Set.
assert(typeof data.annotations === "object");
assert(data.annotations instanceof edgedb.Set);
// The Set of 'annotations' is array-like.
assert(data.annotations.length > 0);
assert(data.annotations[0].name === "cfg::system");
assert(data.annotations[0]["@value"] === "true");
}
main();
Tuples
A regular EdgeDB tuple
becomes an Array
in JavaScript.
// Use the Node.js assert library to test results.
const assert = require("assert");
const edgedb = require("edgedb");
async function main() {
const client = edgedb.createClient("edgedb://edgedb@localhost/");
const data = await client.querySingle(`
select (1, 'a', [3])
`);
// The resulting tuple is an Array.
assert(data instanceof Array);
assert(data.length === 3);
assert(typeof data[0] === "number");
assert(typeof data[1] === "string");
assert(data[2] instanceof Array);
}
main();
Named Tuples
A named EdgeDB tuple
becomes an Array
-like object
in JavaScript,
where the elements are accessible either by their names or indexes.
// Use the Node.js assert library to test results.
const assert = require("assert");
const edgedb = require("edgedb");
async function main() {
const client = edgedb.createClient("edgedb://edgedb@localhost/");
const data = await client.querySingle(`
select (a := 1, b := 'a', c := [3])
`);
// The resulting tuple is an Array.
assert(data instanceof Array);
assert(data.length === 3);
assert(typeof data[0] === "number");
assert(typeof data[1] === "string");
assert(data[2] instanceof Array);
// Elements can be accessed by their names.
assert(typeof data.a === "number");
assert(typeof data["b"] === "string");
assert(data.c instanceof Array);
}
main();
Local Date
A JavaScript representation of an EdgeDB local_date
value. Implements
a subset of the TC39 Temporal Proposal
PlainDate
type.
Assumes the calendar is always ISO 8601.
Local Time
A JavaScript representation of an EdgeDB local_time
value. Implements
a subset of the TC39 Temporal Proposal
PlainTime
type.
The EdgeDB local_time
type only has microsecond precision, any
nanoseconds specified in the LocalTime
will be ignored when
encoding to an EdgeDB local_time
.
Local Date and Time
A JavaScript representation of an EdgeDB local_datetime
value.
Implements a subset of the TC39 Temporal Proposal
PlainDateTime
type.
Inherits all properties from the LocalDate()
and
LocalTime()
types.
Duration
A JavaScript representation of an EdgeDB duration
value. This class
attempts to conform to the TC39 Temporal Proposal
Duration
type as
closely as possible.
No arguments may be infinite and all must have the same sign. Any non-integer arguments will be rounded towards zero.
The Temporal Duration
type can contain both absolute duration
components, such as hours, minutes, seconds, etc. and relative
duration components, such as years, months, weeks, and days, where
their absolute duration changes depending on the exact date they are
relative to (eg. different months have a different number of days).
The EdgeDB duration
type only supports absolute durations, so any
Duration
with non-zero years, months, weeks, or days will throw
an error when trying to encode them.
The EdgeDB duration
type only has microsecond precision, any
nanoseconds specified in the Duration
will be ignored when
encoding to an EdgeDB duration
.
Temporal Duration
objects can be unbalanced, (ie. have a greater
value in any property than it would naturally have, eg. have a seconds
property greater than 59), but EdgeDB duration
objects are always
balanced.
Therefore in a round-trip of a Duration
object to EdgeDB and back,
the returned object, while being an equivalent duration, may not
have exactly the same property values as the sent object.
Get the string representation of the duration in ISO 8601 duration format.
RelativeDuration
A JavaScript representation of an EdgeDB
cal::relative_duration
value. This type represents a
non-definite span of time such as “2 years 3 days”. This cannot be
represented as a duration
because a year has no absolute
duration; for instance, leap years are longer than non-leap years.
This class attempts to conform to the TC39 Temporal Proposal
Duration
type as closely as possible.
Internally, a cal::relative_duration
value is represented as an
integer number of months, days, and seconds. During encoding, other units
will be normalized to these three. Sub-second units like microseconds
will be ignored.
Get the string representation of the duration in ISO 8601 duration format.
DateDuration
A JavaScript representation of an EdgeDB
cal::date_duration
value. This type represents a
non-definite span of time consisting of an integer number of months and
days.
This type is primarily intended to simplify logic involving
cal::local_date
values.
db>
select <cal::date_duration>'5 days';
{<cal::date_duration>'P5D'}
db>
select <cal::local_date>'2022-06-25' + <cal::date_duration>'5 days';
{<cal::local_date>'2022-06-30'}
db>
select <cal::local_date>'2022-06-30' - <cal::local_date>'2022-06-25';
{<cal::date_duration>'P5D'}
Internally, a cal::relative_duration
value is represented as an
integer number of months and days. During encoding, other units will be
normalized to these two.
Get the string representation of the duration in ISO 8601 duration format.
Memory
The memory value in bytes (B).
The EdgeDB cfg::memory
represents a number of bytes stored as
an int64
. Since JS the number
type is a float64
, values
above ~8191TiB
will lose precision when represented as a JS
number
. To keep full precision use the bytesBigInt
property.
Range
A JavaScript representation of an EdgeDB std::range
value. This is a generic TypeScript class with the following type signature.
class Range<
T extends number | Date | LocalDate | LocalDateTime | Duration
>{
// ...
}