Reference
Client
function
createClient()
createClient(options: string | ConnectOptions | null): Client
Creates a new Client() instance.
Arguments
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.
Alternatively the parameter can be a
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.
Arguments
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
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();
class
Client
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.
method
Client.execute()
Client.execute(query: string): Promise<void>
Execute an EdgeQL command (or commands).
Arguments
query
– Query text.
This commands takes no arguments.
Example:
await client.execute(`
CREATE TYPE MyType {
CREATE PROPERTY a -> int64
};
for x in {100, 200, 300}
union (insert MyType { a := x });
`)
method
Client.query<T>()
Client.query<T>(query: string, args?: QueryArgs): Promise<T[]>
Run a query and return the results as an array. This method always returns an array.
This method takes optional query arguments.
method
Client.querySingle<T>()
Client.querySingle<T>(query: string, args?: QueryArgs): Promise<T | null>
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.
method
Client.queryRequiredSingle<T>()
Client.queryRequiredSingle<T>(query: string, args?: QueryArgs): Promise<T>
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.
method
Client.queryJSON()
Client.queryJSON(query: string, args?: QueryArgs): Promise<string>
Run a query and return the results as JSON.
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.
method
Client.querySingleJSON()
Client.querySingleJSON(query: string, args?: QueryArgs): Promise<string>
Run an optional singleton-returning query and return its element in JSON.
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.
method
Client.queryRequiredSingleJSON()
Client.queryRequiredSingleJSON(query: string, args?: QueryArgs): Promise<string>
Run a singleton-returning query and return its element in JSON.
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.
method
Client.transaction<T>()
Client.transaction<T>(action: (tx: Transaction) => Promise<T>): Promise<T>
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
.
method
Client.ensureConnected()
Client.ensureConnected(): Promise<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 ...');
}
method
Client.withRetryOptions()
Client.withRetryOptions(opts: { attempts?: number backoff?: (attempt: number) => number }): Client
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 => {
// ...
});
}
method
Client.close()
Client.close(): Promise<void>
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)
method
Client.isClosed()
Client.isClosed(): boolean
Returns true if close()
has been called on the client.
method
Client.terminate()
Client.terminate(): void
Terminate all connections in the client, closing all connections non gracefully. If the client is already closed, return without doing anything.
Type conversion
The driver 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.
Sets
class
Set
Set extends Array
Under the hood, the result of the .query
method is an instance of edgedb.Set
. This class represents a set of values returned by a query. If the query contained an explicit ORDER BY
clause, the values will be ordered, otherwise no specific ordering is guaranteed.
This type also allows to differentiate between a set of values and an explicit array.
const result = await client.query(`select {0, 1, 2}`);
result instanceof edgedb.Set; // true
result[0]; // 0
result[1]; // 1
result[2]; // 2
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
class
LocalDate
LocalDate(year: number, month: number, day: number)
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.
attribute
LocalDate.year
LocalDate.year: number
The year value of the local date.
attribute
LocalDate.month
LocalDate.month: number
The numerical month value of the local date.
Unlike the JS Date
object, months in LocalDate
start at 1. ie. Jan = 1, Feb = 2, etc.
attribute
LocalDate.day
LocalDate.day: number
The day of the month value of the local date (starting with 1).
attribute
LocalDate.dayOfWeek
LocalDate.dayOfWeek: number
The weekday number of the local date. Returns a value between 1 and 7 inclusive, where 1 = Monday and 7 = Sunday.
attribute
LocalDate.dayOfYear
LocalDate.dayOfYear: number
The ordinal day of the year of the local date. Returns a value between 1 and 365 (or 366 in a leap year).
attribute
LocalDate.weekOfYear
LocalDate.weekOfYear: number
The ISO week number of the local date. Returns a value between 1 and 53, where ISO week 1 is defined as the week containing the first Thursday of the year.
attribute
LocalDate.daysInWeek
LocalDate.daysInWeek: number
The number of days in the week of the local date. Always returns 7.
attribute
LocalDate.daysInMonth
LocalDate.daysInMonth: number
The number of days in the month of the local date. Returns a value between 28 and 31 inclusive.
attribute
LocalDate.daysInYear
LocalDate.daysInYear: number
The number of days in the year of the local date. Returns either 365 or 366 if the year is a leap year.
attribute
LocalDate.monthsInYear
LocalDate.monthsInYear: number
The number of months in the year of the local date. Always returns 12.
attribute
LocalDate.inLeapYear
LocalDate.inLeapYear: boolean
Return whether the year of the local date is a leap year.
method
LocalDate.toString()
LocalDate.toString(): string
Get the string representation of the LocalDate
in the YYYY-MM-DD
format.
method
LocalDate.toJSON()
LocalDate.toJSON(): number
Same as toString().
method
LocalDate.valueOf()
LocalDate.valueOf(): never
Always throws an Error. LocalDate
objects are not comparable.
Local Time
class
LocalTime
LocalTime(hour: number = 0, minute: number = 0, second: number = 0, millisecond: number = 0, microsecond: number = 0, nanosecond: number = 0)
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
.
attribute
LocalTime.hour
LocalTime.hour: number
The hours component of the local time in 0-23 range.
attribute
LocalTime.minute
LocalTime.minute: number
The minutes component of the local time in 0-59 range.
attribute
LocalTime.second
LocalTime.second: number
The seconds component of the local time in 0-59 range.
attribute
LocalTime.millisecond
LocalTime.millisecond: number
The millisecond component of the local time in 0-999 range.
attribute
LocalTime.microsecond
LocalTime.microsecond: number
The microsecond component of the local time in 0-999 range.
attribute
LocalTime.nanosecond
LocalTime.nanosecond: number
The nanosecond component of the local time in 0-999 range.
method
LocalTime.toString()
LocalTime.toString(): string
Get the string representation of the local_time
in the HH:MM:SS
24-hour format.
method
LocalTime.toJSON()
LocalTime.toJSON(): number
Same as toString().
method
LocalTime.valueOf()
LocalTime.valueOf(): never
Always throws an Error. LocalTime
objects are not comparable.
Local Date and Time
class
LocalDateTime
LocalDateTime(year: number, month: number, day: number, hour: number = 0, minute: number = 0, second: number = 0, millisecond: number = 0, microsecond: number = 0, nanosecond: number = 0) extends LocalDate, LocalTime
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.
method
LocalDateTime.toString()
LocalDateTime.toString(): string
Get the string representation of the local_datetime
in the YYYY-MM-DDTHH:MM:SS
24-hour format.
method
LocalDateTime.toJSON()
LocalDateTime.toJSON(): number
Same as toString().
method
LocalDateTime.valueOf()
LocalDateTime.valueOf(): never
Always throws an Error. LocalDateTime
objects are not comparable.
Duration
class
Duration
Duration(years: number = 0, months: number = 0, weeks: number = 0, days: number = 0, hours: number = 0, minutes: number = 0, seconds: number = 0, milliseconds: number = 0, microseconds: number = 0, nanoseconds: number = 0)
A JavaScript representation of an EdgeDB duration
value. Implements a subset of the TC39 Temporal Proposal Duration
type.
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.
attribute
Duration.years
Duration.years: number
The number of years in the duration.
attribute
Duration.months
Duration.months: number
The number of months in the duration.
attribute
Duration.weeks
Duration.weeks: number
The number of weeks in the duration.
attribute
Duration.days
Duration.days: number
The number of days in the duration.
attribute
Duration.hours
Duration.hours: number
The number of hours in the duration.
attribute
Duration.minutes
Duration.minutes: number
The number of minutes in the duration.
attribute
Duration.seconds
Duration.seconds: number
The number of seconds in the duration.
attribute
Duration.milliseconds
Duration.milliseconds: number
The number of milliseconds in the duration.
attribute
Duration.microseconds
Duration.microseconds: number
The number of microseconds in the duration.
attribute
Duration.nanoseconds
Duration.nanoseconds: number
The number of nanoseconds in the duration.
attribute
Duration.sign
Duration.sign: number
Returns -1, 0, or 1 depending on whether the duration is negative, zero or positive.
attribute
Duration.blank
Duration.blank: boolean
Returns true
if the duration is zero.
method
Duration.toString()
Duration.toString(): string
Get the string representation of the duration in ISO 8601 duration format.
method
Duration.toJSON()
Duration.toJSON(): number
Same as toString().
method
Duration.valueOf()
Duration.valueOf(): never
Always throws an Error. Duration
objects are not comparable.
Memory
class
ConfigMemory
ConfigMemory(bytes: BigInt)
A JavaScript representation of an EdgeDB cfg::memory
value.
attribute
ConfigMemory.bytes
ConfigMemory.bytes: number
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.
attribute
ConfigMemory.kibibytes
ConfigMemory.kibibytes: number
The memory value in kibibytes (KiB).
attribute
ConfigMemory.mebibytes
ConfigMemory.mebibytes: number
The memory value in mebibytes (MiB).
attribute
ConfigMemory.gibibytes
ConfigMemory.gibibytes: number
The memory value in gibibytes (GiB).
attribute
ConfigMemory.tebibytes
ConfigMemory.tebibytes: number
The memory value in tebibytes (TiB).
attribute
ConfigMemory.pebibytes
ConfigMemory.pebibytes: number
The memory value in pebibytes (PiB).
method
ConfigMemory.toString()
ConfigMemory.toString(): string
Get the string representation of the memory value. Format is the same as returned by string casting a cfg::memory
value in EdgeDB.