Blocking API​

Connection​

function

connect()

Blocking API - 图1

connect(dsn = None, *, host = None, port = None, admin = None, user = None, password = None, database = None, timeout = 60)

Establish a connection to an EdgeDB server.

Parameters

  • dsn – If this parameter does not start with edgedb:// then this 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. The following options are recognized: host, port, user, database, password.

  • 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 first successful connection will be returned.

    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 EDGEB_PORT environment variable, or 5656 if neither is specified.

  • admin – If True, try to connect to the special administration socket.

  • 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

A BlockingIOConnection instance.

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.

Returns a new BlockingIOConnection object.

Example:

  1. >>>
  1. import edgedb
  1. >>>
  1. con = edgedb.connect(user='edgedeb')
  1. >>>
  1. con.query_single('SELECT 1 + 1')
  1. {2}

class

BlockingIOConnection

Blocking API - 图2

A representation of a database session.

Connections are created by calling connect().

method

BlockingIOConnection.query()

Blocking API - 图3

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

Run a query and return the results as a edgedb.Set instance.

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

BlockingIOConnection.query_single()

Blocking API - 图4

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

Run an optional singleton-returning query and return its element.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result.

The query must return at most 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

BlockingIOConnection.query_required_single()

Blocking API - 图5

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

Run a singleton-returning query and return its element.

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

BlockingIOConnection.query_json()

Blocking API - 图6

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

Run a query and return the results as JSON.

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

BlockingIOConnection.query_single_json()

Blocking API - 图7

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

Run an optional singleton-returning query and return its element in JSON.

Parameters

  • query (str) – Query text.

  • args – Positional query arguments.

  • kwargs – Named query arguments.

Returns

Query result encoded in JSON.

The query must return at most 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

BlockingIOConnection.query_required_single_json()

Blocking API - 图8

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

Run a singleton-returning query and return its element in JSON.

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

BlockingIOConnection.execute()

Blocking API - 图9

BlockingIOConnection.execute(query)

Execute an EdgeQL command (or commands).

Parameters

query (str) – Query text.

The commands must take no arguments.

Example:

  1. >>>
  2. ...
  3. ...
  4. ...
  5. ...
  6. ...
  7. ...
  1. con.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_required_single() or query_single() should be used instead.

method

BlockingIOConnection.transaction()

Blocking API - 图10

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 con.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.

method

BlockingIOConnection.raw_transaction()

Blocking API - 图11

Deprecated. Use transaction() along with with_retry_options(RetryOptions(attempts=1)) instead.

Execute a non-retryable transaction.

Contrary to transaction(), raw_transaction() will not attempt to re-run the nested code block in case a retryable error happens.

This is a low-level API and it is advised to use the transaction() method instead.

A call to raw_transaction() returns AsyncIOTransaction.

Example:

  1. with con.raw_transaction() as tx:
  2. value = tx.query_single("SELECT Counter.value")
  3. tx.execute(
  4. "UPDATE Counter SET { value := <int64>$value }",
  5. value=value + 1,
  6. )

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

method

BlockingIOConnection.close()

Blocking API - 图12

Close the connection gracefully.

method

BlockingIOConnection.is_closed()

Blocking API - 图13

Return True if the connection is closed.

Transactions​

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

  1. for tx in con.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 connection con object.

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 con.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.

See also:

class

Transaction

Blocking API - 图14

Represents a transaction or savepoint block.

Transactions are created by calling the BlockingIOConnection.transaction() method.

method

Transaction.start()

Blocking API - 图15

Enter the transaction or savepoint block.

method

Transaction.commit()

Blocking API - 图16

Exit the transaction or savepoint block and commit changes.

method

Transaction.rollback()

Blocking API - 图17

Exit the transaction or savepoint block and discard changes.

interface

with c:

Blocking API - 图18

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

class

Retry

Blocking API - 图19

Represents a wrapper that yields Transaction object when iterating.

See BlockingIOConnection.transaction() method for an example.

coroutine

Retry.__next__()

Blocking API - 图20

Yields Transaction object every time transaction has to be repeated.