AsyncIO API

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

Establish a connection to an EdgeDB server.

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 AsyncIOConnection object.

Parameters
  • dsn – Connection arguments specified using as 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.

  • hostDatabase 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".

  • portPort 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.

  • userThe 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.

  • databaseThe 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 AsyncIOConnection instance.

Example:

>>> 
import asyncio
>>> 
import edgedb
>>> 
... 
... 
async def run():
    con = await edgedb.async_connect(user='edgedeb')
    print(await con.fetchone('SELECT 1 + 1'))
...
>>> 
asyncio.get_event_loop().run_until_complete(run())
{2}
class AsyncIOConnection

A representation of a database session.

Connections are created by calling async_connect().

coroutine AsyncIOConnection.fetchall(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.

coroutine AsyncIOConnection.fetchone(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.

coroutine AsyncIOConnection.fetchall_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.

coroutine AsyncIOConnection.fetchone_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.

coroutine AsyncIOConnection.execute(query)

Execute an EdgeQL command (or commands).

Parameters

query (str) – Query text.

The commands must take no arguments.

Example:

>>> 
... 
... 
... 
... 
... 
... 
await con.execute('''
    CREATE TYPE MyType {
        CREATE PROPERTY a -> int64
    };
    FOR x IN {100, 200, 300}
    UNION INSERT MyType { a := x };
''')
method AsyncIOConnection.transaction(isolation=None, readonly=None, deferrable=None)

Create a AsyncIOTransaction object.

Parameters
  • isolation – Transaction isolation mode, can be one of: 'serializable', 'repeatable_read'. If not specified, the server-side default is used.

  • readonly – Specifies whether or not this transaction is read-only. If not specified, the server-side default is used.

  • deferrable – Specifies whether or not this transaction is deferrable. If not specified, the server-side default is used.

coroutine AsyncIOConnection.close()

Close the connection gracefully.

method AsyncIOConnection.is_closed()

Return True if the connection is closed.

The most common way to use transactions is through a context manager statement:

async with connection.transaction():
    await connection.execute("INSERT User { name := 'Don' }")

It is possible to nest transactions (a nested transaction context will create a savepoint):

async with connection.transaction():
    await connection.execute(
        'CREATE TYPE User { CREATE PROPERTY name -> str }')

    try:
        # Create a savepoint:
        async with connection.transaction():
            await connection.execute(
                "INSERT User { name := 'Don' }")
            # This nested savepoint will be
            # automatically rolled back:
            raise Exception
    except:
        # Ignore exception
        pass

    # Because the nested savepoint was rolled back, there
    # will be nothing in `User`.
    assert (await connection.fetchall('SELECT User')) == []

Alternatively, transactions can be used without an async with block:

tr = connection.transaction()
await tr.start()
try:
    ...
except:
    await tr.rollback()
    raise
else:
    await tr.commit()

See also the AsyncIOConnection.transaction() function.

class AsyncIOTransaction

Represents a transaction or savepoint block.

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

coroutine AsyncIOTransaction.start()

Enter the trasnaction or savepoint block.

coroutine AsyncIOTransaction.commit()

Exit the transaction or savepoint block and commit changes.

coroutine AsyncIOTransaction.rollback()

Exit the transaction or savepoint block and discard changes.

interface async with c:

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

function create_async_pool()

Create an asynchronous connection pool.

Parameters
  • dsn (str) – Connection arguments specified using as a single string in the following format: edgedb://user:pass@host:port/database?option=value.

  • **connect_kwargs – Keyword arguments for the async_connect() function.

  • connection_class (AsyncIOConnection) – The class to use for connections. Must be a subclass of AsyncIOConnection.

  • min_size (int) – Number of connection the pool will be initialized with.

  • max_size (int) – Max number of connections in the pool.

  • on_acquire – A coroutine to prepare a connection right before it is returned from Pool.acquire().

  • on_release – A coroutine called when a connection is about to be released to the pool.

  • on_connect – A coroutine to initialize a connection when it is created.

Returns

An instance of AsyncIOPool.

Can be used either with an async with block:

async with edgedb.create_pool(user='edgedb') as pool:
    async with pool.acquire() as con:
        await con.fetchall('SELECT {1, 2, 3}')

Or directly with await:

pool = await edgedb.create_pool(user='edgedb')
con = await pool.acquire()
try:
    await con.fetchall('SELECT {1, 2, 3}')
finally:
    await pool.release(con)
class AsyncIOPool

A connection pool.

Connection pool can be used to manage a set of connections to the database. Connections are first acquired from the pool, then used, and then released back to the pool. Once a connection is released, it’s reset to close all open cursors and other resources except prepared statements.

Pools are created by calling create_async_pool().

coroutine AsyncIOPool.acquire()

Acquire a database connection from the pool.

Returns

An instance of AsyncIOConnection.

Can be used in an await expression or with an async with block.

async with pool.acquire() as con:
    await con.execute(...)

Or:

con = await pool.acquire()
try:
    await con.execute(...)
finally:
    await pool.release(con)
coroutine AsyncIOPool.release(connection)

Release a database connection back to the pool.

Parameters

connection (AsyncIOConnection) – A AsyncIOConnection object to release.

coroutine AsyncIOPool.close()

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 cancellation) occurs in close() the pool will terminate by calling Pool.terminate().

It is advisable to use asyncio.wait_for() to set a timeout.

method AsyncIOPool.terminate()

Terminate all connections in the pool.

coroutine AsyncIOPool.expire_connections()

Expire all currently open connections.

Cause all currently open connections to get replaced on the next acquire() call.

method AsyncIOPool.set_connect_args(dsn=None, **connect_kwargs)

Set the new connection arguments for this pool.

Parameters
  • dsn (str) – Connection arguments specified using as a single string in the following format: edgedb://user:pass@host:port/database?option=value.

  • **connect_kwargs – Keyword arguments for the async_connect() function.

The new connection arguments will be used for all subsequent new connection attempts. Existing connections will remain until they expire. Use Pool.expire_connections() to expedite the connection expiry.