Repository navigation
Expand file tree
/
Copy pathtable.rs
More file actions
2553 lines (2401 loc) · 85.4 KB
/
Copy pathtable.rs
File metadata and controls
2553 lines (2401 loc) · 85.4 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 std::collections::HashMap;
use std::ffi::{c_char, c_void};
use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
use arrow_array::{Array, StructArray};
use futures::StreamExt;
use paimon::catalog::{Identifier, DEFAULT_MAIN_BRANCH};
use paimon::io::FileIO;
use paimon::spec::{DataField, DataType, Datum, Predicate, PredicateBuilder, TableSchema};
use paimon::table::{ArrowRecordBatchStream, DataSplit, Table};
use paimon::Plan;
use crate::error::{check_non_null, paimon_error, validate_cstr, PaimonErrorCode};
use crate::file_io::file_io_ref;
use crate::result::{
paimon_result_get_table, paimon_result_latest_snapshot, paimon_result_new_read,
paimon_result_next_batch, paimon_result_plan, paimon_result_predicate,
paimon_result_read_builder, paimon_result_record_batch_reader, paimon_result_table_scan,
};
use crate::runtime;
use crate::types::*;
// Helper to free a wrapper struct that contains a Table clone.
unsafe fn free_table_wrapper<T>(ptr: *mut T, get_inner: impl FnOnce(&T) -> *mut c_void) {
if !ptr.is_null() {
let wrapper = Box::from_raw(ptr);
let inner = get_inner(&wrapper);
if !inner.is_null() {
drop(Box::from_raw(inner as *mut Table));
}
}
}
// Helper to box a ReadBuilderState and return a raw pointer.
unsafe fn box_read_builder_state(state: ReadBuilderState) -> *mut paimon_read_builder {
let inner = Box::into_raw(Box::new(state)) as *mut c_void;
Box::into_raw(Box::new(paimon_read_builder { inner }))
}
// Helper to box a TableReadState and return a raw pointer.
unsafe fn box_table_read_state(state: TableReadState) -> *mut paimon_table_read {
let inner = Box::into_raw(Box::new(state)) as *mut c_void;
Box::into_raw(Box::new(paimon_table_read { inner }))
}
// ======================= Table ===============================
fn resolved_table_result(
file_io: FileIO,
table_path: String,
schema: TableSchema,
database: String,
table_name: String,
branch: String,
) -> paimon_result_get_table {
let table = match Table::from_resolved_schema(
file_io,
Identifier::new(database, table_name),
table_path,
schema,
branch,
) {
Ok(table) => table,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error: paimon_error::from_paimon(error),
}
}
};
let wrapper = Box::new(paimon_table {
inner: Box::into_raw(Box::new(table)) as *mut c_void,
});
paimon_result_get_table {
table: Box::into_raw(wrapper),
error: std::ptr::null_mut(),
}
}
/// Create a table directly from a resolved Paimon table schema JSON.
///
/// This constructor does not create a catalog or derive a warehouse. Storage
/// options are used only to build FileIO; they are not merged into the supplied
/// table schema. `branch` selects the branch-scoped managers while preserving
/// the supplied schema; pass null to default to the `main` branch.
///
/// # Safety
/// All string pointers except `branch` must be valid null-terminated C strings.
/// `branch` may be null to select the default `main` branch, or a valid
/// null-terminated C string. `storage_options` must point to
/// `storage_options_len` valid `paimon_option` values, or be null when
/// `storage_options_len` is 0.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_from_schema_json(
table_path: *const c_char,
table_schema_json: *const c_char,
database: *const c_char,
table_name: *const c_char,
branch: *const c_char,
storage_options: *const paimon_option,
storage_options_len: usize,
) -> paimon_result_get_table {
let table_path = match validate_cstr(table_path, "table_path") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let table_schema_json = match validate_cstr(table_schema_json, "table_schema_json") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let database = match validate_cstr(database, "database") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let table_name = match validate_cstr(table_name, "table_name") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let branch = if branch.is_null() {
DEFAULT_MAIN_BRANCH.to_string()
} else {
match validate_cstr(branch, "branch") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
}
};
if storage_options.is_null() && storage_options_len > 0 {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error: paimon_error::new(
PaimonErrorCode::InvalidInput,
"null storage_options pointer with non-zero length".to_string(),
),
};
}
let schema = match serde_json::from_str::<TableSchema>(&table_schema_json) {
Ok(schema) => schema,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error: paimon_error::new(
PaimonErrorCode::InvalidInput,
format!("Failed to parse table schema JSON: {error}"),
),
}
}
};
let mut options = HashMap::with_capacity(storage_options_len);
if storage_options_len > 0 {
for option in std::slice::from_raw_parts(storage_options, storage_options_len) {
let key = match validate_cstr(option.key, "storage option key") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let value = match validate_cstr(option.value, "storage option value") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
options.insert(key, value);
}
}
let file_io = match FileIO::from_path(&table_path)
.and_then(|builder| builder.with_props(options.iter()).build())
{
Ok(file_io) => file_io,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error: paimon_error::from_paimon(error),
}
}
};
resolved_table_result(file_io, table_path, schema, database, table_name, branch)
}
/// Create a table from a resolved schema and a caller-created FileIO.
///
/// The FileIO is cloned into the table, so its handle may be freed immediately
/// after this call. This additive API allows native embedders to share storage
/// and an externally managed cache across tables.
///
/// # Safety
/// `file_io` must be returned by a Paimon FileIO constructor. All string
/// pointers except `branch` must be valid null-terminated C strings. `branch`
/// may be null to select `main`.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_from_schema_json_with_file_io(
file_io: *const paimon_file_io,
table_path: *const c_char,
table_schema_json: *const c_char,
database: *const c_char,
table_name: *const c_char,
branch: *const c_char,
) -> paimon_result_get_table {
if let Err(error) = check_non_null(file_io, "file_io") {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
};
}
let table_path = match validate_cstr(table_path, "table_path") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let table_schema_json = match validate_cstr(table_schema_json, "table_schema_json") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let database = match validate_cstr(database, "database") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let table_name = match validate_cstr(table_name, "table_name") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
};
let branch = if branch.is_null() {
DEFAULT_MAIN_BRANCH.to_string()
} else {
match validate_cstr(branch, "branch") {
Ok(value) => value,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error,
}
}
}
};
let schema = match serde_json::from_str::<TableSchema>(&table_schema_json) {
Ok(schema) => schema,
Err(error) => {
return paimon_result_get_table {
table: std::ptr::null_mut(),
error: paimon_error::new(
PaimonErrorCode::InvalidInput,
format!("Failed to parse table schema JSON: {error}"),
),
}
}
};
resolved_table_result(
file_io_ref(file_io).clone(),
table_path,
schema,
database,
table_name,
branch,
)
}
/// Free a paimon_table.
///
/// # Safety
/// Only call with a table returned from `paimon_catalog_get_table`,
/// `paimon_table_from_schema_json`, or
/// `paimon_table_from_schema_json_with_file_io`.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_free(table: *mut paimon_table) {
free_table_wrapper(table, |t| t.inner);
}
/// Return the latest snapshot as JSON, or JSON null when the table is empty.
///
/// # Safety
/// `table` must be a valid pointer from a previous paimon C call.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_latest_snapshot(
table: *const paimon_table,
) -> paimon_result_latest_snapshot {
if let Err(error) = check_non_null(table, "table") {
return paimon_result_latest_snapshot {
snapshot: paimon_bytes::empty(),
error,
};
}
let table = &*((*table).inner as *const Table);
match runtime().block_on(table.snapshot_manager().get_latest_snapshot()) {
Ok(snapshot) => match serde_json::to_vec(&snapshot) {
Ok(snapshot) => paimon_result_latest_snapshot {
snapshot: paimon_bytes::new(snapshot),
error: std::ptr::null_mut(),
},
Err(error) => paimon_result_latest_snapshot {
snapshot: paimon_bytes::empty(),
error: paimon_error::new(
PaimonErrorCode::Unexpected,
format!("failed to serialize snapshot metadata: {error}"),
),
},
},
Err(error) => paimon_result_latest_snapshot {
snapshot: paimon_bytes::empty(),
error: paimon_error::from_paimon(error),
},
}
}
/// Time-travel selector option names, in the core's resolution priority order.
const TIME_TRAVEL_SELECTORS: [&str; 5] = [
"scan.timestamp-millis",
"scan.watermark",
"scan.version",
"scan.snapshot-id",
"scan.tag-name",
];
/// Build a `ReadBuilderState` from a table and a scan-option map, resolving any
/// time-travel selector at construction time.
///
/// Rejects more than one time-travel selector up front (the core silently falls
/// back on a conflict, which would misattribute the failure). Otherwise runs the
/// core's `copy_with_time_travel`, which validates unsupported scan options and
/// resolves the selector; a set selector that does not resolve to a snapshot is
/// an error, so a mistyped or missing selector can never silently read latest.
unsafe fn new_read_builder_state(
table: &Table,
options: HashMap<String, String>,
) -> Result<ReadBuilderState, *mut paimon_error> {
let present: Vec<&str> = TIME_TRAVEL_SELECTORS
.iter()
.copied()
.filter(|name| options.contains_key(*name))
.collect();
if present.len() > 1 {
return Err(paimon_error::new(
PaimonErrorCode::InvalidInput,
format!(
"Only one time-travel selector may be set, found: {}",
present.join(", ")
),
));
}
let selector = TIME_TRAVEL_SELECTORS
.iter()
.find_map(|&name| options.get(name).map(|v| (name.to_string(), v.clone())));
let resolved = match runtime().block_on(table.copy_with_time_travel(options)) {
Ok(t) => t,
Err(e) => return Err(paimon_error::from_paimon(e)),
};
if let Some((name, value)) = selector {
if !resolved.has_resolved_travel_snapshot() {
return Err(paimon_error::new(
PaimonErrorCode::InvalidInput,
format!("time-travel selector {name}={value} did not resolve to any snapshot"),
));
}
}
Ok(ReadBuilderState {
table: resolved,
projected_columns: None,
filter: None,
case_sensitive: true,
})
}
/// Create a new ReadBuilder from a Table.
///
/// # Safety
/// `table` must be a valid pointer from `paimon_catalog_get_table` or
/// `paimon_table_from_schema_json`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_table_new_read_builder(
table: *const paimon_table,
) -> paimon_result_read_builder {
paimon_table_new_read_builder_with_options(table, std::ptr::null(), 0)
}
/// Create a ReadBuilder from a Table with scan options (e.g. time-travel
/// selectors `scan.snapshot-id` / `scan.tag-name` / `scan.timestamp-millis` /
/// `scan.watermark` / `scan.version`). At most one time-travel selector may be
/// set. A selector that does not resolve to a snapshot is an error (never a
/// silent read-of-latest).
///
/// # Safety
/// `table` must be a valid pointer. `options` must be a valid pointer to
/// `options_len` `paimon_option` values, or null when `options_len` is 0.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_new_read_builder_with_options(
table: *const paimon_table,
options: *const paimon_option,
options_len: usize,
) -> paimon_result_read_builder {
if let Err(e) = check_non_null(table, "table") {
return paimon_result_read_builder {
read_builder: std::ptr::null_mut(),
error: e,
};
}
if options.is_null() && options_len > 0 {
return paimon_result_read_builder {
read_builder: std::ptr::null_mut(),
error: paimon_error::new(
PaimonErrorCode::InvalidInput,
"null options pointer with non-zero length".to_string(),
),
};
}
let mut map = HashMap::with_capacity(options_len);
if options_len > 0 {
let slice = std::slice::from_raw_parts(options, options_len);
for opt in slice {
let key = match validate_cstr(opt.key, "option key") {
Ok(s) => s,
Err(e) => {
return paimon_result_read_builder {
read_builder: std::ptr::null_mut(),
error: e,
}
}
};
let value = match validate_cstr(opt.value, "option value") {
Ok(s) => s,
Err(e) => {
return paimon_result_read_builder {
read_builder: std::ptr::null_mut(),
error: e,
}
}
};
map.insert(key, value);
}
}
let table_ref = &*((*table).inner as *const Table);
match new_read_builder_state(table_ref, map) {
Ok(state) => paimon_result_read_builder {
read_builder: box_read_builder_state(state),
error: std::ptr::null_mut(),
},
Err(e) => paimon_result_read_builder {
read_builder: std::ptr::null_mut(),
error: e,
},
}
}
// ======================= ReadBuilder ===============================
/// Free a paimon_read_builder.
///
/// # Safety
/// Only call with a read_builder returned from `paimon_table_new_read_builder`.
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_free(rb: *mut paimon_read_builder) {
if !rb.is_null() {
let wrapper = Box::from_raw(rb);
if !wrapper.inner.is_null() {
drop(Box::from_raw(wrapper.inner as *mut ReadBuilderState));
}
}
}
/// Set column projection for a ReadBuilder.
///
/// The `columns` parameter is a null-terminated array of null-terminated C strings.
/// Output order follows the caller-specified order. An empty list is a valid
/// zero-column projection. An obvious typo — a name that matches no field under
/// any case sensitivity — is rejected by this call. Case-dependent resolution
/// (a name that matches only case-insensitively, or a case-fold ambiguity) is
/// deferred to `paimon_read_builder_new_read`, which uses the case sensitivity
/// effective then, so this stays order-independent with
/// `paimon_read_builder_with_case_sensitive`.
///
/// # Safety
/// `rb` must be a valid pointer from `paimon_table_new_read_builder`, or null (returns error).
/// `columns` must be a null-terminated array of null-terminated C strings, or null for no projection.
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_with_projection(
rb: *mut paimon_read_builder,
columns: *const *const std::ffi::c_char,
) -> *mut paimon_error {
if let Err(e) = check_non_null(rb, "rb") {
return e;
}
let state = &mut *((*rb).inner as *mut ReadBuilderState);
if columns.is_null() {
state.projected_columns = None;
return std::ptr::null_mut();
}
let mut col_names = Vec::new();
let mut ptr = columns;
while !(*ptr).is_null() {
let c_str = std::ffi::CStr::from_ptr(*ptr);
match c_str.to_str() {
Ok(s) => col_names.push(s.to_string()),
Err(e) => {
return paimon_error::from_paimon(paimon::Error::ConfigInvalid {
message: format!("Invalid UTF-8 in column name: {e}"),
});
}
}
ptr = ptr.add(1);
}
// Best-effort early validation for obvious typos (columns that cannot match
// under any case sensitivity). Core `with_projection` performs this
// case-independent check and otherwise stores names for lazy resolution, so
// this stays order-independent with `paimon_read_builder_with_case_sensitive`;
// case-dependent resolution/ambiguity errors surface later from
// `paimon_read_builder_new_read`.
let col_refs: Vec<&str> = col_names.iter().map(String::as_str).collect();
if let Err(e) = state.table.new_read_builder().with_projection(&col_refs) {
return paimon_error::from_paimon(e);
}
state.projected_columns = Some(col_names);
std::ptr::null_mut()
}
/// Set whether column-name matching for **projection** is case-sensitive for
/// this ReadBuilder. Defaults to `true` (exact match). When `false`, projected
/// column names are matched by ASCII case-folding and an ambiguous
/// (case-colliding) request errors.
///
/// This does **not** affect predicate resolution: a predicate is resolved when
/// it is constructed, so its case sensitivity is chosen by which constructor
/// you call — `paimon_predicate_*` (case-sensitive) or the additive
/// `paimon_predicate_*_with_case_sensitive` variant — independently of this
/// setting.
///
/// # Safety
/// `rb` must be a valid pointer from `paimon_table_new_read_builder`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_with_case_sensitive(
rb: *mut paimon_read_builder,
case_sensitive: bool,
) -> *mut paimon_error {
if let Err(e) = check_non_null(rb, "rb") {
return e;
}
let state = &mut *((*rb).inner as *mut ReadBuilderState);
state.case_sensitive = case_sensitive;
std::ptr::null_mut()
}
/// Set a filter predicate for scan planning.
///
/// The predicate is consumed (ownership transferred to the read builder).
/// Pass null to clear any previously set filter.
///
/// # Safety
/// `rb` must be a valid pointer from `paimon_table_new_read_builder`, or null (returns error).
/// `predicate` must be a valid pointer from a `paimon_predicate_*` function, or null.
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_with_filter(
rb: *mut paimon_read_builder,
predicate: *mut paimon_predicate,
) -> *mut paimon_error {
if let Err(e) = check_non_null(rb, "rb") {
return e;
}
let state = &mut *((*rb).inner as *mut ReadBuilderState);
if predicate.is_null() {
state.filter = None;
return std::ptr::null_mut();
}
let pred_wrapper = Box::from_raw(predicate);
let pred = Box::from_raw(pred_wrapper.inner as *mut Predicate);
state.filter = Some(*pred);
std::ptr::null_mut()
}
/// Create a new TableScan from a ReadBuilder.
///
/// # Safety
/// `rb` must be a valid pointer from `paimon_table_new_read_builder`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_new_scan(
rb: *const paimon_read_builder,
) -> paimon_result_table_scan {
if let Err(e) = check_non_null(rb, "rb") {
return paimon_result_table_scan {
scan: std::ptr::null_mut(),
error: e,
};
}
let state = &*((*rb).inner as *const ReadBuilderState);
let scan_state = TableScanState {
table: state.table.clone(),
filter: state.filter.clone(),
};
let inner = Box::into_raw(Box::new(scan_state)) as *mut c_void;
paimon_result_table_scan {
scan: Box::into_raw(Box::new(paimon_table_scan { inner })),
error: std::ptr::null_mut(),
}
}
/// Create a new TableRead from a ReadBuilder.
///
/// # Safety
/// `rb` must be a valid pointer from `paimon_table_new_read_builder`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_read_builder_new_read(
rb: *const paimon_read_builder,
) -> paimon_result_new_read {
if let Err(e) = check_non_null(rb, "rb") {
return paimon_result_new_read {
read: std::ptr::null_mut(),
error: e,
};
}
let state = &*((*rb).inner as *const ReadBuilderState);
let mut rb_rust = state.table.new_read_builder();
rb_rust.with_case_sensitive(state.case_sensitive);
// Apply projection if set
if let Some(ref columns) = state.projected_columns {
let col_refs: Vec<&str> = columns.iter().map(|s| s.as_str()).collect();
if let Err(e) = rb_rust.with_projection(&col_refs) {
return paimon_result_new_read {
read: std::ptr::null_mut(),
error: paimon_error::from_paimon(e),
};
}
}
// Apply filter if set
if let Some(ref filter) = state.filter {
rb_rust.with_filter(filter.clone());
}
match rb_rust.new_read() {
Ok(table_read) => {
let read_state = TableReadState {
table: state.table.clone(),
read_type: table_read.read_type().to_vec(),
data_predicates: table_read.data_predicates().to_vec(),
};
paimon_result_new_read {
read: box_table_read_state(read_state),
error: std::ptr::null_mut(),
}
}
Err(e) => paimon_result_new_read {
read: std::ptr::null_mut(),
error: paimon_error::from_paimon(e),
},
}
}
// ======================= TableScan ===============================
/// Free a paimon_table_scan.
///
/// # Safety
/// Only call with a scan returned from `paimon_read_builder_new_scan`.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_scan_free(scan: *mut paimon_table_scan) {
if !scan.is_null() {
let wrapper = Box::from_raw(scan);
if !wrapper.inner.is_null() {
drop(Box::from_raw(wrapper.inner as *mut TableScanState));
}
}
}
/// Execute a scan plan to get splits.
///
/// # Safety
/// `scan` must be a valid pointer from `paimon_read_builder_new_scan`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_table_scan_plan(
scan: *const paimon_table_scan,
) -> paimon_result_plan {
if let Err(e) = check_non_null(scan, "scan") {
return paimon_result_plan {
plan: std::ptr::null_mut(),
error: e,
};
}
let scan_state = &*((*scan).inner as *const TableScanState);
let mut rb = scan_state.table.new_read_builder();
if let Some(ref filter) = scan_state.filter {
rb.with_filter(filter.clone());
}
let table_scan = rb.new_scan();
match runtime().block_on(table_scan.plan()) {
Ok(plan) => {
let wrapper = Box::new(paimon_plan {
inner: Box::into_raw(Box::new(plan)) as *mut c_void,
});
paimon_result_plan {
plan: Box::into_raw(wrapper),
error: std::ptr::null_mut(),
}
}
Err(e) => paimon_result_plan {
plan: std::ptr::null_mut(),
error: paimon_error::from_paimon(e),
},
}
}
// ======================= Plan ===============================
/// Build a one-split `paimon_plan` from a serialized Paimon-native `DataSplit`
/// byte buffer (the wire form produced by `DataSplit::serialize` / Java
/// `DataSplit#serialize`). `data` must be raw bytes (Base64 already decoded by
/// the caller).
///
/// The returned plan is usable with `paimon_table_read_to_arrow` and must be
/// freed with `paimon_plan_free`.
///
/// # Safety
/// `data` must point to `len` valid bytes, or be null when `len == 0`.
#[no_mangle]
pub unsafe extern "C" fn paimon_plan_from_split_bytes(
data: *const u8,
len: usize,
) -> paimon_result_plan {
if data.is_null() || len == 0 {
return paimon_result_plan {
plan: std::ptr::null_mut(),
error: paimon_error::new(
PaimonErrorCode::InvalidInput,
"paimon_plan_from_split_bytes: null or empty buffer".to_string(),
),
};
}
let bytes = std::slice::from_raw_parts(data, len);
match DataSplit::deserialize(bytes) {
Ok(split) => {
let plan = Plan::new(vec![split]);
let wrapper = Box::new(paimon_plan {
inner: Box::into_raw(Box::new(plan)) as *mut c_void,
});
paimon_result_plan {
plan: Box::into_raw(wrapper),
error: std::ptr::null_mut(),
}
}
Err(e) => paimon_result_plan {
plan: std::ptr::null_mut(),
error: paimon_error::from_paimon(e),
},
}
}
/// Free a paimon_plan.
///
/// # Safety
/// Only call with a plan returned from `paimon_table_scan_plan`.
/// A plan returned from `paimon_plan_from_split_bytes` is also a valid source.
#[no_mangle]
pub unsafe extern "C" fn paimon_plan_free(plan: *mut paimon_plan) {
if !plan.is_null() {
let p = Box::from_raw(plan);
if !p.inner.is_null() {
drop(Box::from_raw(p.inner as *mut Plan));
}
}
}
/// Return the number of data splits in a plan.
///
/// # Safety
/// `plan` must be a valid pointer from `paimon_table_scan_plan`, or null (returns 0).
/// A plan returned from `paimon_plan_from_split_bytes` is also a valid source.
#[no_mangle]
pub unsafe extern "C" fn paimon_plan_num_splits(plan: *const paimon_plan) -> usize {
if plan.is_null() {
return 0;
}
let plan_ref = &*((*plan).inner as *const Plan);
plan_ref.splits().len()
}
// ======================= TableRead ===============================
/// Free a paimon_table_read.
///
/// # Safety
/// Only call with a read returned from `paimon_read_builder_new_read`.
#[no_mangle]
pub unsafe extern "C" fn paimon_table_read_free(read: *mut paimon_table_read) {
if !read.is_null() {
let wrapper = Box::from_raw(read);
if !wrapper.inner.is_null() {
drop(Box::from_raw(wrapper.inner as *mut TableReadState));
}
}
}
/// Read table data as Arrow record batches via a streaming reader.
///
/// Returns a `paimon_record_batch_reader` that yields one batch at a time
/// via `paimon_record_batch_reader_next`. This avoids loading all batches
/// into memory at once.
///
/// `offset` and `length` select a contiguous sub-range of splits from the
/// plan. The range is clamped to the available splits (out-of-range values
/// are silently adjusted).
///
/// # Safety
/// `read` and `plan` must be valid pointers from previous paimon C calls, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_table_read_to_arrow(
read: *const paimon_table_read,
plan: *const paimon_plan,
offset: usize,
length: usize,
) -> paimon_result_record_batch_reader {
if let Err(e) = check_non_null(read, "read") {
return paimon_result_record_batch_reader {
reader: std::ptr::null_mut(),
error: e,
};
}
if let Err(e) = check_non_null(plan, "plan") {
return paimon_result_record_batch_reader {
reader: std::ptr::null_mut(),
error: e,
};
}
let state = &*((*read).inner as *const TableReadState);
let plan_ref = &*((*plan).inner as *const Plan);
let all_splits = plan_ref.splits();
let start = offset.min(all_splits.len());
let end = (offset.saturating_add(length)).min(all_splits.len());
let selected = &all_splits[start..end];
let table_read = paimon::table::TableRead::new(
&state.table,
state.read_type.clone(),
state.data_predicates.clone(),
);
match table_read.to_arrow(selected) {
Ok(stream) => {
let reader = Box::new(stream);
let wrapper = Box::new(paimon_record_batch_reader {
inner: Box::into_raw(reader) as *mut c_void,
});
paimon_result_record_batch_reader {
reader: Box::into_raw(wrapper),
error: std::ptr::null_mut(),
}
}
Err(e) => paimon_result_record_batch_reader {
reader: std::ptr::null_mut(),
error: paimon_error::from_paimon(e),
},
}
}
// ======================= RecordBatchReader ===============================
/// Get the next Arrow record batch from the reader.
///
/// When the stream is exhausted, both `batch.array` and `batch.schema` will
/// be null. On error, `error` will be non-null.
///
/// After importing each batch, call `paimon_arrow_batch_free` to free the
/// ArrowArray and ArrowSchema container structs.
///
/// # Safety
/// `reader` must be a valid pointer from `paimon_table_read_to_arrow`, or null (returns error).
#[no_mangle]
pub unsafe extern "C" fn paimon_record_batch_reader_next(
reader: *mut paimon_record_batch_reader,
) -> paimon_result_next_batch {
if let Err(e) = check_non_null(reader, "reader") {
return paimon_result_next_batch {
batch: paimon_arrow_batch {
array: std::ptr::null_mut(),
schema: std::ptr::null_mut(),
},
error: e,
};
}
let stream = &mut *((*reader).inner as *mut ArrowRecordBatchStream);
match runtime().block_on(stream.next()) {
Some(Ok(batch)) => {
let schema = batch.schema();
let struct_array = StructArray::from(batch);
let ffi_array = FFI_ArrowArray::new(&struct_array.to_data());
let ffi_schema = match FFI_ArrowSchema::try_from(schema.as_ref()) {
Ok(s) => s,
Err(e) => {
return paimon_result_next_batch {
batch: paimon_arrow_batch {
array: std::ptr::null_mut(),
schema: std::ptr::null_mut(),
},
error: paimon_error::from_paimon(paimon::Error::UnexpectedError {
message: format!("Failed to export Arrow schema: {e}"),
source: Some(Box::new(e)),
}),
};
}
};
let array_ptr = Box::into_raw(Box::new(ffi_array)) as *mut c_void;
let schema_ptr = Box::into_raw(Box::new(ffi_schema)) as *mut c_void;
paimon_result_next_batch {
batch: paimon_arrow_batch {
array: array_ptr,
schema: schema_ptr,
},
error: std::ptr::null_mut(),
}
}
Some(Err(e)) => paimon_result_next_batch {
batch: paimon_arrow_batch {
array: std::ptr::null_mut(),
schema: std::ptr::null_mut(),
},
error: paimon_error::from_paimon(e),
},