-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathtable.rs
More file actions
2607 lines (2335 loc) · 89.8 KB
/
table.rs
File metadata and controls
2607 lines (2335 loc) · 89.8 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::TOKIO_RUNTIME;
use crate::*;
use arrow::array::RecordBatch as ArrowRecordBatch;
use arrow_pyarrow::{FromPyArrow, ToPyArrow};
use arrow_schema::SchemaRef;
use fluss::record::to_arrow_schema;
use fluss::rpc::message::OffsetSpec;
use indexmap::IndexMap;
use pyo3::IntoPyObjectExt;
use pyo3::exceptions::{PyIndexError, PyRuntimeError, PyTypeError};
use pyo3::sync::PyOnceLock;
use pyo3::types::{
IntoPyDict, PyBool, PyByteArray, PyBytes, PyDate, PyDateAccess, PyDateTime, PyDelta,
PyDeltaAccess, PyDict, PyList, PySequence, PySlice, PyTime, PyTimeAccess, PyTuple, PyType,
PyTzInfo,
};
use pyo3_async_runtimes::tokio::future_into_py;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
// Time conversion constants
const MILLIS_PER_SECOND: i64 = 1_000;
const MILLIS_PER_MINUTE: i64 = 60_000;
const MILLIS_PER_HOUR: i64 = 3_600_000;
const MICROS_PER_MILLI: i64 = 1_000;
const MICROS_PER_SECOND: i64 = 1_000_000;
const MICROS_PER_DAY: i64 = 86_400_000_000;
const NANOS_PER_MILLI: i64 = 1_000_000;
const NANOS_PER_MICRO: i64 = 1_000;
/// Represents a single scan record with metadata.
///
/// Matches Rust/Java: offset, timestamp, change_type, row.
/// The bucket is the key in ScanRecords, not on the individual record.
#[pyclass]
pub struct ScanRecord {
#[pyo3(get)]
offset: i64,
#[pyo3(get)]
timestamp: i64,
#[pyo3(get)]
change_type: ChangeType,
/// Store row as a Python dict directly
row_dict: Py<PyDict>,
}
#[pymethods]
impl ScanRecord {
/// Get the row data as a dictionary
#[getter]
pub fn row(&self, py: Python) -> Py<PyDict> {
self.row_dict.clone_ref(py)
}
fn __str__(&self) -> String {
format!(
"ScanRecord(offset={}, timestamp={}, change_type={})",
self.offset,
self.timestamp,
self.change_type.short_string()
)
}
fn __repr__(&self) -> String {
self.__str__()
}
}
impl ScanRecord {
/// Create a ScanRecord from core types
pub fn from_core(
py: Python,
record: &fcore::record::ScanRecord,
row_type: &fcore::metadata::RowType,
) -> PyResult<Self> {
let fields = row_type.fields();
let row = record.row();
let dict = PyDict::new(py);
for (pos, field) in fields.iter().enumerate() {
let value = datum_to_python_value(py, row, pos, field.data_type())?;
dict.set_item(field.name(), value)?;
}
Ok(ScanRecord {
offset: record.offset(),
timestamp: record.timestamp(),
change_type: ChangeType::from_core(*record.change_type()),
row_dict: dict.unbind(),
})
}
}
/// Represents a batch of records with metadata
#[pyclass]
pub struct RecordBatch {
batch: Arc<ArrowRecordBatch>,
#[pyo3(get)]
bucket: TableBucket,
#[pyo3(get)]
base_offset: i64,
#[pyo3(get)]
last_offset: i64,
}
#[pymethods]
impl RecordBatch {
/// Get the Arrow RecordBatch as PyArrow RecordBatch
#[getter]
pub fn batch(&self, py: Python) -> PyResult<Py<PyAny>> {
let pyarrow_batch = self
.batch
.as_ref()
.to_pyarrow(py)
.map_err(|e| FlussError::new_err(format!("Failed to convert batch: {e}")))?;
Ok(pyarrow_batch.unbind())
}
fn __str__(&self) -> String {
format!(
"RecordBatch(bucket={}, base_offset={}, last_offset={}, rows={})",
self.bucket.__str__(),
self.base_offset,
self.last_offset,
self.batch.num_rows()
)
}
fn __repr__(&self) -> String {
self.__str__()
}
}
impl RecordBatch {
/// Create a RecordBatch from core ScanBatch
pub fn from_scan_batch(scan_batch: fcore::record::ScanBatch) -> Self {
RecordBatch {
bucket: TableBucket::from_core(scan_batch.bucket().clone()),
base_offset: scan_batch.base_offset(),
last_offset: scan_batch.last_offset(),
batch: Arc::new(scan_batch.into_batch()),
}
}
}
/// A collection of scan records grouped by bucket.
///
/// Returned by `LogScanner.poll()`. Records are grouped by `TableBucket`.
#[pyclass]
pub struct ScanRecords {
records_by_bucket: IndexMap<TableBucket, Vec<Py<ScanRecord>>>,
total_count: usize,
}
#[pymethods]
impl ScanRecords {
/// List of distinct buckets that have records in this result.
pub fn buckets(&self) -> Vec<TableBucket> {
self.records_by_bucket.keys().cloned().collect()
}
/// Get records for a specific bucket.
///
/// Returns an empty list if the bucket is not present (matches Rust/Java behavior).
pub fn records(&self, py: Python, bucket: &TableBucket) -> Vec<Py<ScanRecord>> {
self.records_by_bucket
.get(bucket)
.map(|recs| recs.iter().map(|r| r.clone_ref(py)).collect())
.unwrap_or_default()
}
/// Total number of records across all buckets.
pub fn count(&self) -> usize {
self.total_count
}
/// Whether the result set is empty.
pub fn is_empty(&self) -> bool {
self.total_count == 0
}
fn __len__(&self) -> usize {
self.total_count
}
/// Type-dispatched indexing:
/// records[0] → ScanRecord (flat index)
/// records[-1] → ScanRecord (negative index)
/// records[1:3] → list[ScanRecord] (slice)
/// records[bucket] → list[ScanRecord] (by bucket)
fn __getitem__(&self, py: Python, key: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
// Try integer index first
if let Ok(mut idx) = key.extract::<isize>() {
let len = self.total_count as isize;
if idx < 0 {
idx += len;
}
if idx < 0 || idx >= len {
return Err(PyIndexError::new_err(format!(
"index {idx} out of range for ScanRecords of size {len}"
)));
}
let idx = idx as usize;
let mut offset = 0;
for recs in self.records_by_bucket.values() {
if idx < offset + recs.len() {
return Ok(recs[idx - offset].clone_ref(py).into_any());
}
offset += recs.len();
}
return Err(PyRuntimeError::new_err(
"internal error: total_count out of sync with records",
));
}
// Try slice
if let Ok(slice) = key.downcast::<PySlice>() {
let indices = slice.indices(self.total_count as isize)?;
let mut result: Vec<Py<ScanRecord>> = Vec::new();
let mut i = indices.start;
while (indices.step > 0 && i < indices.stop) || (indices.step < 0 && i > indices.stop) {
let idx = i as usize;
let mut offset = 0;
for recs in self.records_by_bucket.values() {
if idx < offset + recs.len() {
result.push(recs[idx - offset].clone_ref(py));
break;
}
offset += recs.len();
}
i += indices.step;
}
return Ok(result.into_pyobject(py).unwrap().into_any().unbind());
}
// Try TableBucket
if let Ok(bucket) = key.extract::<TableBucket>() {
let recs = self.records(py, &bucket);
return Ok(recs.into_pyobject(py).unwrap().into_any().unbind());
}
Err(PyTypeError::new_err(
"index must be int, slice, or TableBucket",
))
}
/// Support `bucket in records`.
fn __contains__(&self, bucket: &TableBucket) -> bool {
self.records_by_bucket.contains_key(bucket)
}
/// Mapping protocol: alias for `buckets()`.
pub fn keys(&self) -> Vec<TableBucket> {
self.buckets()
}
/// Mapping protocol: lazy iterator over record lists, one per bucket.
pub fn values(slf: Bound<'_, Self>) -> ScanRecordsBucketIter {
let this = slf.borrow();
let bucket_keys: Vec<TableBucket> = this.records_by_bucket.keys().cloned().collect();
drop(this);
ScanRecordsBucketIter {
owner: slf.unbind(),
bucket_keys,
bucket_idx: 0,
with_keys: false,
}
}
/// Mapping protocol: lazy iterator over `(TableBucket, list[ScanRecord])` pairs.
pub fn items(slf: Bound<'_, Self>) -> ScanRecordsBucketIter {
let this = slf.borrow();
let bucket_keys: Vec<TableBucket> = this.records_by_bucket.keys().cloned().collect();
drop(this);
ScanRecordsBucketIter {
owner: slf.unbind(),
bucket_keys,
bucket_idx: 0,
with_keys: true,
}
}
fn __str__(&self) -> String {
format!(
"ScanRecords(records={}, buckets={})",
self.total_count,
self.records_by_bucket.len()
)
}
fn __repr__(&self) -> String {
self.__str__()
}
/// Flat iterator over all records across all buckets (matches Java/Rust).
fn __iter__(slf: Bound<'_, Self>) -> ScanRecordsIter {
let this = slf.borrow();
let bucket_keys: Vec<TableBucket> = this.records_by_bucket.keys().cloned().collect();
drop(this);
ScanRecordsIter {
owner: slf.unbind(),
bucket_keys,
bucket_idx: 0,
rec_idx: 0,
}
}
}
#[pyclass]
struct ScanRecordsIter {
owner: Py<ScanRecords>,
bucket_keys: Vec<TableBucket>,
bucket_idx: usize,
rec_idx: usize,
}
#[pymethods]
impl ScanRecordsIter {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(&mut self, py: Python) -> Option<Py<ScanRecord>> {
let owner = self.owner.borrow(py);
loop {
if self.bucket_idx >= self.bucket_keys.len() {
return None;
}
let bucket = &self.bucket_keys[self.bucket_idx];
if let Some(recs) = owner.records_by_bucket.get(bucket) {
if self.rec_idx < recs.len() {
let rec = recs[self.rec_idx].clone_ref(py);
self.rec_idx += 1;
return Some(rec);
}
}
self.bucket_idx += 1;
self.rec_idx = 0;
}
}
}
/// Lazy iterator for `ScanRecords.items()` and `ScanRecords.values()`.
///
/// Yields one bucket at a time: `(TableBucket, list[ScanRecord])` for items,
/// or `list[ScanRecord]` for values. Only materializes records for the
/// current bucket on each `__next__` call.
#[pyclass]
pub struct ScanRecordsBucketIter {
owner: Py<ScanRecords>,
bucket_keys: Vec<TableBucket>,
bucket_idx: usize,
with_keys: bool,
}
#[pymethods]
impl ScanRecordsBucketIter {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(&mut self, py: Python) -> Option<Py<PyAny>> {
if self.bucket_idx >= self.bucket_keys.len() {
return None;
}
let bucket = &self.bucket_keys[self.bucket_idx];
let owner = self.owner.borrow(py);
let recs = owner
.records_by_bucket
.get(bucket)
.map(|recs| recs.iter().map(|r| r.clone_ref(py)).collect::<Vec<_>>())
.unwrap_or_default();
let bucket = bucket.clone();
self.bucket_idx += 1;
if self.with_keys {
Some(
(bucket, recs)
.into_pyobject(py)
.unwrap()
.into_any()
.unbind(),
)
} else {
Some(recs.into_pyobject(py).unwrap().into_any().unbind())
}
}
}
/// Represents a Fluss table for data operations
#[pyclass]
pub struct FlussTable {
connection: Arc<fcore::client::FlussConnection>,
metadata: Arc<fcore::client::Metadata>,
table_info: fcore::metadata::TableInfo,
table_path: fcore::metadata::TablePath,
has_primary_key: bool,
}
/// Builder for creating log scanners with flexible configuration.
///
/// Use this builder to configure projection, and in the future, filters
/// before creating a log scanner.
#[pyclass]
pub struct TableScan {
connection: Arc<fcore::client::FlussConnection>,
metadata: Arc<fcore::client::Metadata>,
table_info: fcore::metadata::TableInfo,
projection: Option<ProjectionType>,
}
/// Scanner type for internal use
enum ScannerType {
Record,
Batch,
}
#[pymethods]
impl TableScan {
/// Project to specific columns by their indices.
///
/// Args:
/// indices: List of column indices (0-based) to include in the scan.
///
/// Returns:
/// Self for method chaining.
pub fn project(mut slf: PyRefMut<'_, Self>, indices: Vec<usize>) -> PyRefMut<'_, Self> {
slf.projection = Some(ProjectionType::Indices(indices));
slf
}
/// Project to specific columns by their names.
///
/// Args:
/// names: List of column names to include in the scan.
///
/// Returns:
/// Self for method chaining.
pub fn project_by_name(mut slf: PyRefMut<'_, Self>, names: Vec<String>) -> PyRefMut<'_, Self> {
slf.projection = Some(ProjectionType::Names(names));
slf
}
/// Create a record-based log scanner.
///
/// Use this scanner with `poll()` to get individual records with metadata
/// (offset, timestamp, change_type).
///
/// Returns:
/// LogScanner for record-by-record scanning with `poll()`
pub fn create_log_scanner<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
self.create_scanner_internal(py, ScannerType::Record)
}
/// Create a batch-based log scanner.
///
/// Use this scanner with `poll_arrow()` to get Arrow Tables, or with
/// `poll_record_batch()` to get individual batches with metadata.
///
/// Returns:
/// LogScanner for batch-based scanning with `poll_arrow()` or `poll_record_batch()`
pub fn create_record_batch_log_scanner<'py>(
&self,
py: Python<'py>,
) -> PyResult<Bound<'py, PyAny>> {
self.create_scanner_internal(py, ScannerType::Batch)
}
fn __repr__(&self) -> String {
format!(
"TableScan(table={}.{})",
self.table_info.table_path.database(),
self.table_info.table_path.table()
)
}
}
impl TableScan {
fn create_scanner_internal<'py>(
&self,
py: Python<'py>,
scanner_type: ScannerType,
) -> PyResult<Bound<'py, PyAny>> {
let conn = self.connection.clone();
let metadata = self.metadata.clone();
let table_info = self.table_info.clone();
let projection = self.projection.clone();
future_into_py(py, async move {
let fluss_table = fcore::client::FlussTable::new(&conn, metadata, table_info.clone());
let projection_indices = resolve_projection_indices(&projection, &table_info)?;
let table_scan = apply_projection(fluss_table.new_scan(), projection)?;
let admin = conn
.get_admin()
.await
.map_err(|e| FlussError::from_core_error(&e))?;
let (projected_schema, projected_row_type) =
calculate_projected_types(&table_info, projection_indices)?;
let scanner_kind = match scanner_type {
ScannerType::Record => {
let s = table_scan
.create_log_scanner()
.map_err(|e| FlussError::from_core_error(&e))?;
ScannerKind::Record(s)
}
ScannerType::Batch => {
let s = table_scan
.create_record_batch_log_scanner()
.map_err(|e| FlussError::from_core_error(&e))?;
ScannerKind::Batch(s)
}
};
let py_scanner = LogScanner::new(
scanner_kind,
admin,
table_info,
projected_schema,
projected_row_type,
);
Python::attach(|py| Py::new(py, py_scanner))
})
}
}
/// Internal enum to represent different projection types
#[derive(Clone)]
enum ProjectionType {
Indices(Vec<usize>),
Names(Vec<String>),
}
/// Resolve projection to column indices
fn resolve_projection_indices(
projection: &Option<ProjectionType>,
table_info: &fcore::metadata::TableInfo,
) -> PyResult<Option<Vec<usize>>> {
match projection {
Some(ProjectionType::Indices(indices)) => Ok(Some(indices.clone())),
Some(ProjectionType::Names(names)) => {
let schema = table_info.get_schema();
let columns = schema.columns();
let mut indices = Vec::with_capacity(names.len());
for name in names {
let idx = columns
.iter()
.position(|c| c.name() == name)
.ok_or_else(|| FlussError::new_err(format!("Column '{name}' not found")))?;
indices.push(idx);
}
Ok(Some(indices))
}
None => Ok(None),
}
}
/// Apply projection to table scan
fn apply_projection(
table_scan: fcore::client::TableScan,
projection: Option<ProjectionType>,
) -> PyResult<fcore::client::TableScan> {
match projection {
Some(ProjectionType::Indices(indices)) => table_scan
.project(&indices)
.map_err(|e| FlussError::from_core_error(&e)),
Some(ProjectionType::Names(names)) => {
let column_name_refs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
table_scan
.project_by_name(&column_name_refs)
.map_err(|e| FlussError::from_core_error(&e))
}
None => Ok(table_scan),
}
}
/// Calculate projected schema and row type from projection indices
fn calculate_projected_types(
table_info: &fcore::metadata::TableInfo,
projection_indices: Option<Vec<usize>>,
) -> PyResult<(SchemaRef, fcore::metadata::RowType)> {
let full_schema =
to_arrow_schema(table_info.get_row_type()).map_err(|e| FlussError::from_core_error(&e))?;
let full_row_type = table_info.get_row_type();
match projection_indices {
Some(indices) => {
let arrow_fields: Vec<_> = indices
.iter()
.map(|&i| full_schema.field(i).clone())
.collect();
let row_fields: Vec<_> = indices
.iter()
.map(|&i| full_row_type.fields()[i].clone())
.collect();
Ok((
Arc::new(arrow_schema::Schema::new(arrow_fields)),
fcore::metadata::RowType::new(row_fields),
))
}
None => Ok((full_schema, full_row_type.clone())),
}
}
#[pymethods]
impl FlussTable {
/// Create a new table scan builder for configuring and creating log scanners.
///
/// Use this method to create scanners with the builder pattern:
/// Returns:
/// TableScan builder for configuring the scanner.
pub fn new_scan(&self) -> TableScan {
TableScan {
connection: self.connection.clone(),
metadata: self.metadata.clone(),
table_info: self.table_info.clone(),
projection: None,
}
}
/// Create a new TableAppend builder for the table.
///
/// Returns:
/// TableAppend builder. Call `create_writer()` to get an AppendWriter.
fn new_append(&self) -> PyResult<TableAppend> {
let _guard = TOKIO_RUNTIME.enter();
let fluss_table = fcore::client::FlussTable::new(
&self.connection,
self.metadata.clone(),
self.table_info.clone(),
);
let table_append = fluss_table
.new_append()
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(TableAppend {
inner: table_append,
table_info: self.table_info.clone(),
})
}
/// Get table information
pub fn get_table_info(&self) -> TableInfo {
TableInfo::from_core(self.table_info.clone())
}
/// Get table path
pub fn get_table_path(&self) -> TablePath {
TablePath::from_core(self.table_path.clone())
}
/// Check if table has primary key
pub fn has_primary_key(&self) -> bool {
self.has_primary_key
}
/// Create a new TableLookup builder for primary key lookups.
///
/// This is only available for tables with a primary key.
///
/// Returns:
/// TableLookup builder. Call `create_lookuper()` to get a Lookuper.
pub fn new_lookup(&self) -> PyResult<TableLookup> {
if !self.has_primary_key {
return Err(FlussError::new_err(
"Lookup is only supported for primary key tables",
));
}
Ok(TableLookup {
connection: self.connection.clone(),
metadata: self.metadata.clone(),
table_info: self.table_info.clone(),
})
}
/// Create a new TableUpsert builder for the table.
///
/// This is only available for tables with a primary key.
///
/// Returns:
/// TableUpsert builder. Call `create_writer()` to get an UpsertWriter,
/// or use `partial_update_by_name()` / `partial_update_by_index()` first.
pub fn new_upsert(&self) -> PyResult<TableUpsert> {
if !self.has_primary_key {
return Err(FlussError::new_err(
"Upsert is only supported for primary key tables",
));
}
let _guard = TOKIO_RUNTIME.enter();
let fluss_table = fcore::client::FlussTable::new(
&self.connection,
self.metadata.clone(),
self.table_info.clone(),
);
let table_upsert = fluss_table
.new_upsert()
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(TableUpsert {
inner: table_upsert,
table_info: self.table_info.clone(),
target_columns: None,
})
}
fn __repr__(&self) -> String {
format!(
"FlussTable(path={}.{})",
self.table_path.database(),
self.table_path.table()
)
}
}
impl FlussTable {
/// Create a FlussTable
pub fn new_table(
connection: Arc<fcore::client::FlussConnection>,
metadata: Arc<fcore::client::Metadata>,
table_info: fcore::metadata::TableInfo,
table_path: fcore::metadata::TablePath,
has_primary_key: bool,
) -> Self {
Self {
connection,
metadata,
table_info,
table_path,
has_primary_key,
}
}
}
/// Builder for creating an AppendWriter.
///
/// Obtain via `FlussTable.new_append()`, then call `create_writer()`.
#[pyclass]
pub struct TableAppend {
inner: fcore::client::TableAppend,
table_info: fcore::metadata::TableInfo,
}
#[pymethods]
impl TableAppend {
/// Create an AppendWriter from this builder.
pub fn create_writer(&self) -> PyResult<AppendWriter> {
let rust_writer = self
.inner
.create_writer()
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(AppendWriter::from_core(
rust_writer,
self.table_info.clone(),
))
}
fn __repr__(&self) -> String {
"TableAppend()".to_string()
}
}
/// Builder for creating an UpsertWriter, with optional partial update configuration.
///
/// Obtain via `FlussTable.new_upsert()`, then optionally call
/// `partial_update_by_name()` or `partial_update_by_index()`,
/// then call `create_writer()`.
#[pyclass]
pub struct TableUpsert {
inner: fcore::client::TableUpsert,
table_info: fcore::metadata::TableInfo,
/// Column indices for partial updates, tracked for Python's dict→GenericRow conversion.
target_columns: Option<Vec<usize>>,
}
#[pymethods]
impl TableUpsert {
/// Configure partial update by column names.
///
/// Only the specified columns will be updated on upsert.
///
/// Args:
/// columns: List of column names to update.
///
/// Returns:
/// A new TableUpsert configured for partial update.
pub fn partial_update_by_name(&self, columns: Vec<String>) -> PyResult<TableUpsert> {
let col_refs: Vec<&str> = columns.iter().map(|s| s.as_str()).collect();
// Core validates and resolves names → indices internally
let updated = self
.inner
.partial_update_with_column_names(&col_refs)
.map_err(|e| FlussError::from_core_error(&e))?;
// Resolve indices for Python's row conversion layer (core validated names above)
let row_type = self.table_info.row_type();
let indices: Vec<usize> = columns
.iter()
.map(|name| {
row_type.get_field_index(name).ok_or_else(|| {
FlussError::new_err(format!("Unknown column name '{name}' for partial update"))
})
})
.collect::<PyResult<Vec<usize>>>()?;
Ok(TableUpsert {
inner: updated,
table_info: self.table_info.clone(),
target_columns: Some(indices),
})
}
/// Configure partial update by column indices.
///
/// Only the specified columns will be updated on upsert.
///
/// Args:
/// column_indices: List of column indices (0-based) to update.
///
/// Returns:
/// A new TableUpsert configured for partial update.
pub fn partial_update_by_index(&self, column_indices: Vec<usize>) -> PyResult<TableUpsert> {
let target = column_indices.clone();
// Core validates indices internally
let updated = self
.inner
.partial_update(Some(column_indices))
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(TableUpsert {
inner: updated,
table_info: self.table_info.clone(),
target_columns: Some(target),
})
}
/// Create an UpsertWriter from this builder.
pub fn create_writer(&self) -> PyResult<crate::UpsertWriter> {
crate::UpsertWriter::new(
&self.inner,
self.table_info.clone(),
self.target_columns.clone(),
)
}
fn __repr__(&self) -> String {
"TableUpsert()".to_string()
}
}
/// Builder for creating a Lookuper.
///
/// Obtain via `FlussTable.new_lookup()`, then call `create_lookuper()`.
#[pyclass]
pub struct TableLookup {
connection: Arc<fcore::client::FlussConnection>,
metadata: Arc<fcore::client::Metadata>,
table_info: fcore::metadata::TableInfo,
}
#[pymethods]
impl TableLookup {
/// Create a Lookuper from this builder.
pub fn create_lookuper(&self) -> PyResult<crate::Lookuper> {
crate::Lookuper::new(
&self.connection,
self.metadata.clone(),
self.table_info.clone(),
)
}
fn __repr__(&self) -> String {
"TableLookup()".to_string()
}
}
/// Writer for appending data to a Fluss table
#[pyclass]
pub struct AppendWriter {
inner: Arc<fcore::client::AppendWriter>,
table_info: fcore::metadata::TableInfo,
}
#[pymethods]
impl AppendWriter {
/// Write Arrow table data (fire-and-forget, use flush() to ensure delivery)
pub fn write_arrow(&self, py: Python, table: Py<PyAny>) -> PyResult<()> {
// Convert Arrow Table to batches and write each batch
let batches = table.call_method0(py, "to_batches")?;
let batch_list: Vec<Py<PyAny>> = batches.extract(py)?;
for batch in batch_list {
// Drop the handle — fire-and-forget for bulk writes
drop(self.write_arrow_batch(py, batch)?);
}
Ok(())
}
/// Write Arrow batch data.
///
/// Returns:
/// WriteResultHandle that can be ignored (fire-and-forget) or
/// awaited via `handle.wait()` for server acknowledgment.
pub fn write_arrow_batch(&self, py: Python, batch: Py<PyAny>) -> PyResult<WriteResultHandle> {
// This shares the underlying Arrow buffers without copying data
let batch_bound = batch.bind(py);
let rust_batch: ArrowRecordBatch = FromPyArrow::from_pyarrow_bound(batch_bound)
.map_err(|e| FlussError::new_err(format!("Failed to convert RecordBatch: {e}")))?;
let result_future = self
.inner
.append_arrow_batch(rust_batch)
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(WriteResultHandle::new(result_future))
}
/// Append a single row to the table.
///
/// Returns:
/// WriteResultHandle that can be ignored (fire-and-forget) or
/// awaited via `handle.wait()` for server acknowledgment.
pub fn append(&self, row: &Bound<'_, PyAny>) -> PyResult<WriteResultHandle> {
let generic_row = python_to_generic_row(row, &self.table_info)?;
let result_future = self
.inner
.append(&generic_row)
.map_err(|e| FlussError::from_core_error(&e))?;
Ok(WriteResultHandle::new(result_future))
}
/// Write Pandas DataFrame data
pub fn write_pandas(&self, py: Python, df: Py<PyAny>) -> PyResult<()> {
// Get the expected Arrow schema from the Fluss table
let row_type = self.table_info.get_row_type();
let expected_schema = fcore::record::to_arrow_schema(row_type)
.map_err(|e| FlussError::from_core_error(&e))?;
// Convert Arrow schema to PyArrow schema
let py_schema = expected_schema
.as_ref()
.to_pyarrow(py)
.map_err(|e| FlussError::new_err(format!("Failed to convert schema: {e}")))?;
// Import pyarrow module
let pyarrow = py.import("pyarrow")?;
// Get the Table class from pyarrow module
let table_class = pyarrow.getattr("Table")?;
// Call Table.from_pandas(df, schema=expected_schema) to ensure proper type casting
let pa_table = table_class.call_method(
"from_pandas",
(df,),
Some(&[("schema", py_schema)].into_py_dict(py)?),
)?;
// Then call write_arrow with the converted table
self.write_arrow(py, pa_table.into())
}
/// Flush any pending data
pub fn flush<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
inner
.flush()
.await
.map_err(|e| FlussError::from_core_error(&e))
})
}
fn __repr__(&self) -> String {
"AppendWriter()".to_string()
}
}
impl AppendWriter {
/// Create a AppendWriter from a core append writer
pub fn from_core(
append: fcore::client::AppendWriter,