ydb 0.16.0

Crate contains generated low-level grpc code from YDB API protobuf, used as base for ydb crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
mod builders;
pub(crate) mod call_options;

use crate::errors::*;
use crate::session::TableSession;
use crate::session_pool::{SessionPool, TableSessionPool};
use crate::types::Value;

use crate::grpc_connection_manager::GrpcConnectionManager;

use crate::grpc_wrapper::grpc_limits::WithGrpcMaxMessageSize;
use crate::grpc_wrapper::raw_table_service::bulk_upsert::RawBulkUpsertRequest;
use crate::grpc_wrapper::raw_table_service::client::RawTableClient;
use crate::grpc_wrapper::raw_table_service::copy_table::{
    RawCopyTableRequest, RawCopyTablesRequest,
};
use crate::grpc_wrapper::raw_table_service::describe_table::{
    table_description_from_raw, RawDescribeTableRequest,
};
use crate::grpc_wrapper::raw_table_service::describe_table_options::{
    RawDescribeTableOptionsRequest, RawDescribeTableOptionsResult,
};
use crate::grpc_wrapper::raw_table_service::drop_table::RawDropTableRequest;
use crate::grpc_wrapper::raw_table_service::read_rows::RawReadRowsRequest;
use crate::grpc_wrapper::raw_table_service::rename_tables::{
    RawRenameTableItem, RawRenameTablesRequest,
};
use crate::grpc_wrapper::runtime_interceptors::InterceptedChannel;
use crate::session::CreateTableClient;
use crate::table_requests::{
    AlterTableRequest, CreateTableRequest, DropTableRequest, ReadRowsRequest,
    TableOptionsDescription,
};
use crate::table_service_types::{CopyTableItem, RenameTableItem, TableDescription};
use crate::types_converters::try_vec_to_list_of_structs;
use itertools::Itertools;
use ydb_grpc::ydb_proto::table::v1::table_service_client::TableServiceClient;

pub use builders::{
    AlterTableBuilder, BulkUpsertBuilder, CopyTableBuilder, CopyTablesBuilder, CreateTableBuilder,
    DescribeTableBuilder, DescribeTableOptionsBuilder, DropTableBuilder, ReadRowsBuilder,
    RenameTableBuilder, RenameTablesBuilder,
};

use call_options::{resolve_timeouts, retry_table_operation, TableCallOptions};

pub(crate) type TableServiceClientType = TableServiceClient<InterceptedChannel>;

impl WithGrpcMaxMessageSize for TableServiceClientType {
    fn with_grpc_max_message_size(self, bytes: usize) -> Self {
        self.max_decoding_message_size(bytes)
            .max_encoding_message_size(bytes)
    }
}

/// Client for YDB Table service: DDL via RPC (`CreateTable`, …), sessionless data plane (`ReadRows`, `BulkUpsert`), describe.
///
/// Ad-hoc DDL YQL (`CREATE TABLE` / `DROP TABLE` as text) belongs to [`crate::QueryClient::exec`] with [`crate::TxMode::Implicit`].
/// YQL execution, transactions, explain, and streaming reads also belong to [`crate::QueryClient`].
///
/// Per-call timeouts are set on operation builders, e.g.
/// `table_client.read_rows(path, keys, None).timeout(Duration::from_secs(1)).await`.
#[derive(Clone)]
pub struct TableClient {
    session_pool: TableSessionPool,
}

impl TableClient {
    pub(crate) fn new(
        connection_manager: GrpcConnectionManager,
        session_pool: SessionPool,
        retry_control: std::sync::Arc<crate::retry_budget::RetryControl>,
    ) -> Self {
        Self {
            session_pool: TableSessionPool::from_shared(
                session_pool,
                connection_manager,
                retry_control,
            ),
        }
    }

    pub(crate) async fn create_session_with_opts(
        &self,
        opts: &TableCallOptions,
    ) -> YdbResult<TableSession> {
        let timeouts = resolve_timeouts(opts);
        Ok(self.session_pool.session().await?.with_timeouts(timeouts))
    }

    async fn sessionless_table_client(&self, opts: &TableCallOptions) -> YdbResult<RawTableClient> {
        self.session_pool
            .connection_manager()
            .create_table_client(resolve_timeouts(opts))
            .await
    }

