Blocking API

Client

function

create_client()

Blocking API - 图1

Blocking API - 图2

Blocking API - 图3

create_client(dsn = None, *, host = None, port = None, user = None, password = None, database = None, timeout = 60, concurrency = None)

Create a blocking client with a lazy connection pool.

The connection parameters may be specified either as a connection URI in dsn, or as specific keyword arguments, or both. If both dsn and keyword arguments are specified, the latter override the corresponding values parsed from the connection URI.

If no connection parameter is specified, the client will try to search in environment variables and then the current project, see Client Library Connection docs for more information.

Returns a new Client object.

Parameters

  • dsn – If this parameter does not start with edgedb:// then this is interpreted as the name of a local instance.Otherwise it specifies a single string in the following format: edgedb://user:password@host:port/database?option=value. The following options are recognized: host, port, user, database, password. For a complete reference on DSN, see the DSN Specification.

  • host – Database host address as one of the following:

    • an IP address or a domain name;
    • an absolute path to the directory containing the database server Unix-domain socket (not supported on Windows);
    • a sequence of any of the above, in which case the addresses will be tried in order, and the host of the first successful connection will be used for the whole connection pool.

    If not specified, the following will be tried, in order:

    • host address(es) parsed from the dsn argument,
    • the value of the EDGEDB_HOST environment variable,
    • on Unix, common directories used for EdgeDB Unix-domain sockets: "/run/edgedb" and "/var/run/edgedb",
    • "localhost".
  • port – Port number to connect to at the server host (or Unix-domain socket file extension). If multiple host addresses were specified, this parameter may specify a sequence of port numbers of the same length as the host sequence, or it may specify a single port number to be used for all host addresses.If not specified, the value parsed from the dsn argument is used, or the value of the EDGEDB_PORT environment variable, or 5656 if neither is specified.

  • user – The name of the database role used for authentication.If not specified, the value parsed from the dsn argument is used, or the value of the EDGEDB_USER environment variable, or the operating system name of the user running the application.

  • database – The name of the database to connect to.If not specified, the value parsed from the dsn argument is used, or the value of the EDGEDB_DATABASE environment variable, or the operating system name of the user running the application.

  • password – Password to be used for authentication, if the server requires one. If not specified, the value parsed from the dsn argument is used, or the value of the EDGEDB_PASSWORD environment variable. Note that the use of the environment variable is discouraged as other users and applications may be able to read it without needing specific privileges.

  • timeout (float) – Connection timeout in seconds.

Returns

An instance of Client.

The APIs on the returned client instance can be safely used by different threads, because under the hood they are checking out different connections from the pool to run the queries:

  1. client = edgedb.create_client()
  2. client.query('SELECT {1, 2, 3}')

The same for transactions:

  1. client = edgedb.create_client()
  2. for tx in client.transaction():
  3. with tx:
  4. tx.query('SELECT {1, 2, 3}')

class

Client

Blocking API - 图4

Blocking API - 图5

Blocking API - 图6

A thread-safe blocking client with a connection pool.

Blocking clients are created by calling create_client().

method

Client.query()

Blocking API - 图7

Blocking API - 图8

Blocking API - 图9

Client.query(query, * args, ** kwargs)

Acquire a connection and use it to run a query and return the results as an edgedb.Set instance. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

An instance of edgedb.Set containing the query result.

Note that positional and named query arguments cannot be mixed.

method

Client.query_single()

Blocking API - 图10

Blocking API - 图11

Blocking API - 图12

Client.query_single(query, * args, ** kwargs)

Acquire a connection and use it to run an optional singleton-returning query and return its element. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result.

The query must return no more than one element. If the query returns more than one element, an edgedb.ResultCardinalityMismatchError is raised, if it returns an empty set, None is returned.

Note, that positional and named query arguments cannot be mixed.

method

Client.query_required_single()

Blocking API - 图13

Blocking API - 图14

Blocking API - 图15

Client.query_required_single(query, * args, ** kwargs)

Acquire a connection and use it to run a singleton-returning query and return its element. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result.

