# Client

The `gel.Client` class implements the basic functionality required to establish a pool of connections to your database, execute queries with some context and parameters, manage transactions, and decode results into Python types.

We provide both a [blocking](https://docs.geldata.com/reference/using/python/client.md#gel-python-blocking-api-client) and an [asyncio](https://docs.geldata.com/reference/using/python/client.md#gel-python-async-api-client) implementation of the client. For the following examples we will use the [asyncio](https://docs.geldata.com/reference/using/python/client.md#gel-python-async-api-client) implementation, but the blocking API is fundamentally identical.

## Creating a client

The `gel` package exposes a [`create_async_client()`](https://docs.geldata.com/reference/using/python/client.md#gel.create_async_client) function that can be used to create a new [`AsyncIOClient`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient) instance. This client instance manages a pool of connections to the database which it discovers automatically from either being in a `gel project init` directory or being provided connection details via Environment Variables. See [the environment section of the connection reference](https://docs.geldata.com/reference/using/connection.md#ref-reference-connection-environments) for more details and options.

> Note: If you're using Gel Cloud to host your development instance, you can use the `gel cloud login` command to authenticate with Gel Cloud and then use the `gel project init --server-instance <instance-name>` command to create a local project-linked instance that is linked to an Gel Cloud instance. For more details, see [the Gel Cloud guide](https://docs.geldata.com/cloud.md#ref-guide-cloud).

```python
import asyncio
import gel

client = gel.create_async_client()
```

### Checking connection status

The client maintains a dynamically sized *pool* of connections under the hood. These connections are initialized *lazily*, so no connection will be established until the first time you execute a query.

If you want to explicitly ensure that the client is connected without running a query, use the `.ensure_connected()` method. This can be useful to catch any errors resulting from connection mis-configuration by triggering the first connection attempt explicitly.

```python
import asyncio
import gel

client = gel.create_async_client()

async def main():
  await client.ensure_connected()
```

## Running queries

The `gel.Client` class provides a number of methods for running queries. The simplest is `query`, which runs a query and returns the result as a list of results.

```python
import asyncio
import gel

client = gel.create_async_client()

async def main():
  await client.ensure_connected()
  result = await client.query("select 2 + 2;")
  print(result)

asyncio.run(main())

# Output:
# [4]
```

### Parameters

If your query contains parameters (e.g. `$foo`), you can pass in values. Positional parameters are passed as positional arguments, and named parameters are passed as keyword arguments. You cannot mix positional and named parameters in the same query.

```python
import asyncio
import gel

client = gel.create_async_client()

async def main():
  await client.ensure_connected()
  result = await client.query("select 2 + $addend;", addend=2)
  print(result)

asyncio.run(main())

# Output:
# [4]
```

> Note: Parameters can only be scalars or arrays of scalars. See [parameters](https://docs.geldata.com/reference/edgeql/parameters.md#ref-eql-params) for more details.

### Cardinality

The `query` method always returns a list of results. It places no constraints on cardinality.

```python
await client.query("select 2 + 2;") # list[int64]: [4]
await client.query("select <int64>{};") # list[int64]: []
await client.query("select {1, 2, 3};") # list[int64]: [1, 2, 3]
```

If you know your query will only return a single element, you can tell Gel to expect a *singleton result* by using the `query_single` method. This is intended for queries that return *zero or one* elements. If the query returns a set with more than one elements, the `Client` will raise a runtime error.

> Note: Remember that arrays and tuples are considered an element of the result set, so if you're returning exactly one array or tuple, the result will be an array.

```python
await client.query_single("select 2 + 2;") # int64 | None: 4
await client.query_single("select [1, 2, 3];") # list[int64] | None: [1, 2, 3]
await client.query_single("select <int64>{};") # int64 | None: None
await client.query_single("select {1, 2, 3};") # Raises a ResultCardinalityMismatchError
```

Use `query_required_single` for queries that return *exactly one* element. If the query returns an empty set or a set with multiple elements, the `Client` will raise a runtime error.

```python
await client.query_required_single("select 2 + 2;") # int64: 4
await client.query_required_single("select <int64>{};") # Raises a NoDataError
await client.query_required_single("select {1, 2, 3};") # Raises a ResultCardinalityMismatchError
```

If you do not need or expect a result, you can use `execute` which will return `None`. This is often useful for mutations where you do not need to retrieve a result.

```python
await client.execute("insert Movie { title := 'Iron Man' }") # None
```

### JSON results

The `Client` provides additional methods for running queries and retrieving results as a *serialized JSON string*. This serialization happens inside the database and is typically more performant than running `JSON.stringify` yourself.

```python
await client.query_json("select 2 + 2;")
# "[4]"

await client.query_single_json("select <int64>{};")
# "null"

await client.query_required_single_json("select 3.14;")
# "3.14"

await client.query_required_json("select 3.14;")
# "3.14"
```

> Warning: 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`.

### SQL queries

The `querySQL` method allows you to run a SQL query and return the result as list of dictionaries.

```python
await client.query_sql("select 2 + 2;")
# [{'col~1': 4}]

await client.query_sql("select 42 as a;")
# [{'a': 42}]
```

### Scripts

Both `execute` and the `query*` methods support scripts (queries containing multiple statements). The statements, like all queries, are run in an implicit transaction (unless already in an explicit transaction), so the whole script remains atomic. For the `query*` methods only the result of the final statement in the script will be returned.

```python
result = await client.query("""
  insert Movie { title := 'Iron Man' };
  insert Person { name := 'Robert Downey Jr.' };
""")
print(result)
# [{"id": "00000000-0000-0000-0000-000000000000"}]
```

For more fine grained control of atomic exectution of multiple statements, use the [`transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.transaction) API.

### Transactions

We execute queries on the `tx` object given in for expression, rather than on the original `client` object.

```python
async for tx in client.transaction():
    async with tx:
        await tx.execute("insert Movie { title := 'Iron Man' }")
        await tx.execute("insert Person { name := 'Robert Downey Jr.' }")
```

The `transaction()` API guarantees that:

1. Transactions are executed atomically;
2. If a transaction fails due to retryable error (like a network failure or a concurrent update error), the transaction would be retried;
3. If any other, non-retryable error occurs, the transaction is rolled back and the `transaction()` block throws.

The transaction object exposes the same `query` and `execute` methods as the `Client` object, with the only difference that queries will run within the current transaction and can be retried automatically.

> Warning: In transactions, the entire nested code block can be re-run, including any non-querying Python code. In general, the code inside the transaction block **should not have side effects or run for a significant amount of time**. Consider the following example:
> 
> - Don't do this:
>   ```python
>     email = "timmy@example.com";
>   
>     async for tx in client.transaction():
>         async with tx:
>             await tx.execute(
>                 'insert User { email := <str>$email }',
>                 email=email,
>             )
>   
>             await sendWelcomeEmail(email)
>   
>             await tx.execute(
>                 """
>                 insert LoginHistory {
>                   user := (select User filter .email = <str>$email),
>                   timestamp := datetime_current()
>                 }
>                 """,
>                 email=email
>             )
>   ```
> 
> In the above example, the welcome email may be sent multiple times if the transaction block is retried. Additionally, transactions allocate expensive server resources. 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.

```python
class RollBack(Exception):
    "A user defined exception."

try:
    for tx in client.transaction():
        with tx:
            raise RollBack
except RollBack:
    pass
```

See also:

- [RFC1004](https://github.com/gel/rfcs/blob/master/text/1004-transactions-api.rst)
- [`Client.transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.transaction)

## Configuring clients

Clients can be configured using a set of methods that start with `with`. One you'll likely use often in application code is the `with_globals` which sets the global variables in the query.

```python
client = gel.create_async_client()
await client.with_globals(
    current_user_id="00000000-0000-0000-0000-000000000000",
).query_single(
    "select User { * } filter .id ?= global current_user_id;"
)
```

> Note: These methods return a *new Client instance* that *shares a connection pool* with the original client. This is important. Each call to `create_async_client` instantiates a new connection pool, so in typical usage you should create a single shared client instance and configure it at runtime as needed.

## Blocking client reference

### Client

## Function: create_client()

```py
create_client(dsn = None, *, host = None, port = None, user = None, password = None, secret_key = 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](https://docs.geldata.com/reference/using/connection.md#gel-client-connection) docs for more information.

Returns a new [`Client`](https://docs.geldata.com/reference/using/python/client.md#gel.Client) object.

##### Parameters

- **dsn** – If this parameter does not start with `gel://` then this is interpreted as the [name of a local instance](https://docs.geldata.com/reference/using/connection.md#ref-reference-connection-instance-name).
  
  Otherwise it specifies a single string in the following format: `gel://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](https://docs.geldata.com/reference/using/connection.md#ref-dsn).

- **host** – Database host address as an IP address or a domain name;
  
  If not specified, the following will be tried, in order:
  
  - host address(es) parsed from the *dsn* argument,
  - the value of the `GEL_HOST` environment variable,
  - `"localhost"`.

- **port** – Port number to connect to at the server host. 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 `GEL_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 `GEL_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 `GEL_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 `GEL_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.

- **secret_key** – Secret key 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 `GEL_SECRET_KEY` 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*](https://docs.python.org/3/library/functions.html#float)) – Connection timeout in seconds.




##### Returns

An instance of [`Client`](https://docs.geldata.com/reference/using/python/client.md#gel.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:

- [`Client.query()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query)
- [`Client.query_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_single)
- [`Client.query_required_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_required_single)
- [`Client.query_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_json)
- [`Client.query_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_single_json)
- [`Client.query_required_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_required_single_json)
- [`Client.execute()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.execute)
- [`Client.transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.transaction)

```python
client = gel.create_client()
client.query('SELECT {1, 2, 3}')
```

The same for transactions:

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


## Class: Client

```py
Client
```

A thread-safe blocking client with a connection pool.

Blocking clients are created by calling [`create_client()`](https://docs.geldata.com/reference/using/python/client.md#gel.create_client).

## Method: Client.query()

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

Acquire a connection and use it to run a query and return the results as an [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) instance. The temporary connection is automatically returned back to the pool.

##### Parameters

- **query** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Query text.
- **args** – Positional query arguments.
- **kwargs** – Named query arguments.




##### Returns

An instance of [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) containing the query result.





Note that positional and named query arguments cannot be mixed.


## Method: Client.query_single()

```py
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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.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()

```py
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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, an `gel.NoDataError` is raised.

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


## Method: Client.query_json()

```py
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*](https://docs.python.org/3/library/stdtypes.html#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.

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

```py
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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, `"null"` is returned.

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

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

```py
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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, an `gel.NoDataError` is raised.

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

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

```py
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*](https://docs.python.org/3/library/stdtypes.html#str)) – Query text.





The commands must take no arguments.

Example:

```pycon
>>> client.execute('''
...     CREATE TYPE MyType {
...         CREATE PROPERTY a -> int64
...     };
...     FOR x IN {100, 200, 300}
...     UNION INSERT MyType { a := x };
... ''')
```

> Note: If the results of *query* are desired, [`query()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query), [`query_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_single) or [`query_required_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_required_single) should be used instead.


## Method: Client.transaction()

```py
Client.transaction()
```

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`](https://docs.geldata.com/reference/using/python/client.md#gel.Retry).

See [Transactions](https://docs.geldata.com/reference/using/python/client.md#gel-python-blocking-api-transaction) for more details.

Example:

```python
for tx in client.transaction():
    with tx:
        value = tx.query_single("SELECT Counter.value")
        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 connection.

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

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.terminate).

##### Parameters

**timeout** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Seconds to wait, `None` for wait forever.






## Method: Client.terminate()

```py
Client.terminate()
```

Terminate all connections in the pool.


## Method: Client.ensure_connected()

```py
Client.ensure_connected()
```

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

```py
Client.with_transaction_options(options = None)
```

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

##### Parameters

**options** ([*TransactionOptions*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.TransactionOptions)) – Object that encapsulates transaction options.





See [Transaction Options](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-transaction-options) for details.


## Method: Client.with_retry_options()

```py
Client.with_retry_options(options = None)
```

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

##### Parameters

**options** ([*RetryOptions*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.RetryOptions)) – Object that encapsulates retry options.





See [Retry Options](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-retry-options) for details.


## Method: Client.with_state()

```py
Client.with_state(state)
```

Returns a shallow copy of the client with adjusted state.

##### Parameters

**state** ([*State*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State)) – Object that encapsulates state.





See [State](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-state) for details.


## Method: Client.with_default_module()

```py
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*](https://docs.python.org/3/library/stdtypes.html#str)* or *[*None*](https://docs.python.org/3/library/constants.html#None)) – Adjust the *default module*.





See [`State.with_default_module()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_default_module) for details.


## Method: Client.with_module_aliases()

```py
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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*str*](https://docs.python.org/3/library/stdtypes.html#str)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **aliases** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Adjust the module aliases after applying `aliases_dict` if set.






See [`State.with_module_aliases()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_module_aliases) for details.


## Method: Client.without_module_aliases()

```py
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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Module aliases to reset.





See [`State.without_module_aliases()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_module_aliases) for details.


## Method: Client.with_config()

```py
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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*]*) – Adjust the config settings after applying `config_dict` if set.






See [`State.with_config()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_config) for details.


## Method: Client.without_config()

```py
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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Config to reset.





See [`State.without_config()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_config) for details.