    async fn bulk_upsert_once(
        &self,
        table_path: String,
        rows: Value,
        opts: &TableCallOptions,
    ) -> YdbResult<()> {
        let raw_rows: crate::grpc_wrapper::raw_table_service::value::RawTypedValue =
            rows.try_into().map_err(YdbError::from)?;
        let mut client = self.sessionless_table_client(opts).await?;
        client
            .bulk_upsert(RawBulkUpsertRequest {
                table: table_path,
                rows: raw_rows.into(),
                operation_params: resolve_timeouts(opts).operation_params(),
            })
            .await
            .map_err(YdbError::from)?;
        Ok(())
    }

    async fn read_rows_once(
        &self,
        request: RawReadRowsRequest,
        opts: &TableCallOptions,
    ) -> YdbResult<crate::ResultSet> {
        let mut client = self.sessionless_table_client(opts).await?;
        let raw_response = client.read_rows(request).await.map_err(YdbError::from)?;
        raw_response.result_set.try_into()
    }

    /// Read rows by primary key without opening a session (go-sdk: `table.Client.ReadRows`).
    ///
    /// `keys` must be a list of [`Value::Struct`] primary-key values.
    /// Returns an empty result set when `keys` is empty.
    pub fn read_rows(
        &self,
        table_path: impl Into<String>,
        keys: Vec<Value>,
        columns: Option<Vec<String>>,
    ) -> ReadRowsBuilder<'_> {
        ReadRowsBuilder {
            client: self,
            table_path: table_path.into(),
            keys,
            columns,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn read_rows_call(
        &self,
        table_path: String,
        keys: Vec<Value>,
        columns: Option<Vec<String>>,
        opts: TableCallOptions,
    ) -> YdbResult<crate::ResultSet> {
        if keys.is_empty() {
            return Ok(crate::ResultSet::default());
        }

        let mut request = ReadRowsRequest::new(table_path).with_keys(keys);
        if let Some(columns) = columns {
            request.columns = columns;
        }
        let raw = request.into_raw(String::new())?;
        retry_table_operation(self.session_pool.retry_control(), &opts, true, || async {
            self.read_rows_once(raw.clone(), &opts).await
        })
        .await
    }

    /// Bulk upsert rows without opening a session (go-sdk: `table.Client.BulkUpsert`).
    pub fn bulk_upsert(
        &self,
        table_path: impl Into<String>,
        rows: Vec<Value>,
    ) -> BulkUpsertBuilder<'_> {
        BulkUpsertBuilder {
            client: self,
            table_path: table_path.into(),
            rows,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn bulk_upsert_call(
        &self,
        table_path: String,
        rows: Vec<Value>,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        let Some(value) = try_vec_to_list_of_structs(rows)? else {
            return Ok(());
        };
        retry_table_operation(self.session_pool.retry_control(), &opts, true, || async {
            self.bulk_upsert_once(table_path.clone(), value.clone(), &opts)
                .await
        })
        .await
    }

    pub fn copy_table(
        &self,
        source_path: String,
        destination_path: String,
    ) -> CopyTableBuilder<'_> {
        CopyTableBuilder {
            client: self,
            source_path,
            destination_path,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn copy_table_call(
        &self,
        source_path: String,
        destination_path: String,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let session_id = session.id.clone();
            let operation_params = session.operation_params();
            session
                .in_flight_rpc(async |table| {
                    table
                        .copy_table(RawCopyTableRequest {
                            session_id,
                            source_path: source_path.clone(),
                            destination_path: destination_path.clone(),
                            operation_params,
                        })
                        .await
                })
                .await
        })
        .await
    }

    pub fn copy_tables(&self, tables: Vec<CopyTableItem>) -> CopyTablesBuilder<'_> {
        CopyTablesBuilder {
            client: self,
            tables,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn copy_tables_call(
        &self,
        tables: Vec<CopyTableItem>,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let session_id = session.id.clone();
            let operation_params = session.operation_params();
            session
                .in_flight_rpc(async |table| {
                    table
                        .copy_tables(RawCopyTablesRequest {
                            operation_params,
                            session_id,
                            tables: tables.clone().into_iter().map_into().collect(),
                        })
                        .await
                })
                .await
        })
        .await
    }

