JingsongLi commented on code in PR #1448:
URL: https://github.com/apache/paimon-rust/pull/1448#discussion_r4665566919


##########
crates/paimon/src/io/file_io.rs:
##########
@@ -4532,6 +4650,79 @@ mod input_output_test {
         );
     }
 
+    #[cfg(feature = "storage-fs")]
+    #[tokio::test]
+    async fn 
test_native_publication_unsupported_allows_only_optional_fallback() {
+        let directory = tempfile::tempdir().unwrap();
+        let path = format!("file:{}/schema-0", directory.path().display());

Review Comment:
   **[P2] Use a portable path in the two native publication tests**
   
   The Windows unit job fails 
`test_native_publication_unsupported_allows_only_optional_fallback` at the 
expected error-kind check and 
`test_native_publication_propagates_uncertain_outcome` because `schema-0` is 
missing. On Windows this builds `file:C:\\…`, and `fs_relative_path` recognizes 
`file:/…` or a native drive path. Construct the path that way in both tests so 
they reach the injected publication result. The repository has a 
`local_file_path` fixture that uses the supported spelling. [Windows 
CI](https://github.com/apache/paimon-rust/actions/runs/45165082989/job/137659811150)



##########
crates/paimon/src/io/file_io.rs:
##########
@@ -990,57 +1066,92 @@ impl FileIO {
             // the bucket's default, never-enabled versioning configuration.
             && matches!(info.scheme(), "memory" | "s3" | "oss" | "gcs")
         {
-            op.write_with(&relative_path, bytes)
-                .if_not_exists(true)
-                .await
-                .map(|_| ())
+            self.conditional_publication(
+                path,
+                op.write_with(&relative_path, bytes).if_not_exists(true),
+            )
+            .await

Review Comment:
   **[P2] Preserve ordinary CREATE when an S3 endpoint rejects conditional PUT**
   
   OpenDAL advertises conditional PUT for the `s3` scheme, including configured 
S3-compatible endpoints. With a catalog-level S3 mock that accepts plain PUT 
and returns HTTP 501 `NotImplemented` for `If-None-Match: *`, ordinary 
`create_table` fails at `schema-0`. The previous schema writer uses plain PUT, 
which the same mock accepts. The optional fallback is reached only when the 
static capability check fails. Deployed endpoints such as ActiveScale OS 7.x 
explicitly reject this header on PUT. Please provide a way for ordinary 
creation to preserve the plain-write path when the endpoint definitively lacks 
the capability. Exclusive creation should still require it, and ambiguous 
responses should continue to surface as errors. [ActiveScale S3 API reference, 
PUT Object 
headers](https://qsupport.quantum.com/kb/flare/Content/ActiveScale/PDFs/Archive/Software/6-68960-01_RevA_ActiveScale_OS_7.x_S3_API_Reference_Guide.pdf#page=120)



##########
crates/integrations/datafusion/src/relation_planner.rs:
##########
@@ -39,6 +41,442 @@ use crate::catalog::{
 };
 use crate::table::{ObjectTableProvider, PaimonTableProvider};
 
+/// Resolves statement-local TABLE bindings to snapshot scans.
+#[derive(Debug)]
+pub(crate) struct SnapshotRelationPlanner {
+    bindings: HashMap<String, (TableReference, Arc<dyn TableProvider>)>,
+    display_qualifiers: HashMap<String, String>,
+    cte_names: HashSet<String>,
+}
+
+impl SnapshotRelationPlanner {
+    pub(crate) fn try_new(
+        mut bindings: HashMap<String, (TableReference, Arc<dyn 
TableProvider>)>,
+        statement: &mut ast::Statement,
+        normalize: bool,
+    ) -> DFResult<Self> {
+        let mut qualifiers = SnapshotQualifiers {
+            bindings: &bindings,
+            normalize,
+            private_bindings: HashSet::new(),
+            cte_names: HashSet::new(),
+            scopes: Vec::new(),
+            query_has_select: Vec::new(),
+            select_sources: Vec::new(),
+            ambiguous_qualifier: None,
+        };
+        let _ = statement.visit(&mut qualifiers);
+        if let Some(qualifier) = qualifiers.ambiguous_qualifier {
+            return Err(plan_datafusion_err!(
+                "Ambiguous snapshot qualifier '{qualifier}'. Use distinct 
aliases for the snapshot scans"
+            ));
+        }
+        let cte_names = qualifiers.cte_names;
+        let mut display_qualifiers = HashMap::new();
+        for name in qualifiers.private_bindings {
+            let (table, _) = bindings.get_mut(&name).unwrap();
+            display_qualifiers.insert(name.clone(), table.to_string());
+            *table = TableReference::bare(name);
+        }
+        Ok(Self {
+            bindings,
+            display_qualifiers,
+            cte_names,
+        })
+    }
+
+    /// DataFusion includes qualifiers in default expression names. Restore
+    /// their SQL spelling before a caller persists the schema or prepares it.
+    pub(crate) fn restore_output_names(&self, plan: LogicalPlan) -> 
DFResult<LogicalPlan> {
+        if self.display_qualifiers.is_empty() {
+            return Ok(plan);
+        }
+        if let LogicalPlan::Statement(Statement::Prepare(mut prepare)) = plan {
+            prepare.input =
+                
Arc::new(self.restore_output_names(Arc::unwrap_or_clone(prepare.input))?);
+            return Ok(LogicalPlan::Statement(Statement::Prepare(prepare)));
+        }
+        let mut renamed = false;
+        let projection = plan
+            .schema()
+            .columns()
+            .into_iter()
+            .map(|column| {
+                let mut name = column.name.clone();
+                for (binding, original) in &self.display_qualifiers {
+                    if name.contains(binding) {
+                        name = name.replace(binding, original);
+                    }
+                }
+                if name == column.name {
+                    Expr::Column(column)
+                } else {
+                    renamed = true;
+                    let qualifier = column.relation.clone();
+                    Expr::Column(column).alias_qualified(qualifier, name)
+                }
+            })
+            .collect::<Vec<_>>();
+        if renamed {
+            LogicalPlanBuilder::from(plan).project(projection)?.build()
+        } else {
+            Ok(plan)
+        }
+    }
+}
+
+#[derive(Clone)]
+enum ScopedQualifier {
+    Original,
+    Snapshot(String),
+    Ambiguous,
+}
+
+/// DataFusion matches a bare qualifier against the last component of a full
+/// table name. Bind colliding snapshots privately and resolve SQL qualifiers
+/// within their original scope before DataFusion plans the join.
+struct SnapshotQualifiers<'a> {
+    bindings: &'a HashMap<String, (TableReference, Arc<dyn TableProvider>)>,
+    normalize: bool,
+    private_bindings: HashSet<String>,
+    cte_names: HashSet<String>,
+    scopes: Vec<HashMap<TableReference, ScopedQualifier>>,
+    query_has_select: Vec<bool>,
+    select_sources: Vec<Vec<ast::TableWithJoins>>,
+    ambiguous_qualifier: Option<TableReference>,
+}
+
+impl SnapshotQualifiers<'_> {
+    fn factors(group: &ast::TableWithJoins) -> impl DoubleEndedIterator<Item = 
&TableFactor> {
+        std::iter::once(&group.relation).chain(group.joins.iter().map(|join| 
&join.relation))
+    }
+
+    fn enter_scope<'a>(
+        &mut self,
+        factors: impl DoubleEndedIterator<Item = &'a TableFactor>,
+    ) -> bool {
+        let mut sources = Vec::new();
+        let mut snapshots = Vec::new();
+        let mut pending: Vec<_> = factors.rev().collect();
+        let normalizer = 
datafusion::sql::planner::IdentNormalizer::new(self.normalize);
+        while let Some(factor) = pending.pop() {
+            let alias = match factor {
+                TableFactor::TableFunction {
+                    expr: ast::Expr::Identifier(binding),
+                    alias: None,
+                } => {
+                    if let Some((table, _)) = 
self.bindings.get(&binding.value) {
+                        snapshots.push((table.clone(), 
Some(binding.value.clone())));
+                    }
+                    continue;
+                }
+                TableFactor::Table {
+                    name,
+                    args: None,
+                    alias: None,
+                    ..
+                } => {
+                    if let Ok(table) = 
datafusion::sql::planner::object_name_to_table_reference(
+                        name.clone(),
+                        self.normalize,
+                    ) {
+                        sources.push((table, None));
+                    }
+                    continue;
+                }
+                TableFactor::NestedJoin {
+                    table_with_joins,
+                    alias: None,
+                } => {
+                    pending.extend(Self::factors(table_with_joins).rev());
+                    continue;
+                }
+                TableFactor::NestedJoin { alias, .. }
+                | TableFactor::Table { alias, .. }
+                | TableFactor::Derived { alias, .. }
+                | TableFactor::Function { alias, .. }
+                | TableFactor::UNNEST { alias, .. }
+                | TableFactor::TableFunction { alias, .. } => alias,
+                _ => continue,
+            };
+            if let Some(alias) = alias {
+                sources.push((
+                    
TableReference::bare(normalizer.normalize(alias.name.clone())),
+                    None,
+                ));
+            }
+        }
+
+        // An explicit alias can shadow an implicit snapshot qualifier.
+        sources.extend(snapshots);
+        let mut reserved = HashMap::<&str, Vec<&TableReference>>::new();
+        let mut scope = HashMap::new();
+        let mut has_private_binding = false;
+        for (table, binding) in &sources {
+            let names = reserved.entry(table.table()).or_default();
+            let qualifier = if let Some(binding) = binding {
+                if names.iter().any(|name| name.resolved_eq(table)) {
+                    self.private_bindings.insert(binding.clone());
+                }
+                has_private_binding |= self.private_bindings.contains(binding);
+                ScopedQualifier::Snapshot(binding.clone())
+            } else {
+                ScopedQualifier::Original
+            };
+            names.push(table);
+            scope
+                .entry(table.clone())
+                .and_modify(|existing| {
+                    if matches!(existing, ScopedQualifier::Snapshot(_))
+                        && matches!(&qualifier, ScopedQualifier::Snapshot(_))
+                    {
+                        *existing = ScopedQualifier::Ambiguous;
+                    }
+                })
+                .or_insert(qualifier);
+        }
+        // Exact names win over suffixes, so both db.t.id and an explicit t.id
+        // can refer to different scans even when their table names coincide.
+        for (table, _) in &sources {
+            if let Some(schema) = table.schema() {
+                let binding = scope[table].clone();
+                scope
+                    .entry(TableReference::partial(schema, table.table()))
+                    .or_insert_with(|| binding.clone());
+                scope
+                    .entry(TableReference::bare(table.table()))
+                    .or_insert(binding);

Review Comment:
   **[P1] Preserve the live table binding when its name is fully qualified**
   
   Using the existing evolved-table fixture, `SELECT COUNT(*) FROM t VERSION AS 
OF 1 CROSS JOIN t WHERE t.id = 5` returns 3. Changing only the live relation to 
`paimon.default.t` returns 0. The live relation reserves its full name, the 
snapshot takes the `t` key, and the suffix pass leaves `t.id` bound to the 
snapshot. The previous planner rewrote the snapshot to an internal name, so 
`t.id` referred to the live scan in both spellings. A CTAS using this source 
can persist the wrong result. Please preserve the live binding across the 
equivalent names and cover the fully qualified form in the join regression test.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to