## Method: Client.with_globals()

```py
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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **globals** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*]*) – Adjust the global values after applying `globals_dict` if set.






See [`State.with_globals()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_globals) for details.


## Method: Client.without_globals()

```py
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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Globals to reset.





See [`State.without_globals()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_globals) for details.



### Transactions

## Class: Transaction

```py
Transaction
```

Represents a transaction.

Instances of this type are yielded by a [`Retry`](https://docs.geldata.com/reference/using/python/client.md#gel.Retry) iterator.

## Describe: with c:

```
with c:
```

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


## Method: Transaction.query()

```py
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 [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) instance. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See [`Client.query()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query) for details.


## Method: Transaction.query_single()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_single) for details.


## Method: Transaction.query_required_single()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_required_single) for details.


## Method: Transaction.query_json()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_json) for details.


## Method: Transaction.query_single_json()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_single_json) for details.


## Method: Transaction.query_required_single_json()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.query_required_single_json) for details.


## Method: Transaction.execute()

```py
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()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.execute) for details.



## Class: Retry

```py
Retry
```

Represents a wrapper that yields [`Transaction`](https://docs.geldata.com/reference/using/python/client.md#gel.Transaction) object when iterating.

See [`Client.transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.Client.transaction) method for an example.

## Method: Retry.__next__()