    pub fn rename_table(
        &self,
        source_path: String,
        destination_path: String,
        replace_destination: bool,
    ) -> RenameTableBuilder<'_> {
        RenameTableBuilder {
            client: self,
            source_path,
            destination_path,
            replace_destination,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn rename_table_call(
        &self,
        source_path: String,
        destination_path: String,
        replace_destination: bool,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let session_id = session.id.clone();
            let operation_params = session.operation_params();
            session
                .in_flight_rpc(async |table| {
                    table
                        .rename_tables(RawRenameTablesRequest {
                            session_id,
                            operation_params,
                            tables: vec![RawRenameTableItem {
                                source_path: source_path.clone(),
                                destination_path: destination_path.clone(),
                                replace_destination,
                            }],
                        })
                        .await
                })
                .await
        })
        .await
    }

    pub fn rename_tables(&self, tables: Vec<RenameTableItem>) -> RenameTablesBuilder<'_> {
        RenameTablesBuilder {
            client: self,
            tables,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn rename_tables_call(
        &self,
        tables: Vec<RenameTableItem>,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let session_id = session.id.clone();
            let operation_params = session.operation_params();
            session
                .in_flight_rpc(async |table| {
                    table
                        .rename_tables(RawRenameTablesRequest {
                            operation_params,
                            session_id,
                            tables: tables.clone().into_iter().map_into().collect(),
                        })
                        .await
                })
                .await
        })
        .await
    }

    pub fn describe_table(&self, path: String) -> DescribeTableBuilder<'_> {
        DescribeTableBuilder {
            client: self,
            path,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn describe_table_call(
        &self,
        path: String,
        opts: TableCallOptions,
    ) -> YdbResult<TableDescription> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let session_id = session.id.clone();
            let operation_params = session.operation_params();
            let raw = session
                .in_flight_rpc(async |table| {
                    table
                        .describe_table(RawDescribeTableRequest {
                            session_id,
                            path: path.clone(),
                            operation_params,
                        })
                        .await
                })
                .await?;
            table_description_from_raw(raw).map_err(|e| YdbError::custom(e.error))
        })
        .await
    }

    /// Create a table via `CreateTable` RPC.
    pub fn create_table(&self, request: CreateTableRequest) -> CreateTableBuilder<'_> {
        CreateTableBuilder {
            client: self,
            request,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn create_table_call(
        &self,
        request: CreateTableRequest,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let raw = request
                .clone()
                .into_raw(session.id.clone(), session.operation_params())?;
            session
                .in_flight_rpc(async |table| table.create_table(raw).await)
                .await
        })
        .await
    }

    /// Drop a table via `DropTable` RPC.
    pub fn drop_table(&self, request: DropTableRequest) -> DropTableBuilder<'_> {
        DropTableBuilder {
            client: self,
            request,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn drop_table_call(
        &self,
        request: DropTableRequest,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let req = RawDropTableRequest {
                session_id: session.id.clone(),
                path: request.path.clone(),
                operation_params: session.operation_params(),
            };
            session
                .in_flight_rpc(async |table| table.drop_table(req).await)
                .await
        })
        .await
    }

    /// Alter a table via `AlterTable` RPC (columns, attributes, etc.).
    pub fn alter_table(&self, request: AlterTableRequest) -> AlterTableBuilder<'_> {
        AlterTableBuilder {
            client: self,
            request,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn alter_table_call(
        &self,
        request: AlterTableRequest,
        opts: TableCallOptions,
    ) -> YdbResult<()> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let raw = request
                .clone()
                .into_raw(session.id.clone(), session.operation_params())?;
            session
                .in_flight_rpc(async |table| table.alter_table(raw).await)
                .await
        })
        .await
    }

    /// Describe cluster-wide table option presets.
    pub fn describe_table_options(&self) -> DescribeTableOptionsBuilder<'_> {
        DescribeTableOptionsBuilder {
            client: self,
            opts: TableCallOptions::default(),
        }
    }

    pub(crate) async fn describe_table_options_call(
        &self,
        opts: TableCallOptions,
    ) -> YdbResult<TableOptionsDescription> {
        retry_table_operation(self.session_pool.retry_control(), &opts, false, || async {
            let mut session = self.create_session_with_opts(&opts).await?;
            let req = RawDescribeTableOptionsRequest {
                operation_params: session.operation_params(),
            };
            let raw: RawDescribeTableOptionsResult = session
                .in_flight_rpc(async |table| table.describe_table_options(req).await)
                .await?;
            Ok(raw.into())
        })
        .await
    }
}