The query must return exactly one element. If the query returns more than one element, an edgedb.ResultCardinalityMismatchError is raised, if it returns an empty set, an edgedb.NoDataError is raised.

Note, that positional and named query arguments cannot be mixed.

method

Client.query_json()

Blocking API - 图16

Blocking API - 图17

Blocking API - 图18

Client.query_json(query, * args, ** kwargs)

Acquire a connection and use it to run a query and return the results as JSON. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

A JSON string containing an array of query results.

Note, that positional and named query arguments cannot be mixed.

Caution is advised when reading decimal values using this method. The JSON specification does not have a limit on significant digits, so a decimal number can be losslessly represented in JSON. However, the default JSON decoder in Python will read all such numbers as float values, which may result in errors or 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 Decimal.

method

Client.query_single_json()

Blocking API - 图19

Blocking API - 图20

Blocking API - 图21

Client.query_single_json(query, * args, ** kwargs)

Acquire a connection and use it to run an optional singleton-returning query and return its element in JSON. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result encoded in JSON.

The query must return no more than one element. If the query returns more than one element, an edgedb.ResultCardinalityMismatchError is raised, if it returns an empty set, "null" is returned.

Note, that positional and named query arguments cannot be mixed.

Caution is advised when reading decimal values using this method. The JSON specification does not have a limit on significant digits, so a decimal number can be losslessly represented in JSON. However, the default JSON decoder in Python will read all such numbers as float values, which may result in errors or 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 Decimal.

method

Client.query_required_single_json()

Blocking API - 图22

Blocking API - 图23

Blocking API - 图24

Client.query_required_single_json(query, * args, ** kwargs)

Acquire a connection and use it to run a singleton-returning query and return its element in JSON. The temporary connection is automatically returned back to the pool.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result encoded in JSON.

The query must return exactly one element. If the query returns more than one element, an edgedb.ResultCardinalityMismatchError is raised, if it returns an empty set, an edgedb.NoDataError is raised.

Note, that positional and named query arguments cannot be mixed.

Caution is advised when reading decimal values using this method. The JSON specification does not have a limit on significant digits, so a decimal number can be losslessly represented in JSON. However, the default JSON decoder in Python will read all such numbers as float values, which may result in errors or 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 Decimal.

method

Client.execute()

Blocking API - 图25

Blocking API - 图26

Blocking API - 图27

Client.execute(query)

Acquire a connection and use it to execute an EdgeQL command (or commands). The temporary connection is automatically returned back to the pool.

Parameters

query (str) – Query text.

The commands must take no arguments.

