Reference​

Client​

function

createClient()

Reference - 图1

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.

  • 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 as strict by default, or no_host_verification if tlsCAFile 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 the Client 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:

  1. // Use the Node.js assert library to test results.
  2. const assert = require("assert");
  3. const edgedb = require("edgedb");
  4. async function main() {
  5. const client = edgedb.createClient();
  6. const data = await client.querySingle("select 1 + 1");
  7. // The result is a number 2.
  8. assert(typeof data === "number");
  9. assert(data === 2);
  10. }
  11. main();

class

Client

Reference - 图2

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()

Reference - 图3

Client.execute(query: string): Promise<void>

Execute an EdgeQL command (or commands).

Arguments

  • query – Query text.

This commands takes no arguments.

Example:

  1. await client.execute(`
  2. CREATE TYPE MyType {
  3. CREATE PROPERTY a -> int64
  4. };
  5. for x in {100, 200, 300}
  6. union (insert MyType { a := x });
  7. `)

method

Client.query<T>()

Reference - 图4

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>()

Reference - 图5

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>()

Reference - 图6

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()

Reference - 图7

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()

Reference - 图8

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()

Reference - 图9

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>()

Reference - 图10

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:

  1. await client.transaction(async tx => {
  2. const value = await tx.querySingle("select Counter.value")
  3. await tx.execute(
  4. `update Counter set { value := <int64>$value }`,
  5. {value: value + 1},
  6. )
  7. });

Note that we are executing queries on the tx object rather than on the original client.

method

Client.ensureConnected()

Reference - 图11

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:

  1. import {createClient} from 'edgedb';
  2. async function getClient() {
  3. try {
  4. return await createClient('custom_instance').ensureConnected();
  5. } catch (err) {
  6. // handle connection error
  7. }
  8. }
  9. function main() {
  10. const client = await getClient();
  11. await client.query('select ...');
  12. }

method

Client.withRetryOptions()

Reference - 图12

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:

  1. import {createClient} from 'edgedb';
  2. function main() {
  3. const client = createClient();
  4. // By default transactions will retry if they fail
  5. await client.transaction(async tx => {
  6. // ...
  7. });
  8. const nonRetryingClient = client.withRetryOptions({
  9. attempts: 1
  10. });
  11. // This transaction will not retry
  12. await nonRetryingClient.transaction(async tx => {
  13. // ...
  14. });
  15. }

method

Client.close()

Reference - 图13

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()

Reference - 图14

Client.isClosed(): boolean

Returns true if close() has been called on the client.

method

Client.terminate()

Reference - 图15

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

Set

Array

array<anytype>

Array

anytuple

Array or Array-like object

anyenum

string

Object

object

bool

boolean

bytes

Buffer

str

string

cal::local_date

LocalDate()

cal::local_time

LocalTime()

cal::local_datetime

LocalDateTime()

datetime

Date

duration

Duration()

float32, float64 int16, int32, int64

number

bigint

BigInt

decimal

n/a

json

string

uuid

edgedb.UUID

cfg::memory

ConfigMemory()

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

Reference - 图16

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.

  1. const result = await client.query(`select {0, 1, 2}`);
  2. result instanceof edgedb.Set; // true
  3. result[0]; // 0
  4. result[1]; // 1
  5. result[2]; // 2

Arrays​

