Skip to main content

paimon_datafusion/
relation_planner.rs

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 `VERSION AS OF` and `TIMESTAMP AS OF`.
19
20use std::collections::HashMap;
21use std::fmt::Debug;
22use std::sync::Arc;
23
24use datafusion::catalog::default_table_source::{provider_as_source, source_as_provider};
25use datafusion::common::TableReference;
26use datafusion::error::Result as DFResult;
27use datafusion::logical_expr::builder::LogicalPlanBuilder;
28use datafusion::logical_expr::planner::{
29    PlannedRelation, RelationPlanner, RelationPlannerContext, RelationPlanning,
30};
31use datafusion::sql::sqlparser::ast::{self, TableFactor, TableVersion};
32use paimon::spec::{SCAN_TIMESTAMP_MILLIS_OPTION, SCAN_VERSION_OPTION};
33
34use crate::table::PaimonTableProvider;
35
36/// A [`RelationPlanner`] that intercepts `VERSION AS OF` and `TIMESTAMP AS OF`
37/// clauses on Paimon tables and resolves them to time travel options.
38///
39/// - `VERSION AS OF <integer or string>` → sets `scan.version` option on the table.
40///   At scan time, the version is resolved: tag name (if exists) → snapshot id → error.
41/// - `TIMESTAMP AS OF <timestamp string>` → parsed as a timestamp, sets `scan.timestamp-millis`.
42#[derive(Debug)]
43pub struct PaimonRelationPlanner;
44
45impl PaimonRelationPlanner {
46    pub fn new() -> Self {
47        Self
48    }
49}
50
51impl Default for PaimonRelationPlanner {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl RelationPlanner for PaimonRelationPlanner {
58    fn plan_relation(
59        &self,
60        relation: TableFactor,
61        context: &mut dyn RelationPlannerContext,
62    ) -> DFResult<RelationPlanning> {
63        // Only handle Table factors with a version clause.
64        let TableFactor::Table {
65            ref name,
66            ref version,
67            ..
68        } = relation
69        else {
70            return Ok(RelationPlanning::Original(Box::new(relation)));
71        };
72
73        let extra_options = match version {
74            Some(TableVersion::VersionAsOf(expr)) => resolve_version_as_of(expr)?,
75            Some(TableVersion::TimestampAsOf(expr)) => resolve_timestamp_as_of(expr)?,
76            _ => return Ok(RelationPlanning::Original(Box::new(relation))),
77        };
78
79        // Resolve the table reference.
80        let table_ref = object_name_to_table_reference(name, context)?;
81        let source = context
82            .context_provider()
83            .get_table_source(table_ref.clone())?;
84        let provider = source_as_provider(&source)?;
85
86        // Check if this is a Paimon table.
87        let Some(paimon_provider) = provider.downcast_ref::<PaimonTableProvider>() else {
88            return Ok(RelationPlanning::Original(Box::new(relation)));
89        };
90
91        // Resolving time travel may switch the table to the snapshot's schema,
92        // which requires async IO; this planner hook is synchronous, so bridge
93        // through the shared runtime like other sync DataFusion callbacks.
94        let table = paimon_provider.table().clone();
95        let new_table = crate::runtime::block_on_with_runtime(
96            async move { table.copy_with_time_travel(extra_options).await },
97            "paimon time travel resolution thread panicked",
98        )
99        .map_err(crate::to_datafusion_error)?;
100        let new_provider = PaimonTableProvider::try_new(new_table)?;
101        let new_source = provider_as_source(Arc::new(new_provider));
102
103        // Destructure to get alias.
104        let TableFactor::Table { alias, .. } = relation else {
105            unreachable!()
106        };
107
108        let plan = LogicalPlanBuilder::scan(table_ref, new_source, None)?.build()?;
109        Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
110            plan, alias,
111        ))))
112    }
113}
114
115/// Convert a sqlparser `ObjectName` to a DataFusion `TableReference`.
116fn object_name_to_table_reference(
117    name: &ast::ObjectName,
118    context: &mut dyn RelationPlannerContext,
119) -> DFResult<TableReference> {
120    let idents: Vec<String> = name
121        .0
122        .iter()
123        .map(|part| {
124            let ident = part.as_ident().ok_or_else(|| {
125                datafusion::error::DataFusionError::Plan(format!(
126                    "Expected simple identifier in table reference, got: {part}"
127                ))
128            })?;
129            Ok(context.normalize_ident(ident.clone()))
130        })
131        .collect::<DFResult<_>>()?;
132    match idents.len() {
133        1 => Ok(TableReference::bare(idents[0].clone())),
134        2 => Ok(TableReference::partial(
135            idents[0].clone(),
136            idents[1].clone(),
137        )),
138        3 => Ok(TableReference::full(
139            idents[0].clone(),
140            idents[1].clone(),
141            idents[2].clone(),
142        )),
143        _ => Err(datafusion::error::DataFusionError::Plan(format!(
144            "Unsupported table reference: {name}"
145        ))),
146    }
147}
148
149/// Resolve `VERSION AS OF <expr>` into `scan.version` option.
150///
151/// The raw value (integer or string) is passed through as-is.
152/// Resolution (tag vs snapshot id) happens at scan time in `TableScan`.
153fn resolve_version_as_of(expr: &ast::Expr) -> DFResult<HashMap<String, String>> {
154    let version = match expr {
155        ast::Expr::Value(v) => match &v.value {
156            ast::Value::Number(n, _) => n.clone(),
157            ast::Value::SingleQuotedString(s) | ast::Value::DoubleQuotedString(s) => s.clone(),
158            _ => {
159                return Err(datafusion::error::DataFusionError::Plan(format!(
160                    "Unsupported VERSION AS OF expression: {expr}"
161                )))
162            }
163        },
164        _ => {
165            return Err(datafusion::error::DataFusionError::Plan(format!(
166                "Unsupported VERSION AS OF expression: {expr}. Expected an integer snapshot id or a tag name."
167            )))
168        }
169    };
170    Ok(HashMap::from([(SCAN_VERSION_OPTION.to_string(), version)]))
171}
172
173/// Resolve `TIMESTAMP AS OF <expr>` into `scan.timestamp-millis` option.
174fn resolve_timestamp_as_of(expr: &ast::Expr) -> DFResult<HashMap<String, String>> {
175    match expr {
176        ast::Expr::Value(v) => match &v.value {
177            ast::Value::SingleQuotedString(s) | ast::Value::DoubleQuotedString(s) => {
178                let millis = parse_timestamp_to_millis(s)?;
179                Ok(HashMap::from([(
180                    SCAN_TIMESTAMP_MILLIS_OPTION.to_string(),
181                    millis.to_string(),
182                )]))
183            }
184            _ => Err(datafusion::error::DataFusionError::Plan(format!(
185                "Unsupported TIMESTAMP AS OF expression: {expr}. Expected a timestamp string."
186            ))),
187        },
188        _ => Err(datafusion::error::DataFusionError::Plan(format!(
189            "Unsupported TIMESTAMP AS OF expression: {expr}. Expected a timestamp string."
190        ))),
191    }
192}
193
194/// Parse a timestamp string to milliseconds since epoch (using local timezone).
195///
196/// Matches Java Paimon's behavior which uses `TimeZone.getDefault()`.
197fn parse_timestamp_to_millis(ts: &str) -> DFResult<i64> {
198    use chrono::{Local, NaiveDateTime, TimeZone};
199
200    let naive = NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").map_err(|e| {
201        datafusion::error::DataFusionError::Plan(format!(
202            "Cannot parse time travel timestamp '{ts}': {e}. Expected format: YYYY-MM-DD HH:MM:SS"
203        ))
204    })?;
205    let local = Local.from_local_datetime(&naive).single().ok_or_else(|| {
206        datafusion::error::DataFusionError::Plan(format!("Ambiguous or invalid local time: '{ts}'"))
207    })?;
208    Ok(local.timestamp_millis())
209}