0
# Query Service Operations
1
2
Modern query interface supporting session management, transaction execution, result streaming, and advanced query options with the new Query service.
3
4
## Capabilities
5
6
### Query Service Client
7
8
The Query service provides a modern interface for executing YQL queries with advanced features like streaming results and transaction management.
9
10
```python { .api }
11
class QueryClientSync:
12
def __init__(self, driver: Driver, query_client_settings: QueryClientSettings = None):
13
"""
14
Create a query service client for modern YQL query execution.
15
16
Args:
17
driver (Driver): YDB driver instance
18
query_client_settings (QueryClientSettings, optional): Client configuration
19
"""
20
21
def session(self) -> QuerySession:
22
"""
23
Create a new query session.
24
25
Returns:
26
QuerySession: New query session instance
27
"""
28
29
class QueryClientSettings:
30
def __init__(self, timeout: float = None):
31
"""
32
Configuration settings for query client.
33
34
Args:
35
timeout (float, optional): Default timeout for operations
36
"""
37
```
38
39
### Query Sessions
40
41
Query sessions provide the execution context for YQL queries with transaction management and result streaming.
42
43
```python { .api }
44
class QuerySession:
45
def __init__(self, driver: Driver, settings: QueryClientSettings = None):
46
"""
47
Create a query session for executing YQL queries.
48
49
Args:
50
driver (Driver): YDB driver instance
51
settings (QueryClientSettings, optional): Session configuration
52
"""
53
54
def execute_query(
55
self,
56
query: str,
57
parameters: Dict[str, Any] = None,
58
tx_control: QueryTxControl = None,
59
settings: ExecuteQuerySettings = None
60
) -> Iterator[ResultSet]:
61
"""
62
Execute YQL query with parameters and transaction control.
63
64
Args:
65
query (str): YQL query text
66
parameters (Dict[str, Any], optional): Query parameters
67
tx_control (QueryTxControl, optional): Transaction control settings
68
settings (ExecuteQuerySettings, optional): Execution settings
69
70
Returns:
71
Iterator[ResultSet]: Query result sets
72
"""
73
74
def transaction(self, tx_settings: QueryTxSettings = None) -> QueryTxContext:
75
"""
76
Begin a new transaction for multiple operations.
77
78
Args:
79
tx_settings (QueryTxSettings, optional): Transaction settings
80
81
Returns:
82
QueryTxContext: Transaction context manager
83
"""
84
85
def close(self):
86
"""
87
Close the query session and release resources.
88
"""
89
90
class ExecuteQuerySettings:
91
def __init__(
92
self,
93
trace_id: str = None,
94
request_type: str = None,
95
stats_mode: QueryStatsMode = None,
96
exec_mode: QueryExecMode = None,
97
syntax: QuerySyntax = None
98
):
99
"""
100
Settings for query execution.
101
102
Args:
103
trace_id (str, optional): Request tracing identifier
104
request_type (str, optional): Request type for logging
105
stats_mode (QueryStatsMode, optional): Statistics collection mode
106
exec_mode (QueryExecMode, optional): Query execution mode
107
syntax (QuerySyntax, optional): Query syntax version
108
"""
109
```
110
111
### Query Transactions
112
113
Transaction context for executing multiple queries within a single transaction scope.
114
115
```python { .api }
116
class QueryTxContext:
117
def __init__(self, session: QuerySession, tx_settings: QueryTxSettings = None):
118
"""
119
Transaction context for query execution.
120
121
Args:
122
session (QuerySession): Parent query session
123
tx_settings (QueryTxSettings, optional): Transaction settings
124
"""
125
126
def execute(
127
self,
128
query: str,
129
parameters: Dict[str, Any] = None,
130
settings: ExecuteQuerySettings = None
131
) -> Iterator[ResultSet]:
132
"""
133
Execute query within the transaction.
134
135
Args:
136
query (str): YQL query text
137
parameters (Dict[str, Any], optional): Query parameters
138
settings (ExecuteQuerySettings, optional): Execution settings
139
140
Returns:
141
Iterator[ResultSet]: Query result sets
142
"""
143
144
def commit(self):
145
"""
146
Commit the transaction.
147
"""
148
149
def rollback(self):
150
"""
151
Rollback the transaction.
152
"""
153
154
def __enter__(self) -> 'QueryTxContext':
155
"""
156
Enter transaction context.
157
"""
158
159
def __exit__(self, exc_type, exc_val, exc_tb):
160
"""
161
Exit transaction context with automatic commit/rollback.
162
"""
163
164
class QueryTxSettings:
165
def __init__(self, tx_mode: BaseQueryTxMode = None):
166
"""
167
Transaction settings for query operations.
168
169
Args:
170
tx_mode (BaseQueryTxMode, optional): Transaction isolation mode
171
"""
172
```
173
174
### Query Session Pool
175
176
Pool management for query sessions with automatic lifecycle management.
177
178
```python { .api }
179
class QuerySessionPool:
180
def __init__(
181
self,
182
driver: Driver,
183
size: int = None,
184
query_client_settings: QueryClientSettings = None
185
):
186
"""
187
Pool of query sessions for efficient resource management.
188
189
Args:
190
driver (Driver): YDB driver instance
191
size (int, optional): Maximum pool size
192
query_client_settings (QueryClientSettings, optional): Default client settings
193
"""
194
195
def acquire(self, timeout: float = None) -> QuerySession:
196
"""
197
Acquire a query session from the pool.
198
199
Args:
200
timeout (float, optional): Acquisition timeout
201
202
Returns:
203
QuerySession: Available query session
204
"""
205
206
def release(self, session: QuerySession):
207
"""
208
Release query session back to the pool.
209
210
Args:
211
session (QuerySession): Session to release
212
"""
213
214
def retry_operation(
215
self,
216
callee: Callable[[QuerySession], Any],
217
retry_settings: RetrySettings = None,
218
*args,
219
**kwargs
220
) -> Any:
221
"""
222
Execute operation with automatic retry and session management.
223
224
Args:
225
callee (Callable): Function to execute with session as first argument
226
retry_settings (RetrySettings, optional): Custom retry configuration
227
*args: Additional arguments for callee
228
**kwargs: Additional keyword arguments for callee
229
230
Returns:
231
Any: Result of callee execution
232
"""
233
234
def stop(self, timeout: float = None):
235
"""
236
Stop the session pool and close all sessions.
237
238
Args:
239
timeout (float, optional): Shutdown timeout
240
"""
241
```
242
243
### Transaction Modes
244
245
Transaction isolation modes for query operations.
246
247
```python { .api }
248
class BaseQueryTxMode:
249
"""Base class for query transaction modes."""
250
251
class QuerySerializableReadWrite(BaseQueryTxMode):
252
"""Serializable read-write transaction mode."""
253
254
class QueryOnlineReadOnly(BaseQueryTxMode):
255
def __init__(self, allow_inconsistent_reads: bool = False):
256
"""
257
Online read-only transaction mode.
258
259
Args:
260
allow_inconsistent_reads (bool): Allow reading inconsistent data
261
"""
262
263
class QuerySnapshotReadOnly(BaseQueryTxMode):
264
"""Snapshot read-only transaction mode."""
265
266
class QueryStaleReadOnly(BaseQueryTxMode):
267
"""Stale read-only transaction mode."""
268
269
class QueryTxControl:
270
def __init__(
271
self,
272
tx_mode: BaseQueryTxMode = None,
273
commit_tx: bool = False,
274
begin_tx: bool = True
275
):
276
"""
277
Transaction control settings for individual queries.
278
279
Args:
280
tx_mode (BaseQueryTxMode, optional): Transaction mode
281
commit_tx (bool): Commit transaction after query execution
282
begin_tx (bool): Begin new transaction if none exists
283
"""
284
```
285
286
### Query Results
287
288
Result handling for query execution with streaming and metadata support.
289
290
```python { .api }
291
class ResultSet:
292
def __init__(self, result_data, columns):
293
"""
294
Query result set with rows and metadata.
295
296
Args:
297
result_data: Raw result data
298
columns: Column metadata
299
"""
300
301
@property
302
def columns(self) -> List[Column]:
303
"""
304
Get column metadata for the result set.
305
306
Returns:
307
List[Column]: Column definitions
308
"""
309
310
@property
311
def rows(self) -> Iterator[Row]:
312
"""
313
Iterate over result rows.
314
315
Returns:
316
Iterator[Row]: Result row iterator
317
"""
318
319
def fetch_all(self) -> List[Row]:
320
"""
321
Fetch all remaining rows from the result set.
322
323
Returns:
324
List[Row]: All remaining rows
325
"""
326
327
class Column:
328
def __init__(self, name: str, type: Type):
329
"""
330
Column metadata for result sets.
331
332
Args:
333
name (str): Column name
334
type (Type): YDB column type
335
"""
336
337
@property
338
def name(self) -> str:
339
"""Column name."""
340
341
@property
342
def type(self) -> Type:
343
"""Column YDB type."""
344
345
class Row:
346
def __getitem__(self, key: Union[int, str]) -> Any:
347
"""
348
Access row values by index or column name.
349
350
Args:
351
key (Union[int, str]): Column index or name
352
353
Returns:
354
Any: Column value
355
"""
356
357
def __getattr__(self, name: str) -> Any:
358
"""
359
Access row values by column name as attributes.
360
361
Args:
362
name (str): Column name
363
364
Returns:
365
Any: Column value
366
"""
367
```
368
369
### Query Options
370
371
Configuration options for query execution behavior.
372
373
```python { .api }
374
class QueryStatsMode(enum.Enum):
375
"""Statistics collection modes for query execution."""
376
NONE = "none"
377
BASIC = "basic"
378
FULL = "full"
379
PROFILE = "profile"
380
381
class QueryExecMode(enum.Enum):
382
"""Query execution modes."""
383
PARSE = "parse"
384
VALIDATE = "validate"
385
EXPLAIN = "explain"
386
EXECUTE = "execute"
387
388
class QuerySyntax(enum.Enum):
389
"""Query syntax versions."""
390
YQL_V1 = "yql_v1"
391
PG = "pg"
392
393
class QueryExplainResultFormat(enum.Enum):
394
"""Explain result format options."""
395
TEXT = "text"
396
JSON = "json"
397
```
398
399
## Usage Examples
400
401
### Basic Query Execution
402
403
```python
404
import ydb
405
406
# Create driver and query client
407
driver = ydb.Driver(endpoint="grpc://localhost:2136", database="/local")
408
query_client = ydb.QueryClientSync(driver)
409
410
# Execute simple query
411
session = query_client.session()
412
try:
413
result_sets = session.execute_query("SELECT 1 AS value")
414
for result_set in result_sets:
415
for row in result_set.rows:
416
print(f"Value: {row.value}")
417
finally:
418
session.close()
419
```
420
421
### Parameterized Queries
422
423
```python
424
# Execute query with parameters
425
parameters = {"$user_id": 123, "$status": "active"}
426
query = """
427
SELECT name, email
428
FROM users
429
WHERE user_id = $user_id AND status = $status
430
"""
431
432
result_sets = session.execute_query(query, parameters=parameters)
433
for result_set in result_sets:
434
for row in result_set.rows:
435
print(f"User: {row.name}, Email: {row.email}")
436
```
437
438
### Transaction Management
439
440
```python
441
# Execute multiple queries in a transaction
442
with session.transaction(QueryTxSettings(QuerySerializableReadWrite())) as tx:
443
# Update user status
444
tx.execute(
445
"UPDATE users SET status = 'inactive' WHERE user_id = $user_id",
446
parameters={"$user_id": 123}
447
)
448
449
# Log the change
450
tx.execute(
451
"INSERT INTO audit_log (user_id, action, timestamp) VALUES ($user_id, $action, $ts)",
452
parameters={
453
"$user_id": 123,
454
"$action": "deactivate",
455
"$ts": datetime.utcnow()
456
}
457
)
458
# Transaction automatically commits on context exit
459
```
460
461
### Query Session Pool
462
463
```python
464
# Use session pool for better resource management
465
pool = ydb.QuerySessionPool(driver, size=10)
466
467
def execute_user_query(session, user_id):
468
result_sets = session.execute_query(
469
"SELECT * FROM users WHERE user_id = $user_id",
470
parameters={"$user_id": user_id}
471
)
472
return list(result_sets[0].rows)
473
474
# Execute with automatic retry and session management
475
try:
476
users = pool.retry_operation(execute_user_query, None, 123)
477
print(f"Found {len(users)} users")
478
finally:
479
pool.stop()
480
```
481
482
### Advanced Query Options
483
484
```python
485
# Execute with statistics and explain
486
settings = ydb.ExecuteQuerySettings(
487
stats_mode=ydb.QueryStatsMode.FULL,
488
exec_mode=ydb.QueryExecMode.EXPLAIN,
489
syntax=ydb.QuerySyntax.YQL_V1
490
)
491
492
result_sets = session.execute_query(
493
"SELECT COUNT(*) FROM large_table",
494
settings=settings
495
)
496
```
497
498
## Type Definitions
499
500
```python { .api }
501
# Type aliases for common patterns
502
QueryParameters = Dict[str, Any]
503
QueryResult = Iterator[ResultSet]
504
QueryCallback = Callable[[QuerySession], Any]
505
506
# Common transaction modes
507
SerializableRW = QuerySerializableReadWrite
508
OnlineRO = QueryOnlineReadOnly
509
SnapshotRO = QuerySnapshotReadOnly
510
StaleRO = QueryStaleReadOnly
511
```