EdgeDB array maps onto the JavaScript Array.

  1. // Use the Node.js assert library to test results.
  2. const assert = require("assert");
  3. const edgedb = require("edgedb");
  4. async function main() {
  5. const client = edgedb.createClient("edgedb://edgedb@localhost/");
  6. const data = await client.querySingle("select [1, 2, 3]");
  7. // The result is an Array.
  8. assert(data instanceof Array);
  9. assert(typeof data[0] === "number");
  10. assert(data.length === 3);
  11. assert(data[2] === 3);
  12. }
  13. 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:

  1. // Use the Node.js assert library to test results.
  2. const assert = require("assert");
  3. const edgedb = require("edgedb");
  4. async function main() {
  5. const client = edgedb.createClient("edgedb://edgedb@localhost/");
  6. const data = await client.querySingle(`
  7. select schema::Property {
  8. name,
  9. annotations: {name, @value}
  10. }
  11. filter .name = 'listen_port'
  12. and .source.name = 'cfg::Config'
  13. limit 1
  14. `);
  15. // The property 'name' is accessible.
  16. assert(typeof data.name === "string");
  17. // The link 'annotaions' is accessible and is a Set.
  18. assert(typeof data.annotations === "object");
  19. assert(data.annotations instanceof edgedb.Set);
  20. // The Set of 'annotations' is array-like.
  21. assert(data.annotations.length > 0);
  22. assert(data.annotations[0].name === "cfg::system");
  23. assert(data.annotations[0]["@value"] === "true");
  24. }
  25. main();

Tuples​

A regular EdgeDB tuple becomes an Array in JavaScript.

  1. // Use the Node.js assert library to test results.
  2. const assert = require("assert");
  3. const edgedb = require("edgedb");
  4. async function main() {
  5. const client = edgedb.createClient("edgedb://edgedb@localhost/");
  6. const data = await client.querySingle(`
  7. select (1, 'a', [3])
  8. `);
  9. // The resulting tuple is an Array.
  10. assert(data instanceof Array);
  11. assert(data.length === 3);
  12. assert(typeof data[0] === "number");
  13. assert(typeof data[1] === "string");
  14. assert(data[2] instanceof Array);
  15. }
  16. 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.

  1. // Use the Node.js assert library to test results.
  2. const assert = require("assert");
  3. const edgedb = require("edgedb");
  4. async function main() {
  5. const client = edgedb.createClient("edgedb://edgedb@localhost/");
  6. const data = await client.querySingle(`
  7. select (a := 1, b := 'a', c := [3])
  8. `);
  9. // The resulting tuple is an Array.
  10. assert(data instanceof Array);
  11. assert(data.length === 3);
  12. assert(typeof data[0] === "number");
  13. assert(typeof data[1] === "string");
  14. assert(data[2] instanceof Array);
  15. // Elements can be accessed by their names.
  16. assert(typeof data.a === "number");
  17. assert(typeof data["b"] === "string");
  18. assert(data.c instanceof Array);
  19. }
  20. main();

Local Date​

class

LocalDate

Reference - 图17

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

Reference - 图18

LocalDate.year: number

The year value of the local date.

attribute

LocalDate.month

Reference - 图19

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

Reference - 图20

LocalDate.day: number

The day of the month value of the local date (starting with 1).

attribute

LocalDate.dayOfWeek

Reference - 图21

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

Reference - 图22

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

Reference - 图23

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

Reference - 图24

LocalDate.daysInWeek: number

The number of days in the week of the local date. Always returns 7.

attribute

LocalDate.daysInMonth

Reference - 图25

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

Reference - 图26

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

Reference - 图27

LocalDate.monthsInYear: number

The number of months in the year of the local date. Always returns 12.

attribute

LocalDate.inLeapYear

Reference - 图28

LocalDate.inLeapYear: boolean

Return whether the year of the local date is a leap year.

method

LocalDate.toString()

Reference - 图29

LocalDate.toString(): string

Get the string representation of the LocalDate in the YYYY-MM-DD format.

method

LocalDate.toJSON()

Reference - 图30

LocalDate.toJSON(): number

Same as toString().

method

LocalDate.valueOf()

Reference - 图31

LocalDate.valueOf(): never

Always throws an Error. LocalDate objects are not comparable.

Local Time​

class

LocalTime

Reference - 图32

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

Reference - 图33

LocalTime.hour: number

The hours component of the local time in 0-23 range.

attribute

LocalTime.minute

Reference - 图34

LocalTime.minute: number

The minutes component of the local time in 0-59 range.

attribute

LocalTime.second

Reference - 图35

LocalTime.second: number

The seconds component of the local time in 0-59 range.

attribute

LocalTime.millisecond

