SteNicholas commented on code in PR #1448:
URL: https://github.com/apache/paimon-rust/pull/1448#discussion_r4670419577
##########
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:
Fixed in `b5efd68d`. The relation planner reserves live-table qualifiers
before assigning implicit snapshot bindings. In the reported query, `t.id`
binds to the live scan when it is written as `paimon.default.t`. The regression
runs that query through CTAS and checks that the persisted count is 3. It also
covers live and snapshot scans with the same name across catalogs. [CTAS
regression](https://github.com/SteNicholas/paimon-rust/blob/b5efd68d4acc825e3a6bbb0a1bd4a6ecaa8d0fa2/crates/integrations/datafusion/tests/time_travel_schema_tests.rs#L399-L479)
##########
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:
Fixed in `b5efd68d`. A direct HTTP 501 on the first conditional `schema-0`
PUT allows ordinary `CREATE TABLE` to fall back to a plain PUT. Exclusive
creation reports `IoUnsupported` in that case. The mock also verifies that a
501 after a retry, 303 and 307 redirects, and a 503 carrying
`PreconditionFailed` propagate an unknown outcome without a plain PUT. [S3
regression](https://github.com/SteNicholas/paimon-rust/blob/b5efd68d4acc825e3a6bbb0a1bd4a6ecaa8d0fa2/crates/paimon/src/io/storage_s3.rs#L784-L825)
##########
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:
Fixed in `b5efd68d`. Both native publication tests now use
`local_file_path`. The helper normalizes a Windows drive path to the supported
`file:/C:/...` form so the tests reach the injected unsupported and timeout
outcomes. Both regressions passed locally on macOS. [Path
helper](https://github.com/SteNicholas/paimon-rust/blob/b5efd68d4acc825e3a6bbb0a1bd4a6ecaa8d0fa2/crates/paimon/src/io/file_io.rs#L2216-L2224)
ยท [Native publication
regressions](https://github.com/SteNicholas/paimon-rust/blob/b5efd68d4acc825e3a6bbb0a1bd4a6ecaa8d0fa2/crates/paimon/src/io/file_io.rs#L4724-L4795)
--
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]