0
# Configuration and Options
1
2
Client configuration options, session state management, connection parameters, and advanced client behavior control.
3
4
## Capabilities
5
6
### Session State Management
7
8
Control client session state including default modules, module aliases, configuration, and global variables.
9
10
```python { .api }
11
class State:
12
"""
13
Client session state management.
14
15
Manages module context, configuration settings, and global variables
16
for EdgeDB client sessions.
17
"""
18
19
def with_default_module(self, module: str) -> State:
20
"""
21
Create new state with default module.
22
23
Parameters:
24
- module: Module name to use as default
25
26
Returns:
27
New State instance with updated default module
28
"""
29
30
def without_default_module(self) -> State:
31
"""
32
Create new state without default module.
33
34
Returns:
35
New State instance with no default module
36
"""
37
38
def with_module_aliases(self, **aliases: str) -> State:
39
"""
40
Create new state with module aliases.
41
42
Parameters:
43
- **aliases: Module alias mappings (alias=module_name)
44
45
Returns:
46
New State instance with added module aliases
47
"""
48
49
def without_module_aliases(self, *aliases: str) -> State:
50
"""
51
Create new state without specified module aliases.
52
53
Parameters:
54
- *aliases: Alias names to remove
55
56
Returns:
57
New State instance with removed aliases
58
"""
59
60
def with_config(self, **config: Any) -> State:
61
"""
62
Create new state with configuration settings.
63
64
Parameters:
65
- **config: Configuration key-value pairs
66
67
Returns:
68
New State instance with updated configuration
69
"""
70
71
def without_config(self, *settings: str) -> State:
72
"""
73
Create new state without specified configuration settings.
74
75
Parameters:
76
- *settings: Configuration setting names to remove
77
78
Returns:
79
New State instance with removed settings
80
"""
81
82
def with_globals(self, **globals: Any) -> State:
83
"""
84
Create new state with global variables.
85
86
Parameters:
87
- **globals: Global variable key-value pairs
88
89
Returns:
90
New State instance with updated globals
91
"""
92
93
def without_globals(self, *globals: str) -> State:
94
"""
95
Create new state without specified global variables.
96
97
Parameters:
98
- *globals: Global variable names to remove
99
100
Returns:
101
New State instance with removed globals
102
"""
103
```
104
105
### Warning Handling
106
107
Configuration for handling query warnings and messages from the database.
108
109
```python { .api }
110
WarningHandler = Callable[[Tuple[EdgeDBError, ...], Any], Any]
111
"""
112
Type for warning handler functions.
113
114
Parameters:
115
- warnings: Tuple of warning messages from the database
116
- result: Query result that generated the warnings
117
118
Returns:
119
Potentially modified result or raises exception
120
"""
121
```
122
123
### Connection Credentials
124
125
Credential management for database authentication.
126
127
```python { .api }
128
class Credentials:
129
"""
130
Database connection credentials.
131
132
Encapsulates authentication information for EdgeDB connections.
133
"""
134
135
def __init__(
136
self,
137
*,
138
user: Optional[str] = None,
139
password: Optional[str] = None,
140
secret_key: Optional[str] = None
141
):
142
"""
143
Create credentials object.
144
145
Parameters:
146
- user: Database user name
147
- password: Database password
148
- secret_key: Secret key for JWT authentication
149
"""
150
151
@classmethod
152
def from_file(cls, path: str) -> Credentials:
153
"""
154
Load credentials from file.
155
156
Parameters:
157
- path: Path to credentials file
158
159
Returns:
160
Credentials object loaded from file
161
"""
162
```
163
164
### Enums and Constants
165
166
Configuration enums and constants for client behavior.
167
168
```python { .api }
169
class Cardinality(Enum):
170
"""
171
Query result cardinality enumeration.
172
173
Indicates the expected number of results from a query.
174
"""
175
NO_RESULT = "n" # Query returns no results
176
AT_MOST_ONE = "?" # Query returns 0 or 1 result
177
ONE = "1" # Query returns exactly 1 result
178
MANY = "*" # Query returns 0 or more results
179
AT_LEAST_ONE = "+" # Query returns 1 or more results
180
181
def is_single(self) -> bool:
182
"""Check if cardinality expects single result."""
183
184
def is_multi(self) -> bool:
185
"""Check if cardinality expects multiple results."""
186
187
class ElementKind(Enum):
188
"""
189
Schema element kind enumeration.
190
191
Identifies the type of schema element in introspection.
192
"""
193
LINK = "link"
194
PROPERTY = "property"
195
LINK_PROPERTY = "linkprop"
196
```
197
198
## Usage Examples
199
200
### Session State Management
201
202
```python
203
import edgedb
204
205
client = edgedb.create_client()
206
207
# Set default module
208
state = edgedb.State().with_default_module("blog")
209
210
# Query without explicitly qualifying types
211
posts = client.with_state(state).query("SELECT Post { title, content }")
212
# Equivalent to: SELECT blog::Post { title, content }
213
214
# Module aliases
215
state = edgedb.State().with_module_aliases(
216
auth="authentication",
217
blog="content_management"
218
)
219
220
users = client.with_state(state).query("SELECT auth::User { name }")
221
# Equivalent to: SELECT authentication::User { name }
222
```
223
224
### Configuration Settings
225
226
```python
227
import edgedb
228
229
client = edgedb.create_client()
230
231
# Set configuration
232
state = edgedb.State().with_config(
233
query_execution_timeout="30s",
234
idle_transaction_timeout="10s"
235
)
236
237
# Apply configuration to queries
238
result = client.with_state(state).query("SELECT expensive_computation()")
239
240
# Chain state modifications
241
state = (
242
edgedb.State()
243
.with_default_module("blog")
244
.with_config(query_execution_timeout="60s")
245
.with_module_aliases(auth="user_management")
246
)
247
248
client_with_state = client.with_state(state)
249
```
250
251
### Global Variables
252
253
```python
254
import edgedb
255
256
client = edgedb.create_client()
257
258
# Set global variables
259
state = edgedb.State().with_globals(
260
current_user_id="123e4567-e89b-12d3-a456-426614174000",
261
tenant_id="tenant_1"
262
)
263
264
# Use globals in queries
265
posts = client.with_state(state).query("""
266
SELECT Post {
267
title,
268
content,
269
author: { name }
270
}
271
FILTER .author.id = global current_user_id
272
""")
273
274
# Update globals
275
updated_state = state.with_globals(current_user_id="different-user-id")
276
```
277
278
### Persistent Client State
279
280
```python
281
import edgedb
282
283
# Create client with persistent state
284
base_state = (
285
edgedb.State()
286
.with_default_module("app")
287
.with_config(query_execution_timeout="30s")
288
.with_globals(app_version="1.0.0")
289
)
290
291
client = edgedb.create_client().with_state(base_state)
292
293
# All queries use the base state
294
users = client.query("SELECT User { name }") # Uses app::User
295
296
# Temporarily override state for specific queries
297
admin_state = base_state.with_globals(is_admin=True)
298
admin_users = client.with_state(admin_state).query("""
299
SELECT User { name, admin_notes }
300
FILTER global is_admin = true
301
""")
302
```
303
304
### Connection Configuration
305
306
```python
307
import edgedb
308
from edgedb import Credentials
309
310
# Using credentials object
311
credentials = Credentials(
312
user="app_user",
313
password="secure_password"
314
)
315
316
client = edgedb.create_client(
317
host="db.example.com",
318
port=5656,
319
database="production",
320
credentials=credentials,
321
tls_security="strict",
322
max_concurrency=50,
323
timeout=30
324
)
325
326
# Load credentials from file
327
credentials = Credentials.from_file("/path/to/credentials.json")
328
client = edgedb.create_client(credentials=credentials)
329
```
330
331
### Warning Handling
332
333
```python
334
import edgedb
335
from typing import Tuple, Any
336
337
def custom_warning_handler(warnings: Tuple[edgedb.EdgeDBError, ...], result: Any) -> Any:
338
"""Custom warning handler that logs warnings."""
339
for warning in warnings:
340
print(f"Database warning: {warning}")
341
342
# Return result unchanged, or modify/raise exception as needed
343
return result
344
345
# Use warning handler in queries
346
client = edgedb.create_client()
347
result = client.query(
348
"SELECT deprecated_function()",
349
warning_handler=custom_warning_handler
350
)
351
```
352
353
### Advanced State Combinations
354
355
```python
356
import edgedb
357
358
# Create complex state configuration
359
production_state = (
360
edgedb.State()
361
.with_default_module("production")
362
.with_module_aliases(
363
log="audit_log",
364
metrics="performance_metrics",
365
auth="user_authentication"
366
)
367
.with_config(
368
query_execution_timeout="60s",
369
idle_transaction_timeout="30s",
370
apply_access_policies=True
371
)
372
.with_globals(
373
environment="production",
374
region="us-west-2",
375
service_name="web_api"
376
)
377
)
378
379
# Development state with different settings
380
development_state = (
381
edgedb.State()
382
.with_default_module("dev")
383
.with_config(
384
query_execution_timeout="300s", # Longer timeout for debugging
385
apply_access_policies=False # Disable access policies
386
)
387
.with_globals(
388
environment="development",
389
debug_mode=True
390
)
391
)
392
393
# Use appropriate state based on environment
394
import os
395
current_state = production_state if os.getenv("ENV") == "prod" else development_state
396
client = edgedb.create_client().with_state(current_state)
397
```
398
399
### State Inheritance and Modification
400
401
```python
402
import edgedb
403
404
# Base organizational state
405
org_state = (
406
edgedb.State()
407
.with_default_module("organization")
408
.with_globals(
409
org_id="org_123",
410
data_classification="internal"
411
)
412
)
413
414
# Department-specific states inheriting from org state
415
sales_state = org_state.with_globals(
416
department="sales",
417
access_level="standard"
418
)
419
420
finance_state = org_state.with_globals(
421
department="finance",
422
access_level="restricted"
423
)
424
425
# User-specific state
426
user_state = sales_state.with_globals(
427
user_id="user_456",
428
role="manager"
429
)
430
431
# Each state inherits and extends the previous configuration
432
client = edgedb.create_client()
433
sales_data = client.with_state(sales_state).query("SELECT SalesRecord { * }")
434
finance_data = client.with_state(finance_state).query("SELECT FinancialRecord { * }")
435
user_data = client.with_state(user_state).query("SELECT UserSpecificData { * }")
436
```
437
438
### Dynamic State Management
439
440
```python
441
import edgedb
442
from typing import Optional
443
444
class StateManager:
445
"""Helper class for dynamic state management."""
446
447
def __init__(self, client: edgedb.Client):
448
self.client = client
449
self.base_state = edgedb.State()
450
451
def with_user_context(self, user_id: str, role: str) -> edgedb.Client:
452
"""Create client with user context."""
453
state = self.base_state.with_globals(
454
current_user_id=user_id,
455
current_user_role=role
456
)
457
return self.client.with_state(state)
458
459
def with_tenant_context(self, tenant_id: str) -> edgedb.Client:
460
"""Create client with tenant context."""
461
state = self.base_state.with_globals(tenant_id=tenant_id)
462
return self.client.with_state(state)
463
464
def with_request_context(
465
self,
466
user_id: str,
467
tenant_id: str,
468
request_id: Optional[str] = None
469
) -> edgedb.Client:
470
"""Create client with full request context."""
471
globals_dict = {
472
"current_user_id": user_id,
473
"tenant_id": tenant_id
474
}
475
if request_id:
476
globals_dict["request_id"] = request_id
477
478
state = self.base_state.with_globals(**globals_dict)
479
return self.client.with_state(state)
480
481
# Usage
482
client = edgedb.create_client()
483
state_manager = StateManager(client)
484
485
# Get context-aware client
486
user_client = state_manager.with_user_context("user_123", "admin")
487
tenant_client = state_manager.with_tenant_context("tenant_456")
488
request_client = state_manager.with_request_context(
489
"user_123", "tenant_456", "req_789"
490
)
491
492
# Each client has appropriate context for queries
493
user_data = user_client.query("SELECT data_for_current_user()")
494
tenant_data = tenant_client.query("SELECT tenant_specific_data()")
495
```