EdgeDB Python driver providing both blocking IO and asyncio implementations for connecting to and interacting with EdgeDB databases.
—
Client configuration options, session state management, connection parameters, and advanced client behavior control.
Control client session state including default modules, module aliases, configuration, and global variables.
class State:
"""
Client session state management.
Manages module context, configuration settings, and global variables
for EdgeDB client sessions.
"""
def with_default_module(self, module: str) -> State:
"""
Create new state with default module.
Parameters:
- module: Module name to use as default
Returns:
New State instance with updated default module
"""
def without_default_module(self) -> State:
"""
Create new state without default module.
Returns:
New State instance with no default module
"""
def with_module_aliases(self, **aliases: str) -> State:
"""
Create new state with module aliases.
Parameters:
- **aliases: Module alias mappings (alias=module_name)
Returns:
New State instance with added module aliases
"""
def without_module_aliases(self, *aliases: str) -> State:
"""
Create new state without specified module aliases.
Parameters:
- *aliases: Alias names to remove
Returns:
New State instance with removed aliases
"""
def with_config(self, **config: Any) -> State:
"""
Create new state with configuration settings.
Parameters:
- **config: Configuration key-value pairs
Returns:
New State instance with updated configuration
"""
def without_config(self, *settings: str) -> State:
"""
Create new state without specified configuration settings.
Parameters:
- *settings: Configuration setting names to remove
Returns:
New State instance with removed settings
"""
def with_globals(self, **globals: Any) -> State:
"""
Create new state with global variables.
Parameters:
- **globals: Global variable key-value pairs
Returns:
New State instance with updated globals
"""
def without_globals(self, *globals: str) -> State:
"""
Create new state without specified global variables.
Parameters:
- *globals: Global variable names to remove
Returns:
New State instance with removed globals
"""Configuration for handling query warnings and messages from the database.
WarningHandler = Callable[[Tuple[EdgeDBError, ...], Any], Any]
"""
Type for warning handler functions.
Parameters:
- warnings: Tuple of warning messages from the database
- result: Query result that generated the warnings
Returns:
Potentially modified result or raises exception
"""Credential management for database authentication.
class Credentials:
"""
Database connection credentials.
Encapsulates authentication information for EdgeDB connections.
"""
def __init__(
self,
*,
user: Optional[str] = None,
password: Optional[str] = None,
secret_key: Optional[str] = None
):
"""
Create credentials object.
Parameters:
- user: Database user name
- password: Database password
- secret_key: Secret key for JWT authentication
"""
@classmethod
def from_file(cls, path: str) -> Credentials:
"""
Load credentials from file.
Parameters:
- path: Path to credentials file
Returns:
Credentials object loaded from file
"""Configuration enums and constants for client behavior.
class Cardinality(Enum):
"""
Query result cardinality enumeration.
Indicates the expected number of results from a query.
"""
NO_RESULT = "n" # Query returns no results
AT_MOST_ONE = "?" # Query returns 0 or 1 result
ONE = "1" # Query returns exactly 1 result
MANY = "*" # Query returns 0 or more results
AT_LEAST_ONE = "+" # Query returns 1 or more results
def is_single(self) -> bool:
"""Check if cardinality expects single result."""
def is_multi(self) -> bool:
"""Check if cardinality expects multiple results."""
class ElementKind(Enum):
"""
Schema element kind enumeration.
Identifies the type of schema element in introspection.
"""
LINK = "link"
PROPERTY = "property"
LINK_PROPERTY = "linkprop"import edgedb
client = edgedb.create_client()
# Set default module
state = edgedb.State().with_default_module("blog")
# Query without explicitly qualifying types
posts = client.with_state(state).query("SELECT Post { title, content }")
# Equivalent to: SELECT blog::Post { title, content }
# Module aliases
state = edgedb.State().with_module_aliases(
auth="authentication",
blog="content_management"
)
users = client.with_state(state).query("SELECT auth::User { name }")
# Equivalent to: SELECT authentication::User { name }import edgedb
client = edgedb.create_client()
# Set configuration
state = edgedb.State().with_config(
query_execution_timeout="30s",
idle_transaction_timeout="10s"
)
# Apply configuration to queries
result = client.with_state(state).query("SELECT expensive_computation()")
# Chain state modifications
state = (
edgedb.State()
.with_default_module("blog")
.with_config(query_execution_timeout="60s")
.with_module_aliases(auth="user_management")
)
client_with_state = client.with_state(state)import edgedb
client = edgedb.create_client()
# Set global variables
state = edgedb.State().with_globals(
current_user_id="123e4567-e89b-12d3-a456-426614174000",
tenant_id="tenant_1"
)
# Use globals in queries
posts = client.with_state(state).query("""
SELECT Post {
title,
content,
author: { name }
}
FILTER .author.id = global current_user_id
""")
# Update globals
updated_state = state.with_globals(current_user_id="different-user-id")import edgedb
# Create client with persistent state
base_state = (
edgedb.State()
.with_default_module("app")
.with_config(query_execution_timeout="30s")
.with_globals(app_version="1.0.0")
)
client = edgedb.create_client().with_state(base_state)
# All queries use the base state
users = client.query("SELECT User { name }") # Uses app::User
# Temporarily override state for specific queries
admin_state = base_state.with_globals(is_admin=True)
admin_users = client.with_state(admin_state).query("""
SELECT User { name, admin_notes }
FILTER global is_admin = true
""")import edgedb
from edgedb import Credentials
# Using credentials object
credentials = Credentials(
user="app_user",
password="secure_password"
)
client = edgedb.create_client(
host="db.example.com",
port=5656,
database="production",
credentials=credentials,
tls_security="strict",
max_concurrency=50,
timeout=30
)
# Load credentials from file
credentials = Credentials.from_file("/path/to/credentials.json")
client = edgedb.create_client(credentials=credentials)import edgedb
from typing import Tuple, Any
def custom_warning_handler(warnings: Tuple[edgedb.EdgeDBError, ...], result: Any) -> Any:
"""Custom warning handler that logs warnings."""
for warning in warnings:
print(f"Database warning: {warning}")
# Return result unchanged, or modify/raise exception as needed
return result
# Use warning handler in queries
client = edgedb.create_client()
result = client.query(
"SELECT deprecated_function()",
warning_handler=custom_warning_handler
)import edgedb
# Create complex state configuration
production_state = (
edgedb.State()
.with_default_module("production")
.with_module_aliases(
log="audit_log",
metrics="performance_metrics",
auth="user_authentication"
)
.with_config(
query_execution_timeout="60s",
idle_transaction_timeout="30s",
apply_access_policies=True
)
.with_globals(
environment="production",
region="us-west-2",
service_name="web_api"
)
)
# Development state with different settings
development_state = (
edgedb.State()
.with_default_module("dev")
.with_config(
query_execution_timeout="300s", # Longer timeout for debugging
apply_access_policies=False # Disable access policies
)
.with_globals(
environment="development",
debug_mode=True
)
)
# Use appropriate state based on environment
import os
current_state = production_state if os.getenv("ENV") == "prod" else development_state
client = edgedb.create_client().with_state(current_state)import edgedb
# Base organizational state
org_state = (
edgedb.State()
.with_default_module("organization")
.with_globals(
org_id="org_123",
data_classification="internal"
)
)
# Department-specific states inheriting from org state
sales_state = org_state.with_globals(
department="sales",
access_level="standard"
)
finance_state = org_state.with_globals(
department="finance",
access_level="restricted"
)
# User-specific state
user_state = sales_state.with_globals(
user_id="user_456",
role="manager"
)
# Each state inherits and extends the previous configuration
client = edgedb.create_client()
sales_data = client.with_state(sales_state).query("SELECT SalesRecord { * }")
finance_data = client.with_state(finance_state).query("SELECT FinancialRecord { * }")
user_data = client.with_state(user_state).query("SELECT UserSpecificData { * }")import edgedb
from typing import Optional
class StateManager:
"""Helper class for dynamic state management."""
def __init__(self, client: edgedb.Client):
self.client = client
self.base_state = edgedb.State()
def with_user_context(self, user_id: str, role: str) -> edgedb.Client:
"""Create client with user context."""
state = self.base_state.with_globals(
current_user_id=user_id,
current_user_role=role
)
return self.client.with_state(state)
def with_tenant_context(self, tenant_id: str) -> edgedb.Client:
"""Create client with tenant context."""
state = self.base_state.with_globals(tenant_id=tenant_id)
return self.client.with_state(state)
def with_request_context(
self,
user_id: str,
tenant_id: str,
request_id: Optional[str] = None
) -> edgedb.Client:
"""Create client with full request context."""
globals_dict = {
"current_user_id": user_id,
"tenant_id": tenant_id
}
if request_id:
globals_dict["request_id"] = request_id
state = self.base_state.with_globals(**globals_dict)
return self.client.with_state(state)
# Usage
client = edgedb.create_client()
state_manager = StateManager(client)
# Get context-aware client
user_client = state_manager.with_user_context("user_123", "admin")
tenant_client = state_manager.with_tenant_context("tenant_456")
request_client = state_manager.with_request_context(
"user_123", "tenant_456", "req_789"
)
# Each client has appropriate context for queries
user_data = user_client.query("SELECT data_for_current_user()")
tenant_data = tenant_client.query("SELECT tenant_specific_data()")Install with Tessl CLI
npx tessl i tessl/pypi-edgedb