```py
Retry.__next__()
```

Yields [`Transaction`](https://docs.geldata.com/reference/using/python/client.md#gel.Transaction) object every time transaction has to be repeated.



## AsyncIO client reference

### Client

## Function: create_async_client()

```py
create_async_client(dsn = None, *, host = None, port = None, user = None, password = None, secret_key = None, database = None, timeout = 60, concurrency = None)
```

Create an asynchronous 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](https://docs.geldata.com/reference/using/connection.md#gel-client-connection) docs for more information.

Returns a new [`AsyncIOClient`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient) object.

##### Parameters

- **dsn** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – If this parameter does not start with `gel://` then this is interpreted as the [name of a local instance](https://docs.geldata.com/reference/using/connection.md#ref-reference-connection-instance-name).
  
  Otherwise it specifies a single string in the following format: `gel://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](https://docs.geldata.com/reference/using/connection.md#ref-dsn).

- **host** – Database host address as an IP address or a domain name;
  
  If not specified, the following will be tried, in order:
  
  - host address(es) parsed from the *dsn* argument,
  - the value of the `GEL_HOST` environment variable,
  - `"localhost"`.

- **port** – Port number to connect to at the server host. 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 `GEL_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 `GEL_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 `GEL_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 `GEL_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.

- **secret_key** – Secret key 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 `GEL_SECRET_KEY` 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*](https://docs.python.org/3/library/functions.html#float)) – Connection timeout in seconds.
- **concurrency** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Max number of connections in the pool. If not set, the suggested concurrency value provided by the server is used.





##### Returns

An instance of [`AsyncIOClient`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient).





The APIs on the returned client instance can be safely used by different [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task)/coroutines, because under the hood they are checking out different connections from the pool to run the queries:

- [`AsyncIOClient.query()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query)
- [`AsyncIOClient.query_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_single)
- [`AsyncIOClient.query_required_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_required_single)
- [`AsyncIOClient.query_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_json)
- [`AsyncIOClient.query_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_single_json)
- [`AsyncIOClient.query_required_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_required_single_json)

- [`AsyncIOClient.execute()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.execute)
- [`AsyncIOClient.transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.transaction)

```python
client = gel.create_async_client()
await client.query('SELECT {1, 2, 3}')
```

The same for transactions:

```python
client = gel.create_async_client()
async for tx in client.transaction():
    async with tx:
        await tx.query('SELECT {1, 2, 3}')
```


## Class: AsyncIOClient

```py
AsyncIOClient
```

An asynchronous client with a connection pool, safe for concurrent use.

Async clients are created by calling [`create_async_client()`](https://docs.geldata.com/reference/using/python/client.md#gel.create_async_client).

## Method: AsyncIOClient.query()

```py
AsyncIOClient.query(query, * args, ** kwargs)
```

Acquire a connection and use it to run a query and return the results as an [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) instance. The temporary connection is automatically returned back to the pool.

##### Parameters

- **query** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Query text.
- **args** – Positional query arguments.
- **kwargs** – Named query arguments.




##### Returns

An instance of [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) containing the query result.





Note that positional and named query arguments cannot be mixed.


## Method: AsyncIOClient.query_single()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, `None` is returned.

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


## Method: AsyncIOClient.query_required_single()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, an `gel.NoDataError` is raised.

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


## Method: AsyncIOClient.query_json()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#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.

> Note: 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: AsyncIOClient.query_single_json()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, `"null"` is returned.

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

> Note: 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: AsyncIOClient.query_required_single_json()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#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 `gel.ResultCardinalityMismatchError` is raised, if it returns an empty set, an `gel.NoDataError` is raised.

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

> Note: 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: AsyncIOClient.execute()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#str)) – Query text.





The commands must take no arguments.

Example:

```pycon
>>> await con.execute('''
...     CREATE TYPE MyType {
...         CREATE PROPERTY a -> int64
...     };
...     FOR x IN {100, 200, 300}
...     UNION INSERT MyType { a := x };
... ''')
```

> Note: If the results of *query* are desired, [`query()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query), [`query_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_single) or [`query_required_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_required_single) should be used instead.


## Method: AsyncIOClient.transaction()

```py
AsyncIOClient.transaction()
```

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 [`AsyncIORetry`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIORetry).

See [Transactions](https://docs.geldata.com/reference/using/python/client.md#gel-python-asyncio-api-transaction) for more details.

Example:

```python
async for tx in con.transaction():
    async with tx:
        value = await tx.query_single("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 connection.

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


## Method: AsyncIOClient.aclose()

```py
AsyncIOClient.aclose()
```

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 `aclose()` the pool will terminate by calling [`terminate()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.terminate).

It is advisable to use [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for) to set a timeout.


## Method: AsyncIOClient.terminate()

```py
AsyncIOClient.terminate()
```

Terminate all connections in the pool.


## Method: AsyncIOClient.ensure_connected()

```py
AsyncIOClient.ensure_connected()
```

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: AsyncIOClient.with_transaction_options()

```py
AsyncIOClient.with_transaction_options(options = None)
```

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

##### Parameters

**options** ([*TransactionOptions*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.TransactionOptions)) – Object that encapsulates transaction options.





See [Transaction Options](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-transaction-options) for details.


## Method: AsyncIOClient.with_retry_options()

```py
AsyncIOClient.with_retry_options(options = None)
```

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

##### Parameters

**options** ([*RetryOptions*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.RetryOptions)) – Object that encapsulates retry options.





See [Retry Options](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-retry-options) for details.


## Method: AsyncIOClient.with_state()

```py
AsyncIOClient.with_state(state)
```

Returns a shallow copy of the client with adjusted state.

##### Parameters

**state** ([*State*](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State)) – Object that encapsulates state.





See [State](https://docs.geldata.com/reference/using/python/api/advanced.md#gel-python-state) for details.


## Method: AsyncIOClient.with_default_module()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#str)* or *[*None*](https://docs.python.org/3/library/constants.html#None)) – Adjust the *default module*.





See [`State.with_default_module()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_default_module) for details.


## Method: AsyncIOClient.with_module_aliases()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*str*](https://docs.python.org/3/library/stdtypes.html#str)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **aliases** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Adjust the module aliases after applying `aliases_dict` if set.






See [`State.with_module_aliases()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_module_aliases) for details.


## Method: AsyncIOClient.without_module_aliases()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Module aliases to reset.





See [`State.without_module_aliases()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_module_aliases) for details.


## Method: AsyncIOClient.with_config()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*]*) – Adjust the config settings after applying `config_dict` if set.






See [`State.with_config()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_config) for details.


## Method: AsyncIOClient.without_config()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Config to reset.





See [`State.without_config()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_config) for details.


## Method: AsyncIOClient.with_globals()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*] or *[*None*](https://docs.python.org/3/library/constants.html#None)) – This is an optional positional-only argument.

- **globals** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*, *[*object*](https://docs.python.org/3/library/functions.html#object)*]*) – Adjust the global values after applying `globals_dict` if set.






See [`State.with_globals()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.with_globals) for details.


## Method: AsyncIOClient.without_globals()

```py
AsyncIOClient.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*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*]*) – Globals to reset.





See [`State.without_globals()`](https://docs.geldata.com/reference/using/python/api/advanced.md#gel.State.without_globals) for details.



### Transactions

## Class: AsyncIORetry

```py
AsyncIORetry
```

Represents a wrapper that yields [`AsyncIOTransaction`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOTransaction) object when iterating.

See [`AsyncIOClient.transaction()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.transaction) method for an example.

## Method: AsyncIORetry.__anext__()

```py
AsyncIORetry.__anext__()
```

Yields [`AsyncIOTransaction`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOTransaction) object every time transaction has to be repeated.



## Class: AsyncIOTransaction

```py
AsyncIOTransaction
```

Represents a transaction.

Instances of this type are yielded by a [`AsyncIORetry`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIORetry) iterator.

## Describe: async with c:

```
async with c:
```

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


## Method: AsyncIOTransaction.query()

```py
AsyncIOTransaction.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 [`gel.Set`](https://docs.geldata.com/reference/using/python/api/types.md#gel.Set) instance. The temporary connection is automatically returned back to the pool when exiting the transaction block.

See [`AsyncIOClient.query()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query) for details.


## Method: AsyncIOTransaction.query_single()

```py
AsyncIOTransaction.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 [`AsyncIOClient.query_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_single) for details.


## Method: AsyncIOTransaction.query_required_single()

```py
AsyncIOTransaction.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 [`AsyncIOClient.query_required_single()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_required_single) for details.


## Method: AsyncIOTransaction.query_json()

```py
AsyncIOTransaction.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 [`AsyncIOClient.query_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_json) for details.


## Method: AsyncIOTransaction.query_single_json()

```py
AsyncIOTransaction.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 [`AsyncIOClient.query_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_single_json) for details.


## Method: AsyncIOTransaction.query_required_single_json()

```py
AsyncIOTransaction.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 [`AsyncIOClient.query_requried_single_json()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.query_required_single_json) for details.


## Method: AsyncIOTransaction.execute()

```py
AsyncIOTransaction.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 [`AsyncIOClient.execute()`](https://docs.geldata.com/reference/using/python/client.md#gel.AsyncIOClient.execute) for details.



