0
# Query Execution
1
2
Core query execution methods for EdgeQL queries with support for different result cardinalities, JSON output formats, and parameter binding.
3
4
## Capabilities
5
6
### Query Methods
7
8
Execute EdgeQL queries with different expected result cardinalities and output formats.
9
10
```python { .api }
11
def query(
12
query: str,
13
*args,
14
**kwargs
15
) -> List[Any]:
16
"""
17
Execute a query and return all results as a list.
18
19
Parameters:
20
- query: EdgeQL query string
21
- *args: Positional query arguments
22
- **kwargs: Named query arguments
23
24
Returns:
25
List of query results, empty list if no results
26
27
Raises:
28
- EdgeDBError: For query execution errors
29
- QueryArgumentError: For invalid arguments
30
"""
31
32
def query_single(
33
query: str,
34
*args,
35
**kwargs
36
) -> Optional[Any]:
37
"""
38
Execute a query expecting at most one result.
39
40
Parameters:
41
- query: EdgeQL query string
42
- *args: Positional query arguments
43
- **kwargs: Named query arguments
44
45
Returns:
46
Single query result or None if no results
47
48
Raises:
49
- EdgeDBError: For query execution errors
50
- ResultCardinalityMismatchError: If query returns more than one result
51
- QueryArgumentError: For invalid arguments
52
"""
53
54
def query_required_single(
55
query: str,
56
*args,
57
**kwargs
58
) -> Any:
59
"""
60
Execute a query expecting exactly one result.
61
62
Parameters:
63
- query: EdgeQL query string
64
- *args: Positional query arguments
65
- **kwargs: Named query arguments
66
67
Returns:
68
Single query result
69
70
Raises:
71
- EdgeDBError: For query execution errors
72
- NoDataError: If query returns no results
73
- ResultCardinalityMismatchError: If query returns more than one result
74
- QueryArgumentError: For invalid arguments
75
"""
76
77
def query_json(
78
query: str,
79
*args,
80
**kwargs
81
) -> str:
82
"""
83
Execute a query and return results as JSON string.
84
85
Parameters:
86
- query: EdgeQL query string
87
- *args: Positional query arguments
88
- **kwargs: Named query arguments
89
90
Returns:
91
JSON string containing query results
92
93
Raises:
94
- EdgeDBError: For query execution errors
95
- QueryArgumentError: For invalid arguments
96
"""
97
98
def query_single_json(
99
query: str,
100
*args,
101
**kwargs
102
) -> str:
103
"""
104
Execute a query expecting at most one result as JSON.
105
106
Parameters:
107
- query: EdgeQL query string
108
- *args: Positional query arguments
109
- **kwargs: Named query arguments
110
111
Returns:
112
JSON string containing single result or null
113
114
Raises:
115
- EdgeDBError: For query execution errors
116
- ResultCardinalityMismatchError: If query returns more than one result
117
- QueryArgumentError: For invalid arguments
118
"""
119
120
def query_required_single_json(
121
query: str,
122
*args,
123
**kwargs
124
) -> str:
125
"""
126
Execute a query expecting exactly one result as JSON.
127
128
Parameters:
129
- query: EdgeQL query string
130
- *args: Positional query arguments
131
- **kwargs: Named query arguments
132
133
Returns:
134
JSON string containing single result
135
136
Raises:
137
- EdgeDBError: For query execution errors
138
- NoDataError: If query returns no results
139
- ResultCardinalityMismatchError: If query returns more than one result
140
- QueryArgumentError: For invalid arguments
141
"""
142
143
def execute(
144
query: str,
145
*args,
146
**kwargs
147
) -> None:
148
"""
149
Execute a command that doesn't return data.
150
151
Used for INSERT, UPDATE, DELETE, DDL commands, etc.
152
153
Parameters:
154
- query: EdgeQL command string
155
- *args: Positional query arguments
156
- **kwargs: Named query arguments
157
158
Returns:
159
None
160
161
Raises:
162
- EdgeDBError: For command execution errors
163
- QueryArgumentError: For invalid arguments
164
"""
165
```
166
167
### Query Context and Options
168
169
Query execution context and options for controlling query behavior.
170
171
```python { .api }
172
class QueryContext(NamedTuple):
173
"""Context for query execution."""
174
query: str
175
cache: QueryCache
176
query_options: Optional[Any]
177
retry_options: Optional[RetryOptions]
178
state: Optional[State]
179
warning_handler: Optional[WarningHandler]
180
181
class ExecuteContext(NamedTuple):
182
"""Context for command execution."""
183
query: str
184
cache: QueryCache
185
state: Optional[State]
186
warning_handler: Optional[WarningHandler]
187
188
class QueryWithArgs(NamedTuple):
189
"""Query with its arguments."""
190
query: str
191
args: Tuple
192
kwargs: Dict[str, Any]
193
194
class QueryCache(NamedTuple):
195
"""Query cache entry for prepared statements."""
196
# Implementation details vary
197
```
198
199
## Usage Examples
200
201
### Basic Queries
202
203
```python
204
import edgedb
205
206
client = edgedb.create_client()
207
208
# Query multiple results
209
users = client.query("SELECT User { name, email }")
210
print(f"Found {len(users)} users")
211
212
# Query single result (optional)
213
user = client.query_single("SELECT User { name } FILTER .id = <uuid>$id",
214
id="123e4567-e89b-12d3-a456-426614174000")
215
if user:
216
print(f"User: {user.name}")
217
218
# Query single result (required)
219
admin = client.query_required_single("SELECT User { name } FILTER .role = 'admin'")
220
print(f"Admin: {admin.name}")
221
```
222
223
### Parameterized Queries
224
225
```python
226
import edgedb
227
228
client = edgedb.create_client()
229
230
# Using positional arguments
231
users = client.query(
232
"SELECT User { name, email } FILTER .age > $0 AND .city = $1",
233
25, "New York"
234
)
235
236
# Using named arguments
237
users = client.query(
238
"SELECT User { name, email } FILTER .age > $min_age AND .city = $city",
239
min_age=25,
240
city="New York"
241
)
242
243
# Mixed arguments
244
user = client.query_single(
245
"SELECT User { name, email } FILTER .id = $0 AND .active = $active",
246
"123e4567-e89b-12d3-a456-426614174000",
247
active=True
248
)
249
```
250
251
### JSON Queries
252
253
```python
254
import edgedb
255
import json
256
257
client = edgedb.create_client()
258
259
# Get results as JSON string
260
users_json = client.query_json("SELECT User { name, email, created_at }")
261
users_data = json.loads(users_json)
262
263
# Single result as JSON
264
user_json = client.query_single_json(
265
"SELECT User { name, email, profile } FILTER .id = <uuid>$id",
266
id="123e4567-e89b-12d3-a456-426614174000"
267
)
268
if user_json != "null":
269
user_data = json.loads(user_json)
270
```
271
272
### Execute Commands
273
274
```python
275
import edgedb
276
277
client = edgedb.create_client()
278
279
# Insert data
280
client.execute(
281
"INSERT User { name := $name, email := $email, age := $age }",
282
name="John Doe",
283
email="john@example.com",
284
age=30
285
)
286
287
# Update data
288
client.execute(
289
"UPDATE User FILTER .email = $email SET { age := $new_age }",
290
email="john@example.com",
291
new_age=31
292
)
293
294
# Delete data
295
client.execute(
296
"DELETE User FILTER .email = $email",
297
email="john@example.com"
298
)
299
300
# DDL commands
301
client.execute("""
302
CREATE TYPE Article {
303
title: str;
304
content: str;
305
author: User;
306
created_at: datetime {
307
default := datetime_current();
308
};
309
}
310
""")
311
```
312
313
### Async Query Execution
314
315
```python
316
import asyncio
317
import edgedb
318
319
async def main():
320
client = edgedb.create_async_client()
321
322
# All query methods have async versions
323
users = await client.query("SELECT User { name, email }")
324
user = await client.query_single("SELECT User FILTER .id = <uuid>$id",
325
id="123e4567-e89b-12d3-a456-426614174000")
326
327
await client.execute(
328
"INSERT User { name := $name, email := $email }",
329
name="Alice Smith",
330
email="alice@example.com"
331
)
332
333
await client.aclose()
334
335
asyncio.run(main())
336
```
337
338
### Complex Queries
339
340
```python
341
import edgedb
342
343
client = edgedb.create_client()
344
345
# Complex query with nested selections
346
articles = client.query("""
347
SELECT Article {
348
title,
349
content,
350
author: { name, email },
351
tags: { name },
352
comment_count := count(.comments),
353
created_at
354
}
355
FILTER .published = true
356
ORDER BY .created_at DESC
357
LIMIT 10
358
""")
359
360
# Query with computed properties
361
user_stats = client.query("""
362
SELECT User {
363
name,
364
email,
365
article_count := count(.articles),
366
latest_article := (
367
SELECT .articles {
368
title,
369
created_at
370
}
371
ORDER BY .created_at DESC
372
LIMIT 1
373
),
374
total_comments := sum(.articles.comment_count)
375
}
376
FILTER .active = true
377
""")
378
```
379
380
### Error Handling
381
382
```python
383
import edgedb
384
385
client = edgedb.create_client()
386
387
try:
388
user = client.query_required_single(
389
"SELECT User { name } FILTER .email = $email",
390
email="nonexistent@example.com"
391
)
392
except edgedb.NoDataError:
393
print("User not found")
394
except edgedb.ResultCardinalityMismatchError:
395
print("Multiple users found with same email")
396
except edgedb.QueryError as e:
397
print(f"Query error: {e}")
398
except edgedb.EdgeDBError as e:
399
print(f"Database error: {e}")
400
```