|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Custom [`RelationPlanner`] for Paimon time travel via `FOR SYSTEM_TIME AS OF`. |
| 19 | +
|
| 20 | +use std::collections::HashMap; |
| 21 | +use std::fmt::Debug; |
| 22 | +use std::sync::Arc; |
| 23 | + |
| 24 | +use datafusion::catalog::default_table_source::{provider_as_source, source_as_provider}; |
| 25 | +use datafusion::common::TableReference; |
| 26 | +use datafusion::error::Result as DFResult; |
| 27 | +use datafusion::logical_expr::builder::LogicalPlanBuilder; |
| 28 | +use datafusion::logical_expr::planner::{ |
| 29 | + PlannedRelation, RelationPlanner, RelationPlannerContext, RelationPlanning, |
| 30 | +}; |
| 31 | +use datafusion::sql::sqlparser::ast::{self, TableFactor, TableVersion}; |
| 32 | +use paimon::spec::{SCAN_SNAPSHOT_ID_OPTION, SCAN_TIMESTAMP_MILLIS_OPTION}; |
| 33 | + |
| 34 | +use crate::table::PaimonTableProvider; |
| 35 | + |
| 36 | +/// A [`RelationPlanner`] that intercepts `FOR SYSTEM_TIME AS OF` clauses |
| 37 | +/// on Paimon tables and resolves them to time travel options. |
| 38 | +/// |
| 39 | +/// - Integer literal → sets `scan.snapshot-id` option on the table. |
| 40 | +/// - String literal → parsed as a timestamp, sets `scan.timestamp-millis` option. |
| 41 | +#[derive(Debug)] |
| 42 | +pub struct PaimonRelationPlanner; |
| 43 | + |
| 44 | +impl PaimonRelationPlanner { |
| 45 | + pub fn new() -> Self { |
| 46 | + Self |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl Default for PaimonRelationPlanner { |
| 51 | + fn default() -> Self { |
| 52 | + Self::new() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl RelationPlanner for PaimonRelationPlanner { |
| 57 | + fn plan_relation( |
| 58 | + &self, |
| 59 | + relation: TableFactor, |
| 60 | + context: &mut dyn RelationPlannerContext, |
| 61 | + ) -> DFResult<RelationPlanning> { |
| 62 | + // Only handle Table factors with a version clause. |
| 63 | + let TableFactor::Table { |
| 64 | + ref name, |
| 65 | + ref version, |
| 66 | + .. |
| 67 | + } = relation |
| 68 | + else { |
| 69 | + return Ok(RelationPlanning::Original(relation)); |
| 70 | + }; |
| 71 | + |
| 72 | + let version_expr = match version { |
| 73 | + Some(TableVersion::ForSystemTimeAsOf(expr)) => expr.clone(), |
| 74 | + _ => return Ok(RelationPlanning::Original(relation)), |
| 75 | + }; |
| 76 | + |
| 77 | + // Resolve the table reference. |
| 78 | + let table_ref = object_name_to_table_reference(name, context)?; |
| 79 | + let source = context |
| 80 | + .context_provider() |
| 81 | + .get_table_source(table_ref.clone())?; |
| 82 | + let provider = source_as_provider(&source)?; |
| 83 | + |
| 84 | + // Check if this is a Paimon table. |
| 85 | + let Some(paimon_provider) = provider.as_any().downcast_ref::<PaimonTableProvider>() else { |
| 86 | + return Ok(RelationPlanning::Original(relation)); |
| 87 | + }; |
| 88 | + |
| 89 | + let extra_options = resolve_time_travel_options(&version_expr)?; |
| 90 | + let new_table = paimon_provider.table().copy_with_options(extra_options); |
| 91 | + let new_provider = PaimonTableProvider::try_new(new_table)?; |
| 92 | + let new_source = provider_as_source(Arc::new(new_provider)); |
| 93 | + |
| 94 | + // Destructure to get alias. |
| 95 | + let TableFactor::Table { alias, .. } = relation else { |
| 96 | + unreachable!() |
| 97 | + }; |
| 98 | + |
| 99 | + let plan = LogicalPlanBuilder::scan(table_ref, new_source, None)?.build()?; |
| 100 | + Ok(RelationPlanning::Planned(PlannedRelation::new(plan, alias))) |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +/// Convert a sqlparser `ObjectName` to a DataFusion `TableReference`. |
| 105 | +fn object_name_to_table_reference( |
| 106 | + name: &ast::ObjectName, |
| 107 | + context: &mut dyn RelationPlannerContext, |
| 108 | +) -> DFResult<TableReference> { |
| 109 | + let idents: Vec<String> = name |
| 110 | + .0 |
| 111 | + .iter() |
| 112 | + .map(|part| { |
| 113 | + let ident = part.as_ident().ok_or_else(|| { |
| 114 | + datafusion::error::DataFusionError::Plan(format!( |
| 115 | + "Expected simple identifier in table reference, got: {part}" |
| 116 | + )) |
| 117 | + })?; |
| 118 | + Ok(context.normalize_ident(ident.clone())) |
| 119 | + }) |
| 120 | + .collect::<DFResult<_>>()?; |
| 121 | + match idents.len() { |
| 122 | + 1 => Ok(TableReference::bare(idents[0].clone())), |
| 123 | + 2 => Ok(TableReference::partial( |
| 124 | + idents[0].clone(), |
| 125 | + idents[1].clone(), |
| 126 | + )), |
| 127 | + 3 => Ok(TableReference::full( |
| 128 | + idents[0].clone(), |
| 129 | + idents[1].clone(), |
| 130 | + idents[2].clone(), |
| 131 | + )), |
| 132 | + _ => Err(datafusion::error::DataFusionError::Plan(format!( |
| 133 | + "Unsupported table reference: {name}" |
| 134 | + ))), |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +/// Resolve `FOR SYSTEM_TIME AS OF <expr>` into table options. |
| 139 | +/// |
| 140 | +/// - Integer literal → `{"scan.snapshot-id": "N"}` |
| 141 | +/// - String literal (timestamp) → parse to millis → `{"scan.timestamp-millis": "M"}` |
| 142 | +fn resolve_time_travel_options(expr: &ast::Expr) -> DFResult<HashMap<String, String>> { |
| 143 | + match expr { |
| 144 | + ast::Expr::Value(v) => match &v.value { |
| 145 | + ast::Value::Number(n, _) => { |
| 146 | + // Validate it's a valid integer |
| 147 | + n.parse::<i64>().map_err(|e| { |
| 148 | + datafusion::error::DataFusionError::Plan(format!( |
| 149 | + "Invalid snapshot id '{n}': {e}" |
| 150 | + )) |
| 151 | + })?; |
| 152 | + Ok(HashMap::from([( |
| 153 | + SCAN_SNAPSHOT_ID_OPTION.to_string(), |
| 154 | + n.clone(), |
| 155 | + )])) |
| 156 | + } |
| 157 | + ast::Value::SingleQuotedString(s) | ast::Value::DoubleQuotedString(s) => { |
| 158 | + let timestamp_millis = parse_timestamp_to_millis(s)?; |
| 159 | + Ok(HashMap::from([( |
| 160 | + SCAN_TIMESTAMP_MILLIS_OPTION.to_string(), |
| 161 | + timestamp_millis.to_string(), |
| 162 | + )])) |
| 163 | + } |
| 164 | + _ => Err(datafusion::error::DataFusionError::Plan(format!( |
| 165 | + "Unsupported time travel expression: {expr}" |
| 166 | + ))), |
| 167 | + }, |
| 168 | + _ => Err(datafusion::error::DataFusionError::Plan(format!( |
| 169 | + "Unsupported time travel expression: {expr}. Expected an integer snapshot id or a timestamp string." |
| 170 | + ))), |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +/// Parse a timestamp string to milliseconds since epoch (using local timezone). |
| 175 | +/// |
| 176 | +/// Matches Java Paimon's behavior which uses `TimeZone.getDefault()`. |
| 177 | +fn parse_timestamp_to_millis(ts: &str) -> DFResult<i64> { |
| 178 | + use chrono::{Local, NaiveDateTime, TimeZone}; |
| 179 | + |
| 180 | + let naive = NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").map_err(|e| { |
| 181 | + datafusion::error::DataFusionError::Plan(format!( |
| 182 | + "Cannot parse time travel timestamp '{ts}': {e}. Expected format: YYYY-MM-DD HH:MM:SS" |
| 183 | + )) |
| 184 | + })?; |
| 185 | + let local = Local.from_local_datetime(&naive).single().ok_or_else(|| { |
| 186 | + datafusion::error::DataFusionError::Plan(format!("Ambiguous or invalid local time: '{ts}'")) |
| 187 | + })?; |
| 188 | + Ok(local.timestamp_millis()) |
| 189 | +} |
0 commit comments