This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git


The following commit(s) were added to refs/heads/main by this push:
     new 999125fd [c] Expose structured read types for nested projection (#1389)
999125fd is described below

commit 999125fd323d3336440beca8c5f5a9ef8f80dd29
Author: Socrates <[email protected]>
AuthorDate: Mon Nov 16 13:24:26 2026 +0800

    [c] Expose structured read types for nested projection (#1389)
---
 bindings/c/src/table.rs           |  56 ++++++++++
 bindings/c/src/tests.rs           |   1 +
 bindings/c/src/tests/read_type.rs | 217 ++++++++++++++++++++++++++++++++++++++
 bindings/c/src/types.rs           |   2 +
 docs/src/c-binding.md             |  22 ++++
 5 files changed, 298 insertions(+)

diff --git a/bindings/c/src/table.rs b/bindings/c/src/table.rs
index 873581dd..e6a91eaa 100644
--- a/bindings/c/src/table.rs
+++ b/bindings/c/src/table.rs
@@ -478,6 +478,7 @@ unsafe fn new_read_builder_state(
         table: resolved,
         resources: None,
         projected_columns: None,
+        read_type: None,
         filter: None,
         case_sensitive: true,
         limit: None,
@@ -633,6 +634,7 @@ pub unsafe extern "C" fn 
paimon_read_builder_with_projection(
 
     if columns.is_null() {
         state.projected_columns = None;
+        state.read_type = None;
         return std::ptr::null_mut();
     }
 
@@ -663,6 +665,53 @@ pub unsafe extern "C" fn 
paimon_read_builder_with_projection(
     }
 
     state.projected_columns = Some(col_names);
+    state.read_type = None;
+    std::ptr::null_mut()
+}
+
+/// Set a structured read type, including nested ROW/ARRAY/MAP projections.
+///
+/// `read_type_json` uses Paimon's JSON array of DataFields, preserving field 
IDs
+/// and the requested recursive types. The input is copied and can be freed
+/// after this call. Core read-type semantics and validation apply when 
building
+/// and executing the read; this does not modify the table's stored schema.
+///
+/// The last successful call to this function or `with_projection` selects the
+/// projection. An empty JSON array selects zero columns; null clears both
+/// selectors. Invalid JSON leaves the builder unchanged. Name-based case
+/// sensitivity does not rewrite the explicitly supplied field identities.
+///
+/// # Safety
+/// `rb` must be a valid read builder or null (returns error).
+/// `read_type_json` must be null or a valid null-terminated UTF-8 string.
+#[no_mangle]
+pub unsafe extern "C" fn paimon_read_builder_with_read_type_json(
+    rb: *mut paimon_read_builder,
+    read_type_json: *const c_char,
+) -> *mut paimon_error {
+    if let Err(error) = check_non_null(rb, "rb") {
+        return error;
+    }
+    let read_type = if read_type_json.is_null() {
+        None
+    } else {
+        let json = match validate_cstr(read_type_json, "read_type_json") {
+            Ok(json) => json,
+            Err(error) => return error,
+        };
+        match serde_json::from_str::<Vec<DataField>>(&json) {
+            Ok(fields) => Some(fields),
+            Err(error) => {
+                return paimon_error::new(
+                    PaimonErrorCode::InvalidInput,
+                    format!("Invalid read type JSON: {error}"),
+                );
+            }
+        }
+    };
+    let state = &mut *((*rb).inner as *mut ReadBuilderState);
+    state.read_type = read_type;
+    state.projected_columns = None;
     std::ptr::null_mut()
 }
 
@@ -762,6 +811,7 @@ pub unsafe extern "C" fn paimon_read_builder_new_scan(
     let state = &*((*rb).inner as *const ReadBuilderState);
     let scan_state = TableScanState {
         table: state.table.clone(),
+        read_type: state.read_type.clone(),
         filter: state.filter.clone(),
         limit: state.limit,
     };
@@ -789,6 +839,9 @@ pub unsafe extern "C" fn paimon_read_builder_new_read(
     let state = &*((*rb).inner as *const ReadBuilderState);
     let mut rb_rust = state.table.new_read_builder();
     rb_rust.with_case_sensitive(state.case_sensitive);
+    if let Some(read_type) = &state.read_type {
+        rb_rust.with_read_type(read_type.clone());
+    }
 
     // Apply projection if set
     if let Some(ref columns) = state.projected_columns {
@@ -863,6 +916,9 @@ pub unsafe extern "C" fn paimon_table_scan_plan(
     }
     let scan_state = &*((*scan).inner as *const TableScanState);
     let mut rb = scan_state.table.new_read_builder();
+    if let Some(read_type) = &scan_state.read_type {
+        rb.with_read_type(read_type.clone());
+    }
     if let Some(ref filter) = scan_state.filter {
         rb.with_filter(filter.clone());
     }
diff --git a/bindings/c/src/tests.rs b/bindings/c/src/tests.rs
index 5ba11190..da10a90a 100644
--- a/bindings/c/src/tests.rs
+++ b/bindings/c/src/tests.rs
@@ -28,6 +28,7 @@
 
 mod audit_read;
 mod commit_messages;
+mod read_type;
 mod table_arrow_schema;
 
 use std::collections::HashMap;
diff --git a/bindings/c/src/tests/read_type.rs 
b/bindings/c/src/tests/read_type.rs
new file mode 100644
index 00000000..d54b684f
--- /dev/null
+++ b/bindings/c/src/tests/read_type.rs
@@ -0,0 +1,217 @@
+// 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 super::*;
+use paimon::spec::{ArrayType, DataField, MapType, RowType};
+use std::io::Cursor;
+
+fn nested_schema() -> TableSchema {
+    let row = DataType::Row(RowType::new(vec![
+        DataField::new(0, "keep".into(), DataType::Int(IntType::new())),
+        DataField::new(
+            1,
+            "drop".into(),
+            DataType::VarChar(VarCharType::string_type()),
+        ),
+    ]));
+    TableSchema::new(
+        0,
+        &Schema::builder()
+            .column("id", DataType::Int(IntType::new()))
+            .column("Row", row.clone())
+            .column("array", DataType::Array(ArrayType::new(row.clone())))
+            .column(
+                "map",
+                DataType::Map(MapType::new(
+                    DataType::VarChar(
+                        VarCharType::with_nullable(false, 
VarCharType::MAX_LENGTH).unwrap(),
+                    ),
+                    row,
+                )),
+            )
+            .build()
+            .unwrap(),
+    )
+}
+
+fn prune(data_type: &DataType) -> DataType {
+    match data_type {
+        DataType::Row(row) => DataType::Row(RowType::with_nullable(
+            data_type.is_nullable(),
+            vec![row.fields()[0].clone()],
+        )),
+        DataType::Array(array) => DataType::Array(ArrayType::with_nullable(
+            data_type.is_nullable(),
+            prune(array.element_type()),
+        )),
+        DataType::Map(map) => DataType::Map(MapType::with_nullable(
+            data_type.is_nullable(),
+            map.key_type().clone(),
+            prune(map.value_type()),
+        )),
+        other => other.clone(),
+    }
+}
+
+fn projected_fields(schema: &TableSchema) -> Vec<DataField> {
+    // Reorder roots while preserving their IDs and selected nested field IDs.
+    [3, 1, 2, 0]
+        .into_iter()
+        .map(|index| {
+            let field = &schema.fields()[index];
+            DataField::new(field.id(), field.name().into(), 
prune(field.data_type()))
+        })
+        .collect()
+}
+
+unsafe fn declared_read_type(builder: *mut paimon_read_builder) -> 
Vec<DataField> {
+    let result = paimon_read_builder_new_read(builder);
+    assert!(result.error.is_null());
+    let state = &*((*result.read).inner as *const TableReadState);
+    let fields = state.read_type.clone();
+    paimon_table_read_free(result.read);
+    fields
+}
+
+unsafe fn collect_batches(builder: *mut paimon_read_builder) -> 
Vec<RecordBatch> {
+    let scan = paimon_read_builder_new_scan(builder);
+    assert!(scan.error.is_null());
+    let plan = paimon_table_scan_plan(scan.scan);
+    assert!(plan.error.is_null());
+    let read = paimon_read_builder_new_read(builder);
+    assert!(read.error.is_null());
+    let result = paimon_table_read_to_arrow(read.read, plan.plan, 0, 
usize::MAX);
+    assert!(result.error.is_null());
+    paimon_table_read_free(read.read);
+    paimon_plan_free(plan.plan);
+    paimon_table_scan_free(scan.scan);
+
+    let mut batches = Vec::new();
+    loop {
+        let next = paimon_record_batch_reader_next(result.reader);
+        assert!(next.error.is_null());
+        if next.batch.array.is_null() {
+            break;
+        }
+        let array = ptr::replace(
+            next.batch.array.cast::<FFI_ArrowArray>(),
+            FFI_ArrowArray::empty(),
+        );
+        let schema = ptr::replace(
+            next.batch.schema.cast::<FFI_ArrowSchema>(),
+            FFI_ArrowSchema::empty(),
+        );
+        let data = arrow_array::ffi::from_ffi(array, &schema).unwrap();
+        paimon_arrow_batch_free(next.batch);
+        batches.push(RecordBatch::from(StructArray::from(data)));
+    }
+    paimon_record_batch_reader_free(result.reader);
+    batches
+}
+
+fn json_batch(fields: &[DataField], json: &str) -> RecordBatch {
+    
arrow::json::ReaderBuilder::new(paimon::arrow::build_target_arrow_schema(fields).unwrap())
+        .build(Cursor::new(json))
+        .unwrap()
+        .next()
+        .unwrap()
+        .unwrap()
+}
+
+#[test]
+fn structured_read_type_projects_nested_containers_through_c() {
+    let schema = nested_schema();
+    let projected = projected_fields(&schema);
+    let json = 
r#"{"id":1,"Row":{"keep":7,"drop":"x"},"array":[{"keep":8,"drop":"y"},null],"map":{"k":{"keep":9,"drop":"z"}}}
+{"id":2,"Row":null,"array":[],"map":{}}
+{"id":3,"Row":{"keep":null,"drop":"unused"},"array":null,"map":null}
+"#;
+    let path = "memory:/ffi_nested_read_type";
+    let file_io = memory_file_io();
+    setup_table_dirs(&file_io, path);
+    let batch = json_batch(schema.fields(), json);
+    let table = Table::new(
+        file_io,
+        Identifier::new("default", "nested"),
+        path.into(),
+        schema,
+        None,
+    );
+    write_data_rust(&table, &[batch]);
+    unsafe {
+        let handle = wrap_table(table);
+        let builder = paimon_table_new_read_builder(handle).read_builder;
+        let json_type = 
CString::new(serde_json::to_string(&projected).unwrap()).unwrap();
+        assert!(paimon_read_builder_with_read_type_json(builder, 
json_type.as_ptr()).is_null());
+        drop(json_type);
+        assert_eq!(declared_read_type(builder), projected);
+        let batches = collect_batches(builder);
+        assert_eq!(batches, vec![json_batch(&projected, json)]);
+
+        let empty = CString::new("[]").unwrap();
+        assert!(paimon_read_builder_with_read_type_json(builder, 
empty.as_ptr()).is_null());
+        let batches = collect_batches(builder);
+        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 
3);
+        assert!(batches.iter().all(|batch| batch.num_columns() == 0));
+        paimon_read_builder_free(builder);
+        unwrap_table(handle);
+    }
+}
+
+#[test]
+fn 
structured_read_type_preserves_selection_on_errors_and_follows_core_precedence()
 {
+    unsafe {
+        let schema = nested_schema();
+        let projected = projected_fields(&schema);
+        let original = schema.fields().to_vec();
+        let table = wrap_table(Table::new(
+            memory_file_io(),
+            Identifier::new("default", "nested"),
+            "memory:/ffi_read_type_options".into(),
+            schema,
+            None,
+        ));
+        let builder = paimon_table_new_read_builder(table).read_builder;
+        let json = 
CString::new(serde_json::to_string(&projected).unwrap()).unwrap();
+        assert!(paimon_read_builder_with_read_type_json(builder, 
json.as_ptr()).is_null());
+        for bytes in [b"{}\0".as_slice(), b"null\0", b"[\0", b"\xff\0"] {
+            let error = paimon_read_builder_with_read_type_json(builder, 
bytes.as_ptr().cast());
+            assert!(!error.is_null());
+            assert_eq!((*error).code, PaimonErrorCode::InvalidInput as i32);
+            paimon_error_free(error);
+            assert_eq!(declared_read_type(builder), projected);
+        }
+        let error = paimon_read_builder_with_read_type_json(ptr::null_mut(), 
json.as_ptr());
+        assert!(!error.is_null());
+        paimon_error_free(error);
+
+        let name = CString::new("id").unwrap();
+        let names = [name.as_ptr(), ptr::null()];
+        assert!(paimon_read_builder_with_projection(builder, 
names.as_ptr()).is_null());
+        assert_eq!(declared_read_type(builder), vec![original[0].clone()]);
+        assert!(paimon_read_builder_with_read_type_json(builder, 
json.as_ptr()).is_null());
+        assert!(paimon_read_builder_with_case_sensitive(builder, 
false).is_null());
+        assert_eq!(declared_read_type(builder), projected);
+        assert!(paimon_read_builder_with_projection(builder, 
ptr::null()).is_null());
+        assert_eq!(declared_read_type(builder), original);
+        assert!(paimon_read_builder_with_projection(builder, 
names.as_ptr()).is_null());
+        assert!(paimon_read_builder_with_read_type_json(builder, 
ptr::null()).is_null());
+        assert_eq!(declared_read_type(builder), original);
+        paimon_read_builder_free(builder);
+        unwrap_table(table);
+    }
+}
diff --git a/bindings/c/src/types.rs b/bindings/c/src/types.rs
index 4dcaefa2..bd1412e1 100644
--- a/bindings/c/src/types.rs
+++ b/bindings/c/src/types.rs
@@ -268,6 +268,7 @@ pub(crate) struct ReadBuilderState {
     pub table: Table,
     pub resources: Option<ResourceContext>,
     pub projected_columns: Option<Vec<String>>,
+    pub read_type: Option<Vec<DataField>>,
     pub filter: Option<Predicate>,
     pub case_sensitive: bool,
     pub limit: Option<usize>,
@@ -276,6 +277,7 @@ pub(crate) struct ReadBuilderState {
 /// Internal state for TableScan that stores table and filter.
 pub(crate) struct TableScanState {
     pub table: Table,
+    pub read_type: Option<Vec<DataField>>,
     pub filter: Option<Predicate>,
     pub limit: Option<usize>,
 }
diff --git a/docs/src/c-binding.md b/docs/src/c-binding.md
index 6c7cf661..ad2f8469 100644
--- a/docs/src/c-binding.md
+++ b/docs/src/c-binding.md
@@ -78,6 +78,28 @@ LD_LIBRARY_PATH=target/release ./example /path/to/warehouse
 DYLD_LIBRARY_PATH=target/release ./example /path/to/warehouse
 ```
 
+## Structured Projections
+
+`paimon_read_builder_with_read_type_json` accepts a JSON array of Paimon
+DataFields for nested projections. Each field retains its schema ID and 
selected
+recursive type, for example:
+
+```json
+[{"id":1,"name":"payload","type":{"type":"ROW","fields":[{"id":2,"name":"selected","type":"INT"}]}}]
+```
+
+Use the IDs from the resolved table schema. This selects `payload.selected`
+without requesting the other fields of `payload`; ARRAY elements and MAP values
+can likewise carry projected ROW types. It uses the core `with_read_type`
+contract, including schema-evolution and format-specific validation. It changes
+the read type, not the table's stored schema.
+
+The JSON is copied during the call. The last successful call to this API or
+`paimon_read_builder_with_projection` selects the projection; JSON decoding 
errors
+leave the previous selection intact. `[]` selects zero columns while retaining
+row counts, and a null pointer clears the projection. Case sensitivity applies
+to name projections; an explicit read type keeps its supplied field identities.
+
 ## Opening and Scanning a Table
 
 The following program opens `default.my_table` from a filesystem catalog and

Reply via email to