Example:

  1. >>>
  2. ...
  3. ...
  4. ...
  5. ...
  6. ...
  7. ...
  1. 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. ''')

If the results of query are desired, query(), query_single() or query_required_single() should be used instead.

method

Client.transaction()

Blocking API - 图28

Blocking API - 图29

Blocking API - 图30

Open a retryable transaction loop.

This is the preferred method of initiating and running a database transaction in a robust fashion. The transaction() transaction loop will attempt to re-execute the transaction loop body if a transient error occurs, such as a network error or a transaction serialization error.

Returns an instance of Retry.

See Transactions for more details.

Example:

  1. for tx in client.transaction():
  2. with tx:
  3. value = tx.query_single("SELECT Counter.value")
  4. tx.execute(
  5. "UPDATE Counter SET { value := <int64>$value }",
  6. value=value + 1,
  7. )

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

The transaction starts lazily. A connection is only acquired from the pool when the first query is issued on the transaction instance.

method

Client.close()

Blocking API - 图31

Blocking API - 图32

Blocking API - 图33

Client.close(timeout = None)

Attempt to gracefully close all connections in the pool.

Wait until all pool connections are released, close them and shut down the pool. If any error (including timeout) occurs in close() the pool will terminate by calling terminate().

Parameters

timeout (float) – Seconds to wait, None for wait forever.

method

Client.terminate()

Blocking API - 图34

Blocking API - 图35

Blocking API - 图36

Terminate all connections in the pool.

method

Client.ensure_connected()

Blocking API - 图37

Blocking API - 图38

Blocking API - 图39

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 on a client. ensureConnected can be useful to catch any errors resulting from connection mis-configuration by triggering the first connection attempt explicitly.

method

Client.with_transaction_options()

Blocking API - 图40

Blocking API - 图41

Blocking API - 图42

Client.with_transaction_options(options = None)

Returns a shallow copy of the client with adjusted transaction options.

Parameters

options (TransactionOptions) – Object that encapsulates transaction options.

See Transaction Options for details.

method

Client.with_retry_options()

Blocking API - 图43

Blocking API - 图44

Blocking API - 图45

Client.with_retry_options(options = None)

Returns a shallow copy of the client with adjusted retry options.

Parameters

options (RetryOptions) – Object that encapsulates retry options.

See Retry Options for details.

method

Client.with_state()

Blocking API - 图46

Blocking API - 图47

Blocking API - 图48

Client.with_state(state)

Returns a shallow copy of the client with adjusted state.

Parameters

state (State) – Object that encapsulates state.

See State for details.

method

Client.with_default_module()

Blocking API - 图49

Blocking API - 图50

Blocking API - 图51

Client.with_default_module(module = None)

Returns a shallow copy of the client with adjusted default module.

This is equivalent to using the set module command, or using the reset module command when giving None.

Parameters

module (str or None) – Adjust the default module.

See State.with_default_module() for details.

method

Client.with_module_aliases()

Blocking API - 图52

Blocking API - 图53

Blocking API - 图54

Client.with_module_aliases(aliases_dict = None, /, ** aliases)

Returns a shallow copy of the client with adjusted module aliases.

This is equivalent to using the set alias command.

Parameters

  • aliases_dict (dict[str, str] or None) – This is an optional positional-only argument.

  • aliases (dict[str, str]) – Adjust the module aliases after applying aliases_dict if set.

See State.with_module_aliases() for details.

method

Client.without_module_aliases()

Blocking API - 图55

Blocking API - 图56

Blocking API - 图57

Client.without_module_aliases(* aliases)

Returns a shallow copy of the client without specified module aliases.

This is equivalent to using the reset alias command.

Parameters

aliases (tuple[str]) – Module aliases to reset.

See State.without_module_aliases() for details.

method

Client.with_config()

Blocking API - 图58

Blocking API - 图59

Blocking API - 图60

Client.with_config(config_dict = None, /, ** config)

Returns a shallow copy of the client with adjusted session config.

This is equivalent to using the configure session set command.

Parameters

  • config_dict (dict[str, object] or None) – This is an optional positional-only argument.

  • config (dict[str, object]) – Adjust the config settings after applying config_dict if set.

See State.with_config() for details.

method

Client.without_config()

Blocking API - 图61

Blocking API - 图62

Blocking API - 图63

Client.without_config(* config_names)

Returns a shallow copy of the client without specified session config.

This is equivalent to using the configure session reset command.

Parameters

config_names (tuple[str]) – Config to reset.

See State.without_config() for details.

method

Client.with_globals()

Blocking API - 图64

Blocking API - 图65

Blocking API - 图66

Client.with_globals(globals_dict = None, /, ** globals_)

Returns a shallow copy of the client with adjusted global values.

This is equivalent to using the set global command.

Parameters

  • globals_dict (dict[str, object] or None) – This is an optional positional-only argument.

  • globals (dict[str, object]) – Adjust the global values after applying globals_dict if set.

See State.with_globals() for details.

method

Client.without_globals()

Blocking API - 图67

Blocking API - 图68

Blocking API - 图69

Client.without_globals(* global_names)

Returns a shallow copy of the client without specified globals.

This is equivalent to using the reset global command.

Parameters

global_names (tuple[str]) – Globals to reset.

See State.without_globals() for details.

Transactions

The most robust way to execute transactional code is to use the transaction() loop API:

  1. for tx in client.transaction():
  2. with tx:
  3. tx.execute("INSERT User { name := 'Don' }")

Note that we execute queries on the tx object in the above example, rather than on the original client object.

The tx object stores a connection acquired from the pool, so that all queries can be executed on the same connection in the same transaction. Transaction start is lazy. for tx or with tx won’t acquire the connection and start the transaction. It’s only done when executing the first query on the tx object. That connection is pinned to the tx object even when a reconnection is needed, until leaving the final with transaction block.

The transaction() API guarantees that:

  1. Transactions are executed atomically;

  2. If a transaction is failed for any of the number of transient errors (i.e. a network failure or a concurrent update error), the transaction would be retried;

  3. If any other, non-retryable exception occurs, the transaction is rolled back, and the exception is propagated, immediately aborting the transaction() block.

The key implication of retrying transactions is that the entire nested code block can be re-run, including any non-querying Python code. Here is an example:

  1. for tx in client.transaction():
  2. with tx:
  3. user = tx.query_single(
  4. "SELECT User { email } FILTER .login = <str>$login",
  5. login=login,
  6. )
  7. data = httpclient.get(
  8. 'https://service.local/email_info',
  9. params=dict(email=user.email),
  10. )
  11. user = tx.query_single('''
  12. UPDATE User FILTER .login = <str>$login
  13. SET { email_info := <json>$data}
  14. ''',
  15. login=login,
  16. data=data,
  17. )

In the above example, the execution of the HTTP request would be retried too. The core of the issue is that whenever transaction is interrupted user might have the email changed (as the result of concurrent transaction), so we have to redo all the work done.

Generally it’s recommended to not execute any long running code within the transaction unless absolutely necessary.

Transactions allocate expensive server resources and having too many concurrently running long-running transactions will negatively impact the performance of the DB server.

To rollback a transaction that is in progress raise an exception.

  1. class RollBack(Exception):
  2. "A user defined exception."
  3. try:
  4. for tx in client.transaction():
  5. with tx:
  6. raise RollBack
  7. except RollBack:
  8. pass

See also:

class

Transaction

Blocking API - 图70

Blocking API - 图71

Blocking API - 图72

Represents a transaction.

Instances of this type are yielded by a Retry iterator.

interface

with c:

Blocking API - 图73

Blocking API - 图74

Blocking API - 图75

start and commit/rollback the transaction automatically when entering and exiting the code inside the context manager block.

method

Transaction.query()

Blocking API - 图76

Blocking API - 图77

Blocking API - 图78

Transaction.query(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run a query and return the results as an edgedb.Set instance. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query() for details.

method

Transaction.query_single()

Blocking API - 图79

Blocking API - 图80

Blocking API - 图81

Transaction.query_single(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run an optional singleton-returning query and return its element. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query_single() for details.

method

Transaction.query_required_single()

Blocking API - 图82

Blocking API - 图83

Blocking API - 图84

Transaction.query_required_single(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run a singleton-returning query and return its element. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query_required_single() for details.

method

Transaction.query_json()

Blocking API - 图85

Blocking API - 图86

Blocking API - 图87

Transaction.query_json(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run a query and return the results as JSON. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query_json() for details.

method

Transaction.query_single_json()

Blocking API - 图88

Blocking API - 图89

Blocking API - 图90

Transaction.query_single_json(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run an optional singleton-returning query and return its element in JSON. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query_single_json() for details.

method

Transaction.query_required_single_json()

Blocking API - 图91

Blocking API - 图92

Blocking API - 图93

Transaction.query_required_single_json(query, * args, ** kwargs)

Acquire a connection if the current transaction doesn’t have one yet, and use it to run a singleton-returning query and return its element in JSON. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.query_requried_single_json() for details.

method

Transaction.execute()

Blocking API - 图94

Blocking API - 图95

Blocking API - 图96

Transaction.execute(query)

Acquire a connection if the current transaction doesn’t have one yet, and use it to execute an EdgeQL command (or commands). The temporary connection is automatically returned back to the pool when exiting the transaction block.

See Client.execute() for details.

class

Retry

Blocking API - 图97

Blocking API - 图98

Blocking API - 图99

Represents a wrapper that yields Transaction object when iterating.

See Client.transaction() method for an example.

method

Retry.__next__()

Blocking API - 图100

Blocking API - 图101

Blocking API - 图102

Yields Transaction object every time transaction has to be repeated.