Reference - 图36

LocalTime.millisecond: number

The millisecond component of the local time in 0-999 range.

attribute

LocalTime.microsecond

Reference - 图37

LocalTime.microsecond: number

The microsecond component of the local time in 0-999 range.

attribute

LocalTime.nanosecond

Reference - 图38

LocalTime.nanosecond: number

The nanosecond component of the local time in 0-999 range.

method

LocalTime.toString()

Reference - 图39

LocalTime.toString(): string

Get the string representation of the local_time in the HH:MM:SS 24-hour format.

method

LocalTime.toJSON()

Reference - 图40

LocalTime.toJSON(): number

Same as toString().

method

LocalTime.valueOf()

Reference - 图41

LocalTime.valueOf(): never

Always throws an Error. LocalTime objects are not comparable.

Local Date and Time​

class

LocalDateTime

Reference - 图42

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()

Reference - 图43

LocalDateTime.toString(): string

Get the string representation of the local_datetime in the YYYY-MM-DDTHH:MM:SS 24-hour format.

method

LocalDateTime.toJSON()

Reference - 图44

LocalDateTime.toJSON(): number

Same as toString().

method

LocalDateTime.valueOf()

Reference - 图45

LocalDateTime.valueOf(): never

Always throws an Error. LocalDateTime objects are not comparable.

Duration​

class

Duration

Reference - 图46

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

Reference - 图47

Duration.years: number

The number of years in the duration.

attribute

Duration.months

Reference - 图48

Duration.months: number

The number of months in the duration.

attribute

Duration.weeks

Reference - 图49

Duration.weeks: number

The number of weeks in the duration.

attribute

Duration.days

Reference - 图50

Duration.days: number

The number of days in the duration.

attribute

Duration.hours

Reference - 图51

Duration.hours: number

The number of hours in the duration.

attribute

Duration.minutes

Reference - 图52

Duration.minutes: number

The number of minutes in the duration.

attribute

Duration.seconds

Reference - 图53

Duration.seconds: number

The number of seconds in the duration.

attribute

Duration.milliseconds

Reference - 图54

Duration.milliseconds: number

The number of milliseconds in the duration.

attribute

Duration.microseconds

Reference - 图55

Duration.microseconds: number

The number of microseconds in the duration.

attribute

Duration.nanoseconds

Reference - 图56

Duration.nanoseconds: number

The number of nanoseconds in the duration.

attribute

Duration.sign

Reference - 图57

Duration.sign: number

Returns -1, 0, or 1 depending on whether the duration is negative, zero or positive.

attribute

Duration.blank

Reference - 图58

Duration.blank: boolean

Returns true if the duration is zero.

method

Duration.toString()

Reference - 图59

Duration.toString(): string

Get the string representation of the duration in ISO 8601 duration format.

method

Duration.toJSON()

Reference - 图60

Duration.toJSON(): number

Same as toString().

method

Duration.valueOf()

Reference - 图61

Duration.valueOf(): never

Always throws an Error. Duration objects are not comparable.

Memory​

class

ConfigMemory

Reference - 图62

ConfigMemory(bytes: BigInt)

A JavaScript representation of an EdgeDB cfg::memory value.

attribute

ConfigMemory.bytes

Reference - 图63

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

Reference - 图64

ConfigMemory.kibibytes: number

The memory value in kibibytes (KiB).

attribute

ConfigMemory.mebibytes

Reference - 图65

ConfigMemory.mebibytes: number

The memory value in mebibytes (MiB).

attribute

ConfigMemory.gibibytes

Reference - 图66

ConfigMemory.gibibytes: number

The memory value in gibibytes (GiB).

attribute

ConfigMemory.tebibytes

Reference - 图67

ConfigMemory.tebibytes: number

The memory value in tebibytes (TiB).

attribute

ConfigMemory.pebibytes

Reference - 图68

ConfigMemory.pebibytes: number

The memory value in pebibytes (PiB).

method

ConfigMemory.toString()

Reference - 图69

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.