### Install Documentation Dependencies Source: https://github.com/geldata/gel-python/blob/master/docs/README.md Install Sphinx and other required themes for building the documentation. Run this command from the `docs` directory. ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Install gel-python Source: https://github.com/geldata/gel-python/blob/master/README.rst Use pip to install the gel library. Requires Python 3.9 or later. ```bash $ pip install gel ``` -------------------------------- ### Handle Email + Password Authentication with `gel.auth.EmailPassword` Source: https://context7.com/geldata/gel-python/llms.txt Provides flows for sign-up, sign-in, email verification, and password reset using Gel's built-in auth extension with PKCE. This example shows the setup for the blocking client. ```python import gel from gel._internal._auth._email_password import make, make_async # Blocking client = gel.create_client() auth = make(client) ``` -------------------------------- ### Install EdgeDB Python Driver from Source Source: https://github.com/geldata/gel-python/blob/master/docs/installation.rst Install the EdgeDB driver from a Git checkout. Ensure you have a C compiler and CPython header files installed. ```bash pip install -e . ``` -------------------------------- ### Generate gel.pth file Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Creates a gel.pth file in the site-packages directory to enable editable wheel installation. This is a critical step for development setup. ```bash python -c 'import pathlib, gel; print(pathlib.Path(gel.__path__[0]).parent)' > \ $(python -c 'import site; print(site.getsitepackages()[0])')/gel.pth ``` -------------------------------- ### Asynchronous Transaction Example Source: https://github.com/geldata/gel-python/blob/master/docs/usage.rst Demonstrates using the `transaction()` method with an asynchronous EdgeDB client within an `async for` loop and `async with` block for robust transaction management in asyncio applications. ```python async for tx in client.transaction(): async with tx: await tx.execute("INSERT User {name := 'Don'}") ``` -------------------------------- ### Example EdgeQL Query Source: https://github.com/geldata/gel-python/blob/master/docs/api/codegen.rst A simple EdgeQL query that selects a 64-bit integer argument. ```edgeql select $arg; ``` -------------------------------- ### Install EdgeDB Python Driver with Debug Build Source: https://github.com/geldata/gel-python/blob/master/docs/installation.rst Create a debug build of the EdgeDB driver by setting the EDGEDB_DEBUG environment variable during installation from source. ```bash env EDGEDB_DEBUG=1 pip install -e . ``` -------------------------------- ### EdgeDB Client Connection Pool with aiohttp Source: https://github.com/geldata/gel-python/blob/master/docs/usage.rst Example of integrating an asynchronous EdgeDB client with an aiohttp web server, demonstrating how to create a client instance and use it within request handlers. The client is created synchronously, and connections are lazily established. ```python import asyncio import gel from aiohttp import web async def handle(request): """Handle incoming requests.""" client = request.app['client'] username = request.match_info.get('name') # Execute the query on any pool connection result = await client.query_single_json( ''' SELECT User {first_name, email, bio} FILTER .name = $username ''', username=username) return web.Response( text=result, content_type='application/json') def init_app(): """Initialize the application server.""" app = web.Application() # Create a database client app['client'] = edgedb.create_async_client( database='my_service', user='my_service') # Configure service routes app.router.add_route('GET', '/user/{name}', handle) return app loop = asyncio.get_event_loop() app = init_app() web.run_app(app) ``` -------------------------------- ### Asyncio Client Transaction with Query Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst This example demonstrates executing a query within an asyncio client transaction and then performing an HTTP request. The transaction API guarantees atomicity and retries transient errors. ```python async for tx in client.transaction(): async with tx: user = await tx.query_single( "SELECT User { email } FILTER .login = $login", login=login, ) data = await httpclient.get( ``` -------------------------------- ### Synchronous Transaction Example Source: https://github.com/geldata/gel-python/blob/master/docs/usage.rst Illustrates how to use the `transaction()` method with a synchronous EdgeDB client to manage database transactions. Changes are applied immediately if not within an explicit transaction block. ```python for tx in client.transaction(): with tx: tx.execute("INSERT User {name := 'Don'}") ``` -------------------------------- ### Transaction Rollback Example Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Demonstrates how to rollback an in-progress transaction by raising a custom exception. ```APIDOC ## Transaction Rollback Example ### Description This example shows how to initiate a transaction and explicitly roll it back by raising a custom exception. ### Code ```python class RollBack(Exception): """A user defined exception.""" try: async for tx in client.transaction(): async with tx: raise RollBack except RollBack: pass ``` ``` -------------------------------- ### Run EdgeDB Python Test Suite Source: https://github.com/geldata/gel-python/blob/master/docs/installation.rst Execute the test suite for the EdgeDB Python driver. This requires a local installation of the EdgeDB server. ```bash python setup.py test ``` -------------------------------- ### Create Asynchronous Gel Client Source: https://context7.com/geldata/gel-python/llms.txt Use `gel.create_async_client()` within an asyncio event loop to get an asynchronous client. This client is designed to be shared across coroutines and tasks for efficient connection pooling. ```python import asyncio import gel async def main(): async with gel.create_async_client( host="localhost", branch="main", max_concurrency=20, ) as client: result = await client.query("SELECT 42") print(result) # [42] asyncio.run(main()) ``` -------------------------------- ### Create Async Client and Query Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Instantiate an asynchronous client and execute a simple query. The client can be created with default parameters, inferring connection details from the environment or project configuration. ```python client = edgedb.create_async_client() await client.query('SELECT {1, 2, 3}') ``` -------------------------------- ### Create Client with Transaction Options Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Returns a shallow copy of the client with adjusted transaction options. Use this to configure transaction-specific settings. ```python client.with_transaction_options(options=TransactionOptions(...)) ``` -------------------------------- ### Basic Gel Python Usage Source: https://github.com/geldata/gel-python/blob/master/README.rst Demonstrates creating a client, defining a User type, inserting a User object, and selecting User objects using raw queries. Ensure the client is closed after use. ```python import datetime import gel def main(): client = gel.create_client() # Create a User object type client.execute(''' CREATE TYPE User { CREATE REQUIRED PROPERTY name -> str; CREATE PROPERTY dob -> cal::local_date; } ''') # Insert a new User object client.query(''' INSERT User { name := $name, dob := $dob } ''', name='Bob', dob=datetime.date(1984, 3, 1)) # Select User objects. user_set = client.query( 'SELECT User {name, dob} FILTER .name = $name', name='Bob') # *user_set* now contains # Set{Object{name := 'Bob', dob := datetime.date(1984, 3, 1)}} # Close the client. client.close() if __name__ == '__main__': main() ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/geldata/gel-python/blob/master/docs/README.md Generate the HTML version of the documentation. The output will be located in the `docs/_build` directory. ```bash $ make html ``` -------------------------------- ### Sign Up with Email and Password Source: https://context7.com/geldata/gel-python/llms.txt Handles user sign-up using email and password. It can either complete the sign-up directly or require email verification. ```python from gel._internal._auth._email_password import ( SignUpCompleteResponse, SignUpVerificationRequiredResponse, ) resp = auth.sign_up("user@example.com", "s3cr3t!", verify_url="https://app.example.com/verify") if isinstance(resp, SignUpCompleteResponse): token = resp.token_data.auth_token print("Signed up:", resp.identity_id, token) elif isinstance(resp, SignUpVerificationRequiredResponse): print("Check your inbox to verify email; verifier:", resp.verifier) ``` -------------------------------- ### Install EdgeDB Python Driver with Pip Source: https://github.com/geldata/gel-python/blob/master/docs/installation.rst Use this command to install the EdgeDB driver using pip. It is recommended to use pip version 8.1 or later for precompiled wheels. ```bash pip install edgedb ``` -------------------------------- ### Create and Use Synchronous EdgeDB Client Source: https://github.com/geldata/gel-python/blob/master/docs/usage.rst Demonstrates creating a synchronous EdgeDB client, inserting data, querying data, and closing the client. Ensure you have an EdgeDB project configured. ```python import datetime import gel client = edgedb.create_client() client.query(""" INSERT User { name := $name, dob := $dob } """, name="Bob", dob=datetime.date(1984, 3, 1)) user_set = client.query( "SELECT User {name, dob} FILTER .name = $name", name="Bob") # *user_set* now contains # Set{Object{name := 'Bob', dob := datetime.date(1984, 3, 1)}} client.close() ``` -------------------------------- ### transaction Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Opens a retryable transaction loop for robust transaction management. The transaction starts lazily when the first query is issued. ```APIDOC ## transaction() ### Description 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 Returns an instance of :py:class:`AsyncIORetry`. ### 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 := $value }", value=value + 1, ) ``` ### Note The transaction starts lazily. A connection is only acquired from the pool when the first query is issued on the transaction instance. ``` -------------------------------- ### Set GEL_SERVER_BINARY using gel server info Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Sets the GEL_SERVER_BINARY environment variable by querying the gel server binary path for a specific version. ```bash export GEL_SERVER_BINARY=$(gel server info --bin-path --version '6') ``` -------------------------------- ### Parallel pytest execution Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Executes tests in parallel using pytest-xdist. Warning: This can consume significant RAM as each process starts its own database. ```bash # Parallel execution (requires pytest-xdist) pytest -n 5 # Warning: High RAM usage, each process starts own DB ``` -------------------------------- ### Check Documentation Links Source: https://github.com/geldata/gel-python/blob/master/docs/README.md Verify that all internal and external links within the documentation are valid and working. ```bash $ make linkcheck ``` -------------------------------- ### Create Client with State Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Returns a shallow copy of the client with adjusted state. Use this to manage and pass custom state information through client operations. ```python new_client = client.with_state(state=my_state_object) ``` -------------------------------- ### Generated Asynchronous Python Function Source: https://github.com/geldata/gel-python/blob/master/docs/api/codegen.rst This is an example of a Python function generated by `edgedb-py` for an asynchronous client. It takes an `AsyncIOClient` and an integer argument, then executes the EdgeQL query. ```python from __future__ import annotations import gel async def get_number( client: edgedb.AsyncIOClient, *, arg: int, ) -> int: return await client.query_single( """ select $arg""", arg=arg, ) ``` -------------------------------- ### Basic Save and Sync Usage Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/_save.md Demonstrates the fundamental usage of `save` to upload changes and `sync` to refetch them. New objects inserted via these functions will have their `id` set. ```python foo = default.Foo(n=1) bar = default.Bar(foo=foo) client.save(foo, bar) # after foo is changed somewhere else client.sync(foo) ``` -------------------------------- ### gel.ai.create_rag_client / gel.ai.create_async_rag_client Source: https://context7.com/geldata/gel-python/llms.txt Creates a client for the Gel AI extension that supports retrieval-augmented generation (RAG) and embedding generation. Requires the `gel[ai]` extra and an AI extension configured in your Gel schema. ```APIDOC ## `gel.ai.create_rag_client` / `gel.ai.create_async_rag_client` Creates a client for the Gel AI extension that supports retrieval-augmented generation (RAG) and embedding generation. Requires the `gel[ai]` extra and an AI extension configured in your Gel schema. ```python import gel from gel.ai import create_rag_client, create_async_rag_client # Blocking RAG db = gel.create_client() rag = create_rag_client(db, model="gpt-4o") # Specify which objects to retrieve as context from gel.ai.types import QueryContext ctx = QueryContext( query="SELECT KnowledgeArticle { title, body }", max_object_count=5, ) # Single response answer: str = rag.query_rag("What is EdgeQL?", context=ctx) print(answer) # Streaming response (SSE) for chunk in rag.stream_rag("Explain transactions in Gel", context=ctx): print(chunk, end="", flush=True) # Embeddings embeddings: list[float] = rag.generate_embeddings( "semantic search query", model="text-embedding-3-small", ) db.close() ``` ``` -------------------------------- ### Connection Options Source: https://github.com/geldata/gel-python/blob/master/docs/api/codegen.rst The `edgedb-py` command supports standard connection options for establishing a connection to the database. ```bash -I, --instance --dsn --credentials-file -H, --host -P, --port -d, --database -u, --user --password --password-from-stdin --tls-ca-file --tls-security ``` -------------------------------- ### Query returning JSON strings Source: https://context7.com/geldata/gel-python/llms.txt Use `query_json` to get results as a JSON string from the server, ideal for HTTP APIs. `query_single_json` retrieves a single JSON object or null. ```python import gel client = gel.create_client() json_str: str = client.query_json( "SELECT User { name, email } ORDER BY .name LIMIT 10" ) # '[{"name": "Alice", "email": "alice@example.com"}, ...]' single_json: str = client.query_single_json( "SELECT User { name, email } FILTER .email = $email", email="alice@example.com", ) # '{"name": "Alice", "email": "alice@example.com"}' or 'null' client.close() ``` -------------------------------- ### Clean Documentation Build Source: https://github.com/geldata/gel-python/blob/master/docs/README.md Remove previously generated documentation files to ensure a clean build. ```bash $ make clean ``` -------------------------------- ### Client.with_globals / Client.with_config / Client.with_default_module Source: https://context7.com/geldata/gel-python/llms.txt Returns a shallow copy of the client with modified session state (globals, config values, module aliases). All methods are immutable / builder-style. ```APIDOC ## `Client.with_globals` / `Client.with_config` / `Client.with_default_module` Returns a shallow copy of the client with modified session state (globals, config values, module aliases). All methods are immutable / builder-style. ```python import gel client = gel.create_client() # Set a global variable used in access policies authed_client = client.with_globals( {"default::current_user_id": "12345678-0000-0000-0000-000000000000"} ) # Adjust query timeout config for a slow reporting query slow_client = client.with_config(query_execution_timeout=60.0) # Set default module mymod_client = client.with_default_module("myapp") results = authed_client.query("SELECT VisibleDocument { title }") client.close() ``` ``` -------------------------------- ### Execute Transactional Code Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Use the transaction() loop API for robust transactional code. Queries should be executed on the `tx` object within the `with tx:` block. Transaction start is lazy and occurs on the first query execution. ```python for tx in client.transaction(): with tx: tx.execute("INSERT User { name := 'Don' }") ``` -------------------------------- ### Transaction Context Manager Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Transactions are managed using a context manager. Entering the block starts a transaction, and exiting either commits or rolls back the transaction automatically. Raising an exception within the block will trigger a rollback. ```APIDOC ## Transaction Context Manager Transactions are managed using a context manager provided by `client.transaction()`. ```python class RollBack(Exception): """A user defined exception.""" try: for tx in client.transaction(): with tx: # Perform operations within the transaction # If an exception is raised, the transaction will be rolled back raise RollBack except RollBack: # Handle the rollback pass ``` **Note:** It is generally recommended to avoid long-running operations within transactions to prevent performance degradation and resource locking. ``` -------------------------------- ### Eagerly Establish Connections with `Client.ensure_connected` Source: https://context7.com/geldata/gel-python/llms.txt Force the connection pool to establish at least one connection immediately, rather than waiting for the first query. This is beneficial for startup health checks. ```python import gel # Sync client = gel.create_client() try: client.ensure_connected() print("Database is reachable") except gel.ClientConnectionError as e: print(f"Cannot connect: {e}") # Async async def startup(app): app["db"] = gel.create_async_client() await app["db"].ensure_connected() ``` -------------------------------- ### Asyncio Client Transaction API Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Use the transaction() loop API for robust transactional code. Queries are executed on the 'tx' object within the transaction block. Transaction start is lazy and occurs on the first query execution. ```python async for tx in client.transaction(): async with tx: await tx.execute("INSERT User { name := 'Don' }") ``` -------------------------------- ### Use RAG/AI Extension Client with `gel.ai` Source: https://context7.com/geldata/gel-python/llms.txt Create a client for the Gel AI extension to support retrieval-augmented generation (RAG) and embedding generation. Requires the `gel[ai]` extra and a configured AI extension in your Gel schema. ```python import gel from gel.ai import create_rag_client, create_async_rag_client # Blocking RAG db = gel.create_client() rag = create_rag_client(db, model="gpt-4o") # Specify which objects to retrieve as context from gel.ai.types import QueryContext ctx = QueryContext( query="SELECT KnowledgeArticle { title, body }", max_object_count=5, ) # Single response answer: str = rag.query_rag("What is EdgeQL?", context=ctx) print(answer) # Streaming response (SSE) for chunk in rag.stream_rag("Explain transactions in Gel", context=ctx): print(chunk, end="", flush=True) # Embeddings embeddings: list[float] = rag.generate_embeddings( "semantic search query", model="text-embedding-3-small", ) db.close() ``` -------------------------------- ### Run raw SQL queries Source: https://context7.com/geldata/gel-python/llms.txt Use `query_sql` to execute SQL queries and receive `gel.Record` objects. `execute_sql` is for fire-and-forget SQL DDL. ```python import gel client = gel.create_client() rows = client.query_sql( "SELECT id, name FROM default.\"User\" WHERE name LIKE $1", "A%", ) for row in rows: print(row["id"], row["name"]) # Fire-and-forget SQL DDL client.execute_sql("CREATE INDEX IF NOT EXISTS user_name_idx ON default.\"User\"(name)") client.close() ``` -------------------------------- ### Create Client with Default Module Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Returns a shallow copy of the client with an adjusted default module. This simplifies queries by allowing you to omit the module name for types and functions within that module. ```python new_client = client.with_default_module('my_module') ``` -------------------------------- ### Create Blocking Gel Client Source: https://context7.com/geldata/gel-python/llms.txt Use `gel.create_client()` to obtain a blocking client instance. It supports project-based configuration or explicit DSN/parameters. The client can be used as a context manager for automatic connection management. ```python import gel # Project-based connection (reads gel.toml / credentials automatically) client = gel.create_client() # Explicit DSN client = gel.create_client("gel://user:pass@localhost:5656/mydb") # All individual parameters client = gel.create_client( host="localhost", port=5656, user="admin", password="secret", branch="main", tls_ca_file="/path/to/ca.pem", tls_security="strict", # "strict" | "no_host_verification" | "insecure" max_concurrency=10, wait_until_available=30, # seconds timeout=10, ) # Use as a context manager (ensures_connected + closes on exit) with gel.create_client() as client: result = client.query("SELECT 1 + 1") print(result) # [2] ``` -------------------------------- ### Create and Use Asynchronous EdgeDB Client Source: https://github.com/geldata/gel-python/blob/master/docs/usage.rst Shows how to create an asynchronous EdgeDB client using `create_async_client`, perform operations within an async function, and close the client. This is suitable for asyncio applications. ```python import asyncio import datetime import gel client = edgedb.create_async_client() async def main(): await client.query(""" INSERT User { name := $name, dob := $dob } """, name="Bob", dob=datetime.date(1984, 3, 1)) user_set = await client.query( "SELECT User {name, dob} FILTER .name = $name", name="Bob") # *user_set* now contains # Set{Object{name := 'Bob', dob := datetime.date(1984, 3, 1)}} await client.aclose() asyncio.run(main()) ``` -------------------------------- ### `gel.create_async_client` — Create an async connection pool Source: https://context7.com/geldata/gel-python/llms.txt Returns a `gel.AsyncIOClient`. Accepts identical parameters to `create_client`. Must be used inside an asyncio event loop. Share a single instance across all coroutines/tasks. ```APIDOC ## `gel.create_async_client` — Create an async connection pool Returns a `gel.AsyncIOClient`. Accepts identical parameters to `create_client`. Must be used inside an asyncio event loop. Share a single instance across all coroutines/tasks. ```python import asyncio import gel async def main(): async with gel.create_async_client( host="localhost", branch="main", max_concurrency=20, ) as client: result = await client.query("SELECT 42") print(result) # [42] asyncio.run(main()) ``` ``` -------------------------------- ### Modify Client Session State with `with_globals`, `with_config`, `with_default_module` Source: https://context7.com/geldata/gel-python/llms.txt Use these builder-style methods to create a new client instance with modified session state without affecting the original client. Useful for setting global variables, adjusting query timeouts, or specifying a default module for queries. ```python import gel client = gel.create_client() # Set a global variable used in access policies authed_client = client.with_globals( {"default::current_user_id": "12345678-0000-0000-0000-000000000000"} ) # Adjust query timeout config for a slow reporting query slow_client = client.with_config(query_execution_timeout=60.0) # Set default module mymod_client = client.with_default_module("myapp") results = authed_client.query("SELECT VisibleDocument { title }") client.close() ``` -------------------------------- ### Sign In with Email and Password Source: https://context7.com/geldata/gel-python/llms.txt Authenticates a user using their email and password, returning an authentication token upon success. ```python from gel._internal._auth._email_password import SignInCompleteResponse resp2 = auth.sign_in("user@example.com", "s3cr3t!") if isinstance(resp2, SignInCompleteResponse): print("Auth token:", resp2.token_data.auth_token) ``` -------------------------------- ### Basic pytest execution Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Runs all tests in the tests/test_qb.py file using pytest. ```bash # Basic test run pytest tests/test_qb.py ``` -------------------------------- ### Create Client with Retry Options Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Returns a shallow copy of the client with adjusted retry options. This allows for customizing how the client handles retries for transient errors. ```python client.with_retry_options(options=RetryOptions(...)) ``` -------------------------------- ### Set GEL_SERVER_BINARY environment variable Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Configures the GEL_SERVER_BINARY environment variable to point to the development server binary. This is necessary for using the dev server in your Gel environment. ```bash export GEL_SERVER_BINARY=/bin/gel-server ``` -------------------------------- ### Gel Datatype Mapping and Querying Source: https://context7.com/geldata/gel-python/llms.txt Demonstrates how Gel automatically maps EdgeDB wire types to Python types and how to query data using the client. ```python import gel import datetime, decimal, uuid client = gel.create_client() # gel.Object — query result rows obj = client.query_single("SELECT User { name, dob } LIMIT 1") print(obj.name) # str print(obj.dob) # datetime.date (cal::local_date) # gel.NamedTuple nt = client.query_single("SELECT (a := 1, b := 'hello')") print(nt.a, nt.b) # 1 'hello' print(nt._fields) # ('a', 'b') # gel.RelativeDuration rd = client.query_single("SELECT '1 year 3 months 5 days'") print(rd.months, rd.days) # 15 5 # gel.DateDuration dd = client.query_single("SELECT '2 months 10 days'") print(dd.months, dd.days) # 2 10 # gel.EnumValue ev = client.query_single("SELECT 'active'") print(str(ev)) # 'active' print(ev.value) # 'active' # gel.Range rng = client.query_single("SELECT range(1, 10)") print(rng.lower, rng.upper, rng.inc_lower, rng.inc_upper) # 1 10 True False # Scalar types map directly results = client.query_single ( """SELECT { i := 42, f := 3.14, d := '1.5', b := true, ts := datetime_current(), uid := '00000000-0000-0000-0000-000000000000', }""" ) # int, float, Decimal, bool, datetime.datetime(tz-aware), uuid.UUID client.close() ``` -------------------------------- ### create_async_client Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Creates an asynchronous client with a lazy connection pool. Connection parameters can be specified via DSN, keyword arguments, or environment variables. ```APIDOC ## create_async_client ### Description 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 :ref:`Client Library Connection ` docs for more information. Returns a new :py:class:`AsyncIOClient` object. ### Parameters * **dsn** (str) - If this parameter does not start with ``edgedb://`` then this is interpreted as the :ref:`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 :ref:`DSN Specification `. * **host** (str) - 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 ``EDGEDB_HOST`` environment variable, - ``"localhost"``. * **port** (int) - 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 ``EDGEDB_PORT`` environment variable, or ``5656`` if neither is specified. * **user** (str) - 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** (str) - 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** (str) - 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. * **secret_key** (str) - 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 ``EDGEDB_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) - Connection timeout in seconds. Defaults to 60. * **concurrency** (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 :py:class:`AsyncIOClient`. ### Example ```python import edgedb async def main(): client = edgedb.create_async_client() await client.query('SELECT {1, 2, 3}') # Example with transaction async for tx in client.transaction(): async with tx: await tx.execute("SELECT 1") if __name__ == "__main__": import asyncio asyncio.run(main()) ``` ``` -------------------------------- ### Client State Management Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Methods for creating copies of the client with modified state, default modules, module aliases, configuration, and global values. ```APIDOC ## `with_state(state)` ### Description Returns a shallow copy of the client with adjusted state. ### Parameters #### Path Parameters - **state** (State) - Required - Object that encapsulates state. ### See Also :ref:`edgedb-python-state` ``` ```APIDOC ## `with_default_module(module=None)` ### Description 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 #### Path Parameters - **module** (str or None) - Optional - Adjust the *default module*. ### See Also :py:meth:`State.with_default_module` ``` ```APIDOC ## `with_module_aliases(aliases_dict=None, /, **aliases)` ### Description Returns a shallow copy of the client with adjusted module aliases. This is equivalent to using the ``set alias`` command. ### Parameters #### Path Parameters - **aliases_dict** (dict[str, str] or None) - Optional - This is an optional positional-only argument. #### Keyword Arguments - **aliases** (dict[str, str]) - Adjust the module aliases after applying ``aliases_dict`` if set. ### See Also :py:meth:`State.with_module_aliases` ``` ```APIDOC ## `without_module_aliases(*aliases)` ### Description Returns a shallow copy of the client without specified module aliases. This is equivalent to using the ``reset alias`` command. ### Parameters #### Path Parameters - **aliases** (tuple[str]) - Module aliases to reset. ### See Also :py:meth:`State.without_module_aliases` ``` ```APIDOC ## `with_config(config_dict=None, /, **config)` ### Description Returns a shallow copy of the client with adjusted session config. This is equivalent to using the ``configure session set`` command. ### Parameters #### Path Parameters - **config_dict** (dict[str, object] or None) - Optional - This is an optional positional-only argument. #### Keyword Arguments - **config** (dict[str, object]) - Adjust the config settings after applying ``config_dict`` if set. ### See Also :py:meth:`State.with_config` ``` ```APIDOC ## `without_config(*config_names)` ### Description Returns a shallow copy of the client without specified session config. This is equivalent to using the ``configure session reset`` command. ### Parameters #### Path Parameters - **config_names** (tuple[str]) - Config to reset. ### See Also :py:meth:`State.without_config` ``` ```APIDOC ## `with_globals(globals_dict=None, /, **globals_)` ### Description Returns a shallow copy of the client with adjusted global values. This is equivalent to using the ``set global`` command. ### Parameters #### Path Parameters - **globals_dict** (dict[str, object] or None) - Optional - This is an optional positional-only argument. #### Keyword Arguments - **globals_** (dict[str, object]) - Adjust the global values after applying ``globals_dict`` if set. ### See Also :py:meth:`State.with_globals` ``` ```APIDOC ## `without_globals(*global_names)` ### Description Returns a shallow copy of the client without specified globals. This is equivalent to using the ``reset global`` command. ### Parameters #### Path Parameters - **global_names** (tuple[str]) - Globals to reset. ### See Also :py:meth:`State.without_globals` ``` -------------------------------- ### Create and Use Blocking Client Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Create a blocking client instance and execute a simple query. The client manages a connection pool, making its methods thread-safe. ```python client = edgedb.create_client() client.query('SELECT {1, 2, 3}') ``` -------------------------------- ### Querying and Accessing Object Properties Source: https://github.com/geldata/gel-python/blob/master/docs/api/types.rst Demonstrates how to query for an object and access its properties using attribute notation. Ensure you have an EdgeDB client initialized. ```pycon >>> import gel >>> client = edgedb.create_client() >>> r = client.query_single(''' SELECT schema::ObjectType {name} FILTER .name = 'std::Object' LIMIT 1''') >>> r Object{name := 'std::Object'} >>> r.name 'std::Object' ``` -------------------------------- ### `gel.create_client` — Create a blocking connection pool Source: https://context7.com/geldata/gel-python/llms.txt Returns a `gel.Client` that lazily creates and pools blocking (thread-safe) connections. All keyword arguments are optional when a Gel project is active in the current directory. ```APIDOC ## `gel.create_client` — Create a blocking connection pool Returns a `gel.Client` that lazily creates and pools blocking (thread-safe) connections. All keyword arguments are optional when a Gel project is active in the current directory. ```python import gel # Project-based connection (reads gel.toml / credentials automatically) client = gel.create_client() # Explicit DSN client = gel.create_client("gel://user:pass@localhost:5656/mydb") # All individual parameters client = gel.create_client( host="localhost", port=5656, user="admin", password="secret", branch="main", tls_ca_file="/path/to/ca.pem", tls_security="strict", # "strict" | "no_host_verification" | "insecure" max_concurrency=10, wait_until_available=30, # seconds timeout=10, ) # Use as a context manager (ensures_connected + closes on exit) with gel.create_client() as client: result = client.query("SELECT 1 + 1") print(result) # [2] ``` ``` -------------------------------- ### Client State Modification Shortcuts Source: https://github.com/geldata/gel-python/blob/master/docs/api/advanced.rst Provides shortcuts for modifying client state, such as setting default modules, module aliases, configuration, and global variables. These methods return a new client instance with the adjusted state. ```APIDOC ## Client State Modification Shortcuts These methods provide convenient ways to adjust the client's state without directly manipulating the state object. Each method returns a new client instance with the specified state modification applied. ### `edgedb.Client.with_default_module(module_name: str)` Sets the default module for subsequent queries. ### `edgedb.Client.with_module_aliases(aliases: dict[str, str])` Applies a dictionary of module aliases. ### `edgedb.Client.without_module_aliases()` Removes all module aliases. ### `edgedb.Client.with_config(config: dict[str, Any])` Applies a dictionary of configuration settings. ### `edgedb.Client.without_config()` Removes all client-side configuration. ### `edgedb.Client.with_globals(globals: dict[str, Any])` Applies a dictionary of global variables. ### `edgedb.Client.without_globals()` Removes all global variables. ### `edgedb.AsyncIOClient.with_default_module(module_name: str)` Asynchronous version: Sets the default module for subsequent queries. ### `edgedb.AsyncIOClient.with_module_aliases(aliases: dict[str, str])` Asynchronous version: Applies a dictionary of module aliases. ### `edgedb.AsyncIOClient.without_module_aliases()` Asynchronous version: Removes all module aliases. ### `edgedb.AsyncIOClient.with_config(config: dict[str, Any])` Asynchronous version: Applies a dictionary of configuration settings. ### `edgedb.AsyncIOClient.without_config()` Asynchronous version: Removes all client-side configuration. ### `edgedb.AsyncIOClient.with_globals(globals: dict[str, Any])` Asynchronous version: Applies a dictionary of global variables. ### `edgedb.AsyncIOClient.without_globals()` Asynchronous version: Removes all global variables. ``` -------------------------------- ### State Manipulation Methods Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Methods for creating a shallow copy of the client with adjusted module, alias, configuration, or global settings. ```APIDOC ## with_default_module ### Description Returns a shallow copy of the client with an adjusted default module. ### Method `with_default_module(module: str | None = None)` ### Parameters - **module** (str or None) - The default module to set. ### See Also :py:meth:`State.with_default_module` ``` ```APIDOC ## with_module_aliases ### Description Returns a shallow copy of the client with adjusted module aliases. ### Method `with_module_aliases(aliases_dict: dict[str, str] | None = None, /, **aliases: dict[str, str])` ### Parameters - **aliases_dict** (dict[str, str] or None) - An optional positional-only argument for module aliases. - **aliases** (dict[str, str]) - Adjust the module aliases after applying ``aliases_dict`` if set. ### See Also :py:meth:`State.with_module_aliases` ``` ```APIDOC ## without_module_aliases ### Description Returns a shallow copy of the client without specified module aliases. ### Method `without_module_aliases(*aliases: str)` ### Parameters - **aliases** (tuple[str]) - Module aliases to reset. ### See Also :py:meth:`State.without_module_aliases` ``` ```APIDOC ## with_config ### Description Returns a shallow copy of the client with adjusted session config. ### Method `with_config(config_dict: dict[str, object] | None = None, /, **config: dict[str, object])` ### Parameters - **config_dict** (dict[str, object] or None) - An optional positional-only argument for session config. - **config** (dict[str, object]) - Adjust the config settings after applying ``config_dict`` if set. ### See Also :py:meth:`State.with_config` ``` ```APIDOC ## without_config ### Description Returns a shallow copy of the client without specified session config. ### Method `without_config(*config_names: str)` ### Parameters - **config_names** (tuple[str]) - Config to reset. ### See Also :py:meth:`State.without_config` ``` ```APIDOC ## with_globals ### Description Returns a shallow copy of the client with adjusted global values. ### Method `with_globals(globals_dict: dict[str, object] | None = None, /, **globals_: dict[str, object])` ### Parameters - **globals_dict** (dict[str, object] or None) - An optional positional-only argument for global values. - **globals_** (dict[str, object]) - Adjust the global values after applying ``globals_dict`` if set. ### See Also :py:meth:`State.with_globals` ``` ```APIDOC ## without_globals ### Description Returns a shallow copy of the client without specified globals. ### Method `without_globals(*global_names: str)` ### Parameters - **global_names** (tuple[str]) - Globals to reset. ### See Also :py:meth:`State.without_globals` ``` -------------------------------- ### with_state Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Returns a copy of the client with adjusted state. ```APIDOC ## with_state(state) ### Description Returns a shallow copy of the client with adjusted state. ### Method `with_state` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **state** (State) - Required - Object that encapsulates state. ### Request Example ```python from edgedb.state import State client_state = State(session_params={'some_param': 'some_value'}) new_client = client.with_state(state=client_state) ``` ### Response #### Success Response (200) A shallow copy of the client with adjusted state. #### Response Example None specified. ``` -------------------------------- ### query_single Source: https://github.com/geldata/gel-python/blob/master/docs/api/asyncio_client.rst Acquires a connection, runs an optional singleton-returning query, and returns its element. The connection is automatically returned to the pool. ```APIDOC ## query_single(query, *args, **kwargs) ### Description 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. ``` -------------------------------- ### gel.auth.EmailPassword / gel.auth.AsyncEmailPassword Source: https://context7.com/geldata/gel-python/llms.txt Provides sign-up, sign-in, email verification, and password-reset flows using Gel's built-in auth extension with PKCE. ```APIDOC ## `gel.auth.EmailPassword` / `gel.auth.AsyncEmailPassword` Provides sign-up, sign-in, email verification, and password-reset flows using Gel's built-in auth extension with PKCE. ```python import gel from gel._internal._auth._email_password import make, make_async # Blocking client = gel.create_client() auth = make(client) ``` ``` -------------------------------- ### create_client Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Creates a blocking client instance with a lazy connection pool. Connection parameters can be provided via DSN, keyword arguments, or environment variables. ```APIDOC ## create_client ### Description Creates a blocking client with a lazy connection pool. Connection parameters can be specified via DSN, keyword arguments, or environment variables. If both DSN and keyword arguments are provided, keyword arguments take precedence. ### Parameters * **dsn** (string, optional) - Connection URI or instance name. * **host** (string, optional) - Database host address. * **port** (integer, optional) - Port number to connect to. * **user** (string, optional) - Database role name for authentication. * **password** (string, optional) - Password for authentication. * **secret_key** (string, optional) - Secret key for authentication. * **database** (string, optional) - Name of the database to connect to. * **timeout** (float, optional) - Connection timeout in seconds. Defaults to 60. * **concurrency** (integer, optional) - Number of concurrent connections. ### Returns * An instance of `Client`. ### Example ```python import edgedb client = edgedb.create_client() client.query('SELECT {1, 2, 3}') # Example with specific parameters client_specific = edgedb.create_client( user='myuser', database='mydb', host='localhost', port=5656 ) ``` ``` -------------------------------- ### Generate Python Models with Gel Source: https://github.com/geldata/gel-python/blob/master/README.rst Run the gel generate command to create a 'models' package in your Python project. This enables programmatic query building and Pydantic model integration. ```bash $ gel generate py/models ``` -------------------------------- ### Gel Python Project Structure Source: https://github.com/geldata/gel-python/blob/master/gel/_internal/arch.md Illustrates the directory structure of the gel-python library, indicating the organization of internal modules for query building, model systems, reflection, code generation, and persistence. ```tree gel/ ├── _internal/ │ ├── _qb/ │ ├── _qbmodel/ │ │ ├── _abstract/ │ │ └── _pydantic/ │ ├── _reflection/ │ ├── _codegen/ │ │ └── _models/ │ │ └── _pydantic.py │ ├── _save.py │ ├── _tracked_list.py │ └── _link_set.py ``` -------------------------------- ### with_default_module Source: https://github.com/geldata/gel-python/blob/master/docs/api/blocking_client.rst Returns a copy of the client with an adjusted default module. ```APIDOC ## with_default_module(module=None) ### Description Returns a shallow copy of the client with adjusted default module. ### Method `with_default_module` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **module** (str) - Optional - The name of the default module. ### Request Example ```python new_client = client.with_default_module(module='my_module') ``` ### Response #### Success Response (200) A shallow copy of the client with an adjusted default module. #### Response Example None specified. ```