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 fc58deab [datafusion] Support GROUP_CONCAT and SHOW CREATE VIEW (#1427)
fc58deab is described below
commit fc58deab6cf9ae77b05484dfa6c77f4107a9af93
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 17 18:24:13 2026 +0800
[datafusion] Support GROUP_CONCAT and SHOW CREATE VIEW (#1427)
---
crates/integrations/datafusion/src/catalog.rs | 127 +---
.../datafusion/src/compat_functions.rs | 67 +++
.../datafusion/src/expression_compat.rs | 136 ++++-
crates/integrations/datafusion/src/sql_context.rs | 665 ++++++++++++++++++++-
crates/integrations/datafusion/src/sql_function.rs | 450 +++++++++++++-
.../datafusion/tests/sql_compatibility.rs | 458 ++++++++++++++
docs/src/sql.md | 38 ++
7 files changed, 1829 insertions(+), 112 deletions(-)
diff --git a/crates/integrations/datafusion/src/catalog.rs
b/crates/integrations/datafusion/src/catalog.rs
index 7b1b0594..fa6c3bc7 100644
--- a/crates/integrations/datafusion/src/catalog.rs
+++ b/crates/integrations/datafusion/src/catalog.rs
@@ -31,7 +31,7 @@ use datafusion::execution::SessionState;
use datafusion::logical_expr::{expr_fn::cast, Expr, LogicalPlan,
LogicalPlanBuilder};
use datafusion::prelude::SessionContext;
use datafusion::sql::planner::IdentNormalizer;
-use datafusion::sql::sqlparser::ast::{Ident, ObjectName, Query, Statement,
Visit, Visitor};
+use datafusion::sql::sqlparser::ast::{Ident, ObjectName, Statement};
use datafusion::sql::sqlparser::dialect::GenericDialect;
use datafusion::sql::sqlparser::parser::Parser;
use paimon::catalog::{Catalog, Identifier, View};
@@ -1461,7 +1461,7 @@ async fn validate_view_dependencies(
fn view_relation_identifiers(view: &View, catalog_name: &str) ->
DFResult<Vec<Identifier>> {
let regex_sql =
crate::regex_operators::parseable_sql(view.query_for("datafusion"))?;
let parseable = crate::lateral_views::parseable_sql(regex_sql.as_ref())?;
- let statements =
+ let mut statements =
Parser::parse_sql(&GenericDialect {},
parseable.as_ref()).map_err(|error| {
plan_datafusion_err!(
"Invalid SQL for REST catalog view '{}': {error}",
@@ -1474,115 +1474,42 @@ fn view_relation_identifiers(view: &View,
catalog_name: &str) -> DFResult<Vec<Id
view.full_name()
));
}
- if !matches!(statements.first(), Some(Statement::Query(_))) {
+ let Some(Statement::Query(query)) = statements.first() else {
return Err(plan_datafusion_err!(
"REST catalog view '{}' must contain a single read-only query",
view.full_name()
));
- }
-
- let mut visitor = ViewRelationVisitor::new(catalog_name,
view.identifier().database());
- let _: std::ops::ControlFlow<()> = statements.visit(&mut visitor);
- Ok(visitor.identifiers)
-}
-
-type SqlIdentifierKey = String;
-
-struct QueryCteScope {
- visible: HashSet<SqlIdentifierKey>,
- cte_query_visibility: HashMap<usize, HashSet<SqlIdentifierKey>>,
-}
-
-struct ViewRelationVisitor<'a> {
- catalog_name: &'a str,
- current_database: &'a str,
- scopes: Vec<QueryCteScope>,
- identifiers: Vec<Identifier>,
-}
-
-impl<'a> ViewRelationVisitor<'a> {
- fn new(catalog_name: &'a str, current_database: &'a str) -> Self {
- Self {
- catalog_name,
- current_database,
- scopes: Vec::new(),
- identifiers: Vec::new(),
- }
- }
-}
+ };
-impl Visitor for ViewRelationVisitor<'_> {
- type Break = ();
-
- fn pre_visit_query(&mut self, query: &Query) ->
std::ops::ControlFlow<Self::Break> {
- let query_address = query as *const Query as usize;
- let inherited = self
- .scopes
- .last()
- .map(|scope| {
- scope
- .cte_query_visibility
- .get(&query_address)
- .unwrap_or(&scope.visible)
- .clone()
- })
- .unwrap_or_default();
- let mut visible = inherited.clone();
- let mut cte_query_visibility = HashMap::new();
-
- if let Some(with) = &query.with {
- let local_ctes = with
- .cte_tables
- .iter()
- .map(|cte| sql_identifier_key(&cte.alias.name))
- .collect::<Vec<_>>();
- if with.recursive {
- visible.extend(local_ctes);
- for cte in &with.cte_tables {
- cte_query_visibility
- .insert(cte.query.as_ref() as *const Query as usize,
visible.clone());
- }
- } else {
- for (cte, alias) in with.cte_tables.iter().zip(local_ctes) {
- cte_query_visibility
- .insert(cte.query.as_ref() as *const Query as usize,
visible.clone());
- visible.insert(alias);
- }
- }
+ let mut identifiers = Vec::new();
+ crate::sql_function::visit_view_table_dependencies(query, true, &mut
|relation| {
+ if let Some(identifier) =
+ relation_identifier(relation, catalog_name,
view.identifier().database())
+ {
+ identifiers.push(identifier);
}
-
- self.scopes.push(QueryCteScope {
- visible,
- cte_query_visibility,
- });
- std::ops::ControlFlow::Continue(())
- }
-
- fn post_visit_query(&mut self, _query: &Query) ->
std::ops::ControlFlow<Self::Break> {
- self.scopes.pop();
- std::ops::ControlFlow::Continue(())
- }
-
- fn pre_visit_relation(&mut self, relation: &ObjectName) ->
std::ops::ControlFlow<Self::Break> {
- let is_cte = match relation.0.as_slice() {
- [part] => part.as_ident().is_some_and(|identifier| {
- self.scopes
- .last()
- .is_some_and(|scope|
scope.visible.contains(&sql_identifier_key(identifier)))
- }),
- _ => false,
- };
- if !is_cte {
- if let Some(identifier) =
- relation_identifier(relation, self.catalog_name,
self.current_database)
- {
- self.identifiers.push(identifier);
+ Ok(())
+ })?;
+ // Preserve all native metadata lookup edges too, including prefetch-only
+ // syntax, without interpreting every relation lookup as a physical
binding.
+ let statement =
datafusion::sql::parser::Statement::Statement(Box::new(statements.remove(0)));
+ let (prefetched, _) =
datafusion::sql::resolve::resolve_table_references(&statement, true)?;
+ let mut seen = identifiers.iter().cloned().collect::<HashSet<_>>();
+ for reference in prefetched {
+ let resolved = reference.resolve(catalog_name,
view.identifier().database());
+ if resolved.catalog.as_ref() == catalog_name {
+ let identifier =
+ Identifier::new(resolved.schema.to_string(),
resolved.table.to_string());
+ if seen.insert(identifier.clone()) {
+ identifiers.push(identifier);
}
}
- std::ops::ControlFlow::Continue(())
}
+ Ok(identifiers)
}
+type SqlIdentifierKey = String;
+
fn sql_identifier_key(identifier: &Ident) -> SqlIdentifierKey {
IdentNormalizer::default().normalize(identifier.clone())
}
diff --git a/crates/integrations/datafusion/src/compat_functions.rs
b/crates/integrations/datafusion/src/compat_functions.rs
index 9de2033e..e156b16e 100644
--- a/crates/integrations/datafusion/src/compat_functions.rs
+++ b/crates/integrations/datafusion/src/compat_functions.rs
@@ -33,6 +33,9 @@ use std::collections::HashMap;
use std::sync::Arc;
pub(crate) fn register_compat_functions(ctx: &SessionContext) {
+ ctx.register_udf(ScalarUDF::from(GroupConcatRow {
+ signature: Signature::variadic(vec![DataType::Utf8],
Volatility::Immutable),
+ }));
crate::approx_percentile::register(ctx);
for (name, alias) in [
("current_date", "curdate"),
@@ -60,6 +63,70 @@ pub(crate) fn register_compat_functions(ctx:
&SessionContext) {
}
}
+/// Concatenate a GROUP_CONCAT row, skipping the entire row if any input is
NULL.
+/// DataFusion evaluates the arguments before invoking the UDF, including
+/// volatile expressions, so each SQL argument is evaluated exactly once.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct GroupConcatRow {
+ signature: Signature,
+}
+
+impl ScalarUDFImpl for GroupConcatRow {
+ fn name(&self) -> &str {
+ "__paimon_group_concat_row"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ let scalar = args
+ .args
+ .iter()
+ .all(|arg| matches!(arg, ColumnarValue::Scalar(_)));
+ let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+ let arrays = arrays
+ .iter()
+ .map(|array| cast(array, &DataType::Utf8))
+ .collect::<std::result::Result<Vec<_>, _>>()?;
+ let strings = arrays
+ .iter()
+ .map(|array| array.as_any().downcast_ref::<StringArray>().unwrap())
+ .collect::<Vec<_>>();
+ let Some(first) = strings.first() else {
+ return Err(DataFusionError::Execution(
+ "GROUP_CONCAT row requires arguments".into(),
+ ));
+ };
+ let mut output = StringBuilder::new();
+ let mut value = String::new();
+ for row in 0..first.len() {
+ if strings.iter().any(|array| array.is_null(row)) {
+ output.append_null();
+ } else {
+ value.clear();
+ for array in &strings {
+ value.push_str(array.value(row));
+ }
+ output.append_value(&value);
+ }
+ }
+ let output: ArrayRef = Arc::new(output.finish());
+ if scalar {
+ Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &output, 0,
+ )?))
+ } else {
+ Ok(ColumnarValue::Array(output))
+ }
+ }
+}
+
// DataFusion 54's with_aliases wrapper does not forward configuration updates.
// Keep the native function registered separately and forward timezone changes
// and simplification to the alias's own native implementation.
diff --git a/crates/integrations/datafusion/src/expression_compat.rs
b/crates/integrations/datafusion/src/expression_compat.rs
index 0f19b9f2..72d7753f 100644
--- a/crates/integrations/datafusion/src/expression_compat.rs
+++ b/crates/integrations/datafusion/src/expression_compat.rs
@@ -17,10 +17,11 @@
use datafusion::common::{DataFusionError, Result};
use datafusion::execution::SessionState;
+use datafusion::logical_expr::Volatility;
use datafusion::sql::sqlparser::ast::{
- DuplicateTreatment, Expr, Function, FunctionArg, FunctionArgExpr,
FunctionArgumentClause,
- FunctionArguments, Ident, NullTreatment, ObjectName, Select, SelectItem,
Statement, Value,
- VisitMut, VisitorMut,
+ visit_expressions, DuplicateTreatment, Expr, Function, FunctionArg,
FunctionArgExpr,
+ FunctionArgumentClause, FunctionArguments, Ident, NullTreatment,
ObjectName, Select,
+ SelectItem, Statement, Value, VisitMut, VisitorMut,
};
use datafusion::sql::sqlparser::{dialect::GenericDialect, parser::Parser};
use std::ops::ControlFlow;
@@ -37,6 +38,7 @@ pub(crate) fn is_aggregate(name: &str) -> bool {
| "min_by"
| "arg_max"
| "listagg"
+ | "group_concat"
)
}
fn error(message: impl Into<String>) -> DataFusionError {
@@ -73,7 +75,10 @@ fn set_args(call: &mut Function, args: Vec<Expr>) {
.collect();
}
}
-fn lower_aggregate(call: &Function, name: &str) -> Result<Expr> {
+fn lower_aggregate(call: &Function, name: &str, state: &SessionState) ->
Result<Expr> {
+ if name == "group_concat" {
+ return lower_group_concat(call, state);
+ }
let args = arguments(call)?;
let mut lowered = call.clone();
if !call.within_group.is_empty() && name != "listagg" {
@@ -208,6 +213,127 @@ fn lower_aggregate(call: &Function, name: &str) ->
Result<Expr> {
Ok(Expr::Function(lowered))
}
+fn contains_volatile_function(expr: &Expr, state: &SessionState) -> bool {
+ matches!(
+ visit_expressions(expr, |expr| {
+ if let Expr::Function(call) = expr {
+ let name = if call.name.0.len() == 1 {
+ let Some(ident) = call.name.0[0].as_ident() else {
+ return ControlFlow::Continue(());
+ };
+ if ident.quote_style.is_some() {
+ ident.value.clone()
+ } else {
+ ident.value.to_ascii_lowercase()
+ }
+ } else {
+ call.name.to_string()
+ };
+ let volatile =
state.scalar_functions().get(&name).is_some_and(|function| {
+ function.signature().volatility == Volatility::Volatile
+ }) || state.higher_order_functions().get(&name).is_some_and(
+ |function| function.signature().volatility ==
Volatility::Volatile,
+ ) || state.aggregate_functions().get(&name).is_some_and(
+ |function| function.signature().volatility ==
Volatility::Volatile,
+ ) ||
state.window_functions().get(&name).is_some_and(|function| {
+ function.signature().volatility == Volatility::Volatile
+ });
+ if volatile {
+ return ControlFlow::Break(());
+ }
+ }
+ ControlFlow::Continue(())
+ }),
+ ControlFlow::Break(())
+ )
+}
+
+fn lower_group_concat(call: &Function, state: &SessionState) -> Result<Expr> {
+ let args = arguments(call)?;
+ if args.is_empty() || !call.within_group.is_empty() ||
call.null_treatment.is_some() {
+ return Err(error(
+ "GROUP_CONCAT requires expressions and does not accept WITHIN
GROUP or NULL modifiers",
+ ));
+ }
+ let mut aggregate = call.clone();
+ aggregate.name = ObjectName::from(vec![Ident::new("array_agg")]);
+ aggregate.null_treatment = Some(NullTreatment::IgnoreNulls);
+ let FunctionArguments::List(list) = &mut aggregate.args else {
+ unreachable!()
+ };
+ if args.len() > 1 && list.duplicate_treatment ==
Some(DuplicateTreatment::Distinct) {
+ return Err(error("GROUP_CONCAT DISTINCT supports one expression"));
+ }
+ let mut separator = None;
+ let mut clauses = Vec::new();
+ for clause in &list.clauses {
+ match clause {
+ FunctionArgumentClause::Separator(value) => {
+ if separator.is_some() || !matches!(value.value,
Value::SingleQuotedString(_)) {
+ return Err(error("GROUP_CONCAT SEPARATOR must be one
string literal"));
+ }
+ separator = Some(Expr::Value(value.clone()));
+ }
+ FunctionArgumentClause::OrderBy(ordering) => {
+ let mut ordering = ordering.clone();
+ for key in &mut ordering {
+ if let Expr::Value(value) = &key.expr {
+ if let Value::Number(number, _) = &value.value {
+ if number.chars().all(|ch| ch.is_ascii_digit()) {
+ let index = number
+ .parse::<usize>()
+ .ok()
+ .and_then(|index| index.checked_sub(1))
+ .filter(|index| *index < args.len())
+ .ok_or_else(|| {
+ error(format!(
+ "GROUP_CONCAT ORDER BY position must
be between 1 and {}",
+ args.len()
+ ))
+ })?;
+ if contains_volatile_function(&args[index],
state) {
+ return Err(error("GROUP_CONCAT ORDER BY
position cannot reference a volatile expression; compute the expression in a
subquery first"));
+ }
+ key.expr =
Expr::Nested(Box::new(args[index].clone()));
+ } else {
+ // DataFusion treats a bare numeric aggregate
sort key
+ // as an input-column index. Non-integer
literals here
+ // are ordinary constants, not argument
positions.
+ key.expr =
Expr::Nested(Box::new(key.expr.clone()));
+ }
+ }
+ }
+ }
+ clauses.push(FunctionArgumentClause::OrderBy(ordering));
+ }
+ _ => return Err(error("Unsupported GROUP_CONCAT argument
modifier")),
+ }
+ }
+ list.clauses = clauses;
+ let value = if args.len() == 1 {
+ args[0].clone()
+ } else {
+ // Evaluate every input once. A CASE-based NULL guard would evaluate
+ // volatile arguments again when concatenating the non-NULL row.
+ let strings = args
+ .iter()
+ .map(|arg| format!("CAST(({arg}) AS STRING)"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ expression(&format!("__paimon_group_concat_row({strings})"))?
+ };
+ set_args(&mut aggregate, vec![value]);
+ let separator = separator.unwrap_or(expression("','")?);
+ // Aggregate before converting to text so DISTINCT and numeric ORDER BY
+ // retain their original types. Empty/all-NULL groups return NULL, but a
+ // group containing an empty string still returns an empty string. Convert
+ // elements with Arrow's STRING cast after aggregation so all argument
+ // counts share the same formatting, including integral floating values.
+ expression(&format!(
+ "CASE WHEN cardinality({aggregate}) > 0 THEN
array_to_string(arrow_cast({aggregate}, 'List(Utf8)'), {separator}) ELSE
CAST(NULL AS STRING) END"
+ ))
+}
+
struct Rewriter<'a> {
state: &'a SessionState,
changed: bool,
@@ -257,7 +383,7 @@ impl VisitorMut for Rewriter<'_> {
||
self.state.window_functions().contains_key(&name)
||
self.state.higher_order_functions().contains_key(&name);
if is_aggregate(&name) && !registered {
- return lower_aggregate(call, &name).map(Some);
+ return lower_aggregate(call, &name,
self.state).map(Some);
}
}
}
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index d3dbeeea..d4316527 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -71,8 +71,9 @@ use datafusion::sql::sqlparser::ast::{
ColumnOption, CommentDef, CommentObject, CreateFunction,
CreateFunctionBody, CreateTable,
CreateTableOptions, CreateView, DataType as SqlDataType, Delete, Expr as
SqlExpr,
ExprWithAlias, FromTable, FunctionBehavior, FunctionReturnType, Ident,
Insert, Merge,
- ObjectName, ObjectType, RenameTableNameKind, Reset, ResetStatement, Set,
ShowCreateObject,
- SqlOption, Statement, TableFactor, TableObject, Truncate, Update, Use,
Value as SqlValue,
+ ObjectName, ObjectType, RenameTableNameKind, Reset, ResetStatement, Set,
SetExpr,
+ ShowCreateObject, SqlOption, Statement, TableFactor, TableObject,
Truncate, Update, Use,
+ Value as SqlValue,
};
use datafusion::sql::sqlparser::dialect::GenericDialect;
use datafusion::sql::sqlparser::keywords::Keyword;
@@ -522,9 +523,9 @@ impl SQLContext {
}
let rewritten;
- let persistent_definition = matches!(&statements[0],
Statement::CreateView(view) if !view.temporary &&
self.is_paimon_catalog_ref(&TableReference::from(view.name.to_string().as_str())))
+ let stored_definition = matches!(&statements[0],
Statement::CreateView(view) if view.temporary ||
self.is_paimon_catalog_ref(&TableReference::from(view.name.to_string().as_str())))
|| matches!(&statements[0], Statement::CreateFunction(_));
- let changed = !persistent_definition && {
+ let changed = !stored_definition && {
let binary_changed = crate::binary_cast::rewrite(&mut
statements[0])?;
let regex_changed = crate::regex_operators::rewrite(&mut
statements[0]);
let lateral_changed = crate::lateral_views::rewrite(&mut
statements[0])?;
@@ -668,6 +669,10 @@ impl SQLContext {
obj_type: ShowCreateObject::Table,
obj_name,
} => self.handle_show_create_table(sql, obj_name, options).await,
+ Statement::ShowCreate {
+ obj_type: ShowCreateObject::View,
+ obj_name,
+ } => self.handle_show_create_view(obj_name).await,
Statement::AlterTable(alter_table) => {
if alter_table.location.is_some()
&& alter_table.operations.iter().any(|operation| {
@@ -759,7 +764,30 @@ impl SQLContext {
if self.is_paimon_catalog_ref(&table_ref) {
self.handle_create_view(create_view, options).await
} else {
- self.ctx.sql_with_options(sql, options).await
+ // DataFusion stores the submitted SQL in its
ViewTable. Bind
+ // dependencies now so SHOW CREATE VIEW remains
portable after
+ // the session defaults change, even for a different
target schema.
+ let state = self.ctx.state();
+ let namespace = &state.config_options().catalog;
+ let query = crate::sql_function::bind_view_query(
+ &state,
+ &create_view.query.to_string(),
+ &namespace.default_catalog,
+ &namespace.default_schema,
+ )?;
+ let mut bound_view = create_view.clone();
+ bound_view.query = Parser::new(&GenericDialect {})
+ .try_with_sql(&query)
+ .and_then(|mut parser| parser.parse_query())
+ .map_err(|error| {
+ DataFusionError::Plan(format!("Invalid view
SQL: {error}"))
+ })?;
+ self.ctx
+ .sql_with_options(
+ &Statement::CreateView(bound_view).to_string(),
+ options,
+ )
+ .await
}
}
}
@@ -1510,6 +1538,115 @@ impl SQLContext {
)
}
+ async fn handle_show_create_view(&self, name: &ObjectName) ->
DFResult<DataFrame> {
+ if let Some((catalog, database, view, provider)) =
self.temp_table_for(name).await? {
+ return self.show_create_provider_view(catalog, database, view,
provider, true);
+ }
+ let table_ref =
+ object_name_to_table_reference(name.clone(),
self.ctx.enable_ident_normalization())?;
+ if !self.is_paimon_catalog_ref(&table_ref) {
+ let provider = self.ctx.table_provider(table_ref.clone()).await?;
+ let config = self.ctx.copied_config();
+ let config = &config.options().catalog;
+ let resolved = table_ref.resolve(&config.default_catalog,
&config.default_schema);
+ return self.show_create_provider_view(
+ resolved.catalog.to_string(),
+ resolved.schema.to_string(),
+ resolved.table.to_string(),
+ provider,
+ false,
+ );
+ }
+ let config = self.ctx.copied_config();
+ let defaults = &config.options().catalog;
+ let resolved = table_ref.resolve(&defaults.default_catalog,
&defaults.default_schema);
+ let catalog_name = resolved.catalog.to_string();
+ let catalog = self
+ .catalogs
+ .get(&catalog_name)
+ .ok_or_else(|| plan_datafusion_err!("Unknown catalog
'{catalog_name}'"))?;
+ let identifier = Identifier::new(resolved.schema.to_string(),
resolved.table.to_string());
+ // Read the stored definition directly: SHOW CREATE must not execute or
+ // plan the view's query, including when a dependency no longer exists.
+ let view = catalog
+ .get_view(&identifier)
+ .await
+ .map_err(to_datafusion_error)?;
+ let columns = view
+ .schema()
+ .fields()
+ .iter()
+ .map(|field| field.name().to_string())
+ .collect::<Vec<_>>();
+ let definition = view_definition(
+ &catalog_name,
+ identifier.database(),
+ identifier.object(),
+ &columns,
+ &typed_view_query(&view)?,
+ false,
+ );
+ self.show_create_result(
+ catalog_name,
+ identifier.database().into(),
+ identifier.object().into(),
+ Some(&definition),
+ false,
+ )
+ }
+
+ fn show_create_provider_view(
+ &self,
+ catalog: String,
+ database: String,
+ view: String,
+ provider: Arc<dyn TableProvider>,
+ temporary: bool,
+ ) -> DFResult<DataFrame> {
+ if provider.table_type() != datafusion::datasource::TableType::View {
+ return Err(plan_datafusion_err!(
+ "'{}.{}.{}' is not a view",
+ catalog,
+ database,
+ view
+ ));
+ }
+ let columns = provider
+ .schema()
+ .fields()
+ .iter()
+ .map(|field| field.name().clone())
+ .collect::<Vec<_>>();
+ let definition = provider
+ .get_table_definition()
+ .map(|stored| -> DFResult<String> {
+ // DataFusion stores CREATE VIEW, whereas Paimon temporary
views
+ // store only their query. Neither the provider nor a bare
table
+ // scan reliably records the namespace used at creation.
+ let (statements, _) = parse_sql_statements(stored)?;
+ let (query, query_sql) = match statements.as_slice() {
+ [Statement::CreateView(create)] => {
+ (create.query.as_ref(), create.query.to_string())
+ }
+ [Statement::Query(query)] => (query.as_ref(),
stored.to_string()),
+ _ => {
+ return Err(plan_datafusion_err!(
+ "Stored view definition must contain one query or
CREATE VIEW statement"
+ ));
+ }
+ };
+ crate::sql_function::validate_bound_view_query(
+ query,
+ self.ctx.enable_ident_normalization(),
+ )?;
+ Ok(view_definition(
+ &catalog, &database, &view, &columns, &query_sql,
temporary,
+ ))
+ })
+ .transpose()?;
+ self.show_create_result(catalog, database, view,
definition.as_deref(), true)
+ }
+
/// The temporary table or view `name` resolves to in queries.
pub(crate) async fn temp_table_for(
&self,
@@ -2261,6 +2398,12 @@ impl SQLContext {
self.ctx.enable_ident_normalization(),
)?;
let state = self.ctx.state();
+ let query_sql = crate::sql_function::bind_view_query(
+ &state,
+ &query_sql,
+ &state.config_options().catalog.default_catalog,
+ &state.config_options().catalog.default_schema,
+ )?;
let (df, reads_metadata) =
crate::partition_functions::track_metadata_reads(async {
let expanded_query = crate::sql_function::expand_sql(
&state,
@@ -2807,6 +2950,101 @@ impl SQLContext {
}
}
+fn typed_view_query(view: &paimon::catalog::View) -> DFResult<String> {
+ let fields = view.schema().fields();
+ if fields.is_empty() {
+ return Ok(view.query_for("datafusion").to_string());
+ }
+ let quote = |name: &str| Ident::with_quote('"', name).to_string();
+ let source = quote("view_source");
+ let columns = fields
+ .iter()
+ .map(|field| quote(field.name()))
+ .collect::<Vec<_>>();
+ let projections = fields
+ .iter()
+ .zip(&columns)
+ .map(|(field, column)| {
+ let arrow_type =
paimon::arrow::paimon_type_to_arrow(field.data_type())
+ .map_err(to_datafusion_error)?;
+ let arrow_type = arrow_type.to_string().replace('\'', "''");
+ Ok(format!(
+ "arrow_cast({source}.{column}, '{arrow_type}') AS {column}"
+ ))
+ })
+ .collect::<DFResult<Vec<_>>>()?;
+ // Match the casts applied by the catalog's enforce_view_schema without
+ // resolving or planning the stored query. The derived-table column list
+ // binds by position even when the query's original names are different.
+ let render = |query: &str| {
+ format!(
+ "SELECT {} FROM (\n{query}\n) AS {source} ({})",
+ projections.join(", "),
+ columns.join(", ")
+ )
+ };
+ let query = match parse_sql_statements(view.query_for("datafusion")) {
+ Ok((mut statements, _))
+ if statements.len() == 1 && matches!(statements[0],
Statement::Query(_)) =>
+ {
+ let Statement::Query(query) = statements.remove(0) else {
+ unreachable!()
+ };
+ let normalized = query.to_string();
+ // Exporting an already exported definition must be idempotent.
+ // Match the complete current wrapper, rather than stripping casts:
+ // earlier casts with a different declared type remain meaningful.
+ if let SetExpr::Select(select) = query.body.as_ref() {
+ if let [from] = select.from.as_slice() {
+ if let TableFactor::Derived { subquery, .. } =
&from.relation {
+ if let Ok((expected, _)) =
+
parse_sql_statements(&render(&subquery.to_string()))
+ {
+ if expected.len() == 1 && expected[0].to_string()
== normalized {
+ return Ok(normalized);
+ }
+ }
+ }
+ }
+ }
+ normalized
+ }
+ _ => view
+ .query_for("datafusion")
+ .trim()
+ .trim_end_matches(';')
+ .trim_end()
+ .to_string(),
+ };
+ Ok(render(&query))
+}
+
+fn view_definition(
+ catalog: &str,
+ database: &str,
+ view: &str,
+ columns: &[String],
+ query: &str,
+ temporary: bool,
+) -> String {
+ let quote = |name: &str| Ident::with_quote('"', name).to_string();
+ let name = [catalog, database, view].map(quote).join(".");
+ let columns = if columns.is_empty() {
+ String::new()
+ } else {
+ format!(
+ " ({})",
+ columns
+ .iter()
+ .map(|name| quote(name))
+ .collect::<Vec<_>>()
+ .join(", ")
+ )
+ };
+ let modifier = if temporary { "TEMPORARY " } else { "" };
+ format!("CREATE {modifier}VIEW {name}{columns} AS {query}")
+}
+
/// DDL from the engine provider of an external table.
async fn engine_table_definition(
catalog_provider: Arc<dyn datafusion::catalog::CatalogProvider>,
@@ -5103,6 +5341,366 @@ mod tests {
);
}
+ async fn shown_view_definition(ctx: &SQLContext, name: &str) -> String {
+ let batches = ctx
+ .sql(&format!("SHOW CREATE VIEW {name}"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), 1);
+ assert_eq!(
+ batches[0]
+ .schema()
+ .fields()
+ .iter()
+ .map(|field| field.name().as_str())
+ .collect::<Vec<_>>(),
+ vec!["table_catalog", "table_schema", "table_name", "definition"]
+ );
+ batches[0]
+ .column(3)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap()
+ .value(0)
+ .to_string()
+ }
+
+ #[tokio::test]
+ async fn
show_create_view_round_trips_column_names_and_quoted_identifiers() {
+ let catalog = Arc::new(MockCatalog::new());
+ let ctx = make_sql_context(catalog).await;
+ let name = "paimon.default.\"view.dot\"\"name\"";
+ ctx.sql(&format!(
+ "CREATE VIEW {name} (\"answer value\") AS SELECT 7 AS original"
+ ))
+ .await
+ .unwrap();
+ let definition = shown_view_definition(&ctx, name).await;
+ assert!(
+ definition.starts_with(
+ "CREATE VIEW \"paimon\".\"default\".\"view.dot\"\"name\"
(\"answer value\") AS "
+ ),
+ "{definition}"
+ );
+ assert!(
+ definition.contains("arrow_cast(\"view_source\".\"answer value\",
'Int64')"),
+ "{definition}"
+ );
+ assert!(definition.contains("SELECT 7 AS original"), "{definition}");
+ ctx.sql(&format!("DROP VIEW {name}")).await.unwrap();
+ ctx.sql(&definition).await.unwrap();
+ let batches = ctx
+ .sql(&format!("SELECT \"answer value\" FROM {name}"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(batches[0].column(0),
0).unwrap(),
+ datafusion::common::ScalarValue::Int64(Some(7))
+ );
+ }
+
+ #[tokio::test]
+ async fn
show_create_view_normalizes_unquoted_names_and_preserves_quoted_case() {
+ let catalog = Arc::new(MockCatalog::new());
+ let ctx = make_sql_context(catalog).await;
+ ctx.sql("CREATE VIEW v AS SELECT 1 AS id").await.unwrap();
+ for name in ["V", "DEFAULT.V", "PAIMON.DEFAULT.V"] {
+ let definition = shown_view_definition(&ctx, name).await;
+ assert!(
+ definition.starts_with("CREATE VIEW
\"paimon\".\"default\".\"v\" (\"id\") AS "),
+ "{definition}"
+ );
+ assert!(definition.contains("SELECT 1 AS id"), "{definition}");
+ }
+ ctx.sql("CREATE VIEW \"V\" AS SELECT 2 AS id")
+ .await
+ .unwrap();
+ let quoted = shown_view_definition(&ctx, "paimon.default.\"V\"").await;
+ assert!(
+ quoted.starts_with("CREATE VIEW \"paimon\".\"default\".\"V\"
(\"id\") AS "),
+ "{quoted}"
+ );
+ assert!(quoted.contains("SELECT 2 AS id"), "{quoted}");
+ let unquoted = shown_view_definition(&ctx, "V").await;
+ assert!(
+ unquoted.starts_with("CREATE VIEW \"paimon\".\"default\".\"v\"
(\"id\") AS "),
+ "{unquoted}"
+ );
+ assert!(unquoted.contains("SELECT 1 AS id"), "{unquoted}");
+ }
+
+ #[tokio::test]
+ async fn
show_create_view_round_trip_preserves_authoritative_declared_type() {
+ let catalog = Arc::new(MockCatalog::new());
+ let fields = serde_json::from_value(serde_json::json!([
+ {"id":0,"name":"answer","type":"INT"}
+ ]))
+ .unwrap();
+ catalog.add_view(paimon::catalog::View::new(
+ Identifier::new("default", "typed_view"),
+ paimon::catalog::ViewSchema::new(
+ fields,
+ "SELECT CAST(42 AS BIGINT) AS original; -- stored query
comment".into(),
+ HashMap::new(),
+ None,
+ HashMap::new(),
+ ),
+ ));
+ let ctx = make_sql_context(catalog).await;
+ let before = ctx.sql("SELECT answer FROM typed_view").await.unwrap();
+ let before_type = before.schema().field(0).data_type().clone();
+ assert_eq!(before_type, ArrowDataType::Int32);
+ let mut definition = shown_view_definition(&ctx, "typed_view").await;
+ let canonical =
parse_sql_statements(&definition).unwrap().0[0].to_string();
+ for cycle in 0..4 {
+ ctx.sql("DROP VIEW typed_view").await.unwrap();
+ ctx.sql(&definition).await.unwrap();
+ let recreated = ctx.sql("SELECT answer FROM
typed_view").await.unwrap();
+ assert_eq!(recreated.schema().field(0).data_type(), &before_type);
+ let batches = recreated.collect().await.unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(batches[0].column(0),
0).unwrap(),
+ datafusion::common::ScalarValue::Int32(Some(42))
+ );
+ definition = shown_view_definition(&ctx, "typed_view").await;
+ assert_eq!(
+ parse_sql_statements(&definition).unwrap().0[0].to_string(),
+ canonical,
+ "cycle {cycle}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn
show_create_view_preserves_earlier_casts_with_different_metadata_types() {
+ let catalog = Arc::new(MockCatalog::new());
+ let fields = serde_json::from_value(serde_json::json!([
+ {"id":0,"name":"answer","type":"BIGINT"}
+ ]))
+ .unwrap();
+ catalog.add_view(paimon::catalog::View::new(
+ Identifier::new("default", "narrowed_view"),
+ paimon::catalog::ViewSchema::new(fields,
+ "SELECT arrow_cast(\"view_source\".\"answer\", 'Int32') AS
\"answer\" FROM (SELECT 2147483648 AS answer) AS \"view_source\"
(\"answer\")".into(),
+ HashMap::new(), None, HashMap::new()),
+ ));
+ let ctx = make_sql_context(catalog).await;
+ let definition = shown_view_definition(&ctx, "narrowed_view").await;
+ assert!(definition.contains("'Int32'"), "{definition}");
+ assert!(definition.contains("'Int64'"), "{definition}");
+ ctx.sql("DROP VIEW narrowed_view").await.unwrap();
+ ctx.sql(&definition).await.unwrap();
+ let recreated = ctx.sql("SELECT answer FROM narrowed_view").await;
+ let error = match recreated {
+ Ok(frame) => frame.collect().await.unwrap_err(),
+ Err(error) => error,
+ };
+ assert!(error.to_string().contains("2147483648"), "{error}");
+ }
+
+ #[tokio::test]
+ async fn
show_create_temporary_view_round_trip_preserves_creation_namespace() {
+ let catalog = Arc::new(MockCatalog::new());
+ let ctx = make_sql_context(catalog).await;
+ ctx.sql("CREATE TEMPORARY TABLE paimon.a.source AS SELECT 1 AS id")
+ .await
+ .unwrap();
+ ctx.sql("CREATE TEMPORARY TABLE paimon.b.source AS SELECT 2 AS id")
+ .await
+ .unwrap();
+ ctx.sql("USE paimon.a").await.unwrap();
+ ctx.sql("CREATE TEMPORARY VIEW paimon.a.bound_view AS SELECT id FROM
source")
+ .await
+ .unwrap();
+ ctx.sql("USE paimon.b").await.unwrap();
+ let original = ctx
+ .sql("SELECT id FROM paimon.a.bound_view")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(original[0].column(0),
0).unwrap(),
+ datafusion::common::ScalarValue::Int64(Some(1))
+ );
+ let definition = shown_view_definition(&ctx,
"paimon.a.bound_view").await;
+ ctx.sql("DROP TEMPORARY VIEW paimon.a.bound_view")
+ .await
+ .unwrap();
+ ctx.sql(&definition).await.unwrap();
+ let recreated = ctx
+ .sql("SELECT id FROM paimon.a.bound_view")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(recreated[0].column(0),
0).unwrap(),
+ datafusion::common::ScalarValue::Int64(Some(1))
+ );
+ }
+
+ #[tokio::test]
+ async fn
temporary_view_ddl_preserves_cte_shadowing_and_catalog_function_namespace() {
+ let catalog = Arc::new(MockCatalog::new());
+ add_unary_sql_function_in_database(&catalog, "a", "adjust", "x + 10",
true);
+ add_unary_sql_function_in_database(&catalog, "b", "adjust", "x + 100",
true);
+ let ctx = make_sql_context(catalog).await;
+ ctx.sql("CREATE TEMPORARY TABLE paimon.a.source AS SELECT 1 AS id")
+ .await
+ .unwrap();
+ ctx.sql("CREATE TEMPORARY TABLE paimon.b.source AS SELECT 2 AS id")
+ .await
+ .unwrap();
+ ctx.sql("USE paimon.a").await.unwrap();
+ ctx.sql("CREATE TEMPORARY VIEW paimon.a.bound_cte AS WITH source AS
(SELECT adjust(id) AS id FROM source) SELECT id FROM source").await.unwrap();
+ ctx.sql("USE paimon.b").await.unwrap();
+ let definition = shown_view_definition(&ctx,
"paimon.a.bound_cte").await;
+ assert!(
+ definition.contains("\"paimon\".\"a\".\"source\""),
+ "{definition}"
+ );
+ assert!(
+ definition.contains("\"paimon\".\"a\".\"adjust\""),
+ "{definition}"
+ );
+ assert!(
+ definition.ends_with("SELECT id FROM source"),
+ "{definition}"
+ );
+ ctx.sql("DROP TEMPORARY VIEW paimon.a.bound_cte")
+ .await
+ .unwrap();
+ ctx.sql(&definition).await.unwrap();
+ let batches = ctx
+ .sql("SELECT id FROM paimon.a.bound_cte")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(batches[0].column(0),
0).unwrap(),
+ datafusion::common::ScalarValue::Int64(Some(11))
+ );
+ }
+
+ #[tokio::test]
+ async fn show_create_view_prefers_dialect_without_planning_dependencies() {
+ let catalog = Arc::new(MockCatalog::new());
+ let fields = serde_json::from_value(serde_json::json!([
+ {"id":0,"name":"answer","type":"BIGINT"}
+ ]))
+ .unwrap();
+ catalog.add_view(paimon::catalog::View::new(
+ Identifier::new("default", "stale_view"),
+ paimon::catalog::ViewSchema::new(
+ fields,
+ "SELECT 0".into(),
+ HashMap::from([(
+ "datafusion".into(),
+ "SELECT answer FROM missing_dependency".into(),
+ )]),
+ None,
+ HashMap::new(),
+ ),
+ ));
+ let ctx = make_sql_context(catalog).await;
+ for name in [
+ "stale_view",
+ "default.stale_view",
+ "paimon.default.stale_view",
+ ] {
+ let definition = shown_view_definition(&ctx, name).await;
+ assert!(
+ definition.starts_with(
+ "CREATE VIEW \"paimon\".\"default\".\"stale_view\"
(\"answer\") AS "
+ ),
+ "{definition}"
+ );
+ assert!(
+ definition.contains("SELECT answer FROM missing_dependency"),
+ "{definition}"
+ );
+ }
+ let error = ctx
+ .sql("SHOW CREATE VIEW missing_view")
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("missing_view"), "{error}");
+ }
+
+ #[tokio::test]
+ async fn
show_create_view_uses_temporary_shadow_before_persistent_definition() {
+ let catalog = Arc::new(MockCatalog::new());
+ let ctx = make_sql_context(catalog).await;
+ ctx.sql("CREATE VIEW v AS SELECT 1 AS id").await.unwrap();
+ ctx.sql("CREATE TEMPORARY VIEW v AS SELECT 2 AS id")
+ .await
+ .unwrap();
+ assert_eq!(
+ shown_view_definition(&ctx, "v").await,
+ "CREATE TEMPORARY VIEW \"paimon\".\"default\".\"v\" (\"id\") AS
SELECT 2 AS id"
+ );
+ ctx.sql("DROP TEMPORARY VIEW v").await.unwrap();
+ let definition = shown_view_definition(&ctx, "v").await;
+ assert!(
+ definition.starts_with("CREATE VIEW \"paimon\".\"default\".\"v\"
(\"id\") AS "),
+ "{definition}"
+ );
+ assert!(definition.contains("SELECT 1 AS id"), "{definition}");
+ }
+
+ #[tokio::test]
+ async fn views_preserve_and_execute_group_concat_sql() {
+ let catalog = Arc::new(MockCatalog::new());
+ let ctx = make_sql_context(Arc::clone(&catalog)).await;
+ let query = "SELECT group_concat(v ORDER BY v SEPARATOR '|') AS joined
FROM (VALUES ('b'),('a')) t(v)";
+ for (modifier, name) in [
+ ("", "persistent_compat"),
+ ("TEMPORARY ", "temporary_compat"),
+ ] {
+ ctx.sql(&format!("CREATE {modifier}VIEW {name} AS {query}"))
+ .await
+ .unwrap();
+ let definition = shown_view_definition(&ctx, name).await;
+ assert!(
+ definition.contains("GROUP_CONCAT") ||
definition.contains("group_concat"),
+ "{definition}"
+ );
+ assert!(definition.contains("SEPARATOR '|'"), "{definition}");
+ assert!(!definition.contains("__paimon"), "{definition}");
+ let batches = ctx
+ .sql(&format!("SELECT joined FROM {name}"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+
datafusion::common::ScalarValue::try_from_array(batches[0].column(0), 0)
+ .unwrap()
+ .to_string(),
+ "a|b"
+ );
+ }
+ let view = catalog
+ .get_view(&Identifier::new("default", "persistent_compat"))
+ .await
+ .unwrap();
+ assert!(view.query_for("datafusion").contains("SEPARATOR '|'"));
+ }
+
#[tokio::test]
async fn persistent_rest_catalog_view_can_be_created_and_read() {
let catalog = Arc::new(MockCatalog::new());
@@ -6488,6 +7086,63 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn rest_catalog_view_cycles_are_not_hidden_by_recursive_cte_names() {
+ for query in [
+ "WITH RECURSIVE recursive_view AS (SELECT answer FROM
recursive_view) SELECT answer FROM recursive_view",
+ "WITH RECURSIVE a AS (SELECT answer FROM recursive_view),
recursive_view AS (SELECT 99 AS answer) SELECT answer FROM a",
+ "WITH RECURSIVE recursive_view AS (SELECT answer FROM
recursive_view UNION ALL SELECT answer + 1 FROM recursive_view WHERE answer <
3) SELECT answer FROM recursive_view",
+ "WITH RECURSIVE r AS (WITH unused AS (SELECT answer FROM
recursive_view) SELECT CAST(1 AS BIGINT) AS answer UNION ALL SELECT answer + 1
FROM r WHERE answer < 3) SELECT answer FROM r",
+ ] {
+ let catalog = Arc::new(MockCatalog::new());
+ add_bigint_view(&catalog, "default", "recursive_view", query);
+ let ctx = make_sql_context(catalog).await;
+ let error = tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ ctx.sql("SELECT * FROM recursive_view"),
+ )
+ .await
+ .expect("recursive view planning should terminate")
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("recursive REST catalog view"), "{query}:
{error}");
+ }
+ }
+
+ #[tokio::test]
+ async fn rest_catalog_view_allows_recursive_cte_work_table() {
+ let catalog = Arc::new(MockCatalog::new());
+ add_bigint_view(
+ &catalog,
+ "default",
+ "recursive_view",
+ "WITH RECURSIVE recursive_view AS (SELECT CAST(1 AS BIGINT) AS
answer \
+ UNION ALL SELECT answer + 1 FROM recursive_view WHERE answer < 3)
\
+ SELECT answer FROM recursive_view",
+ );
+ let ctx = make_sql_context(catalog).await;
+ let batches = ctx
+ .sql("SELECT answer FROM recursive_view ORDER BY answer")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ let values = batches
+ .iter()
+ .flat_map(|batch| {
+ batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<Int64Array>()
+ .unwrap()
+ .values()
+ .to_vec()
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(values, vec![1, 2, 3]);
+ }
+
#[tokio::test]
async fn rest_catalog_view_allows_cte_with_same_name() {
let catalog = Arc::new(MockCatalog::new());
diff --git a/crates/integrations/datafusion/src/sql_function.rs
b/crates/integrations/datafusion/src/sql_function.rs
index ebd7ab48..3faed363 100644
--- a/crates/integrations/datafusion/src/sql_function.rs
+++ b/crates/integrations/datafusion/src/sql_function.rs
@@ -24,7 +24,8 @@ use datafusion::execution::SessionState;
use datafusion::sql::planner::IdentNormalizer;
use datafusion::sql::sqlparser::ast::{
visit_expressions, visit_expressions_mut, Expr as SqlExpr, FunctionArg,
FunctionArgExpr,
- FunctionArguments, Ident, ObjectName, Statement,
+ FunctionArguments, Ident, ObjectName, Query, SetExpr, SetOperator,
Statement, TableFactor,
+ VisitMut, Visitor, VisitorMut,
};
use paimon::catalog::{Catalog, Function, Identifier};
@@ -33,6 +34,367 @@ const MAX_FUNCTION_REFERENCES: usize = 1024;
const MAX_EXPANDED_CALLS: usize = 1024;
type FunctionReference = (String, Identifier);
+/// Bind persistent catalog dependencies in a view's stored SQL to
+/// the namespace used to create its logical plan. Keep CTEs, table functions,
+/// and native function calls in their original scopes.
+pub(crate) fn bind_view_query(
+ state: &SessionState,
+ sql: &str,
+ current_catalog: &str,
+ current_database: &str,
+) -> DFResult<String> {
+ let regex_sql = crate::regex_operators::parseable_sql(sql)?;
+ let parseable = crate::lateral_views::parseable_sql(regex_sql.as_ref())?;
+ let mut statements = crate::vector_type::parse_sql(parseable.as_ref())
+ .map_err(|error| DataFusionError::Plan(format!("Invalid view SQL:
{error}")))?;
+ if statements.len() != 1 || !matches!(statements.first(),
Some(Statement::Query(_))) {
+ return Err(DataFusionError::Plan(
+ "View SQL must contain one query".into(),
+ ));
+ }
+ let mut physical_tables = HashSet::new();
+ if let Statement::Query(query) = &statements[0] {
+ visit_view_table_dependencies(
+ query,
+ state.config_options().sql_parser.enable_ident_normalization,
+ &mut |name| {
+ physical_tables.insert(name as *const ObjectName as usize);
+ Ok(())
+ },
+ )?;
+ }
+ struct Binder<'a> {
+ state: &'a SessionState,
+ catalog: &'a str,
+ database: &'a str,
+ physical_tables: HashSet<usize>,
+ table_functions: HashSet<usize>,
+ }
+ impl VisitorMut for Binder<'_> {
+ type Break = ();
+
+ fn pre_visit_table_factor(&mut self, factor: &mut TableFactor) ->
ControlFlow<Self::Break> {
+ if let TableFactor::TableFunction {
+ expr: SqlExpr::Function(call),
+ ..
+ } = factor
+ {
+ self.table_functions.insert(call as *const _ as usize);
+ return ControlFlow::Continue(());
+ }
+ let TableFactor::Table {
+ name, args: None, ..
+ } = factor
+ else {
+ return ControlFlow::Continue(());
+ };
+ let normalize = self
+ .state
+ .config_options()
+ .sql_parser
+ .enable_ident_normalization;
+ if !self
+ .physical_tables
+ .contains(&(name as *const ObjectName as usize))
+ {
+ return ControlFlow::Continue(());
+ }
+ let parts = name
+ .0
+ .iter()
+ .map(|part| {
+ part.as_ident()
+ .cloned()
+ .map(|identifier|
IdentNormalizer::new(normalize).normalize(identifier))
+ })
+ .collect::<Option<Vec<_>>>();
+ if let Some(parts) = parts {
+ let names = match parts.as_slice() {
+ [table] => vec![self.catalog, self.database,
table.as_str()],
+ [database, table] => vec![self.catalog, database.as_str(),
table.as_str()],
+ _ => return ControlFlow::Continue(()),
+ };
+ *name = quoted_name(&names);
+ }
+ ControlFlow::Continue(())
+ }
+
+ fn post_visit_expr(&mut self, expr: &mut SqlExpr) ->
ControlFlow<Self::Break> {
+ if let SqlExpr::Function(function) = expr {
+ if self
+ .table_functions
+ .remove(&(function as *const _ as usize))
+ {
+ return ControlFlow::Continue(());
+ }
+ if let Some((catalog, identifier)) =
+ function_reference(function, self.catalog, self.database,
self.state)
+ {
+ function.name =
+ quoted_name(&[&catalog, identifier.database(),
identifier.object()]);
+ }
+ }
+ ControlFlow::Continue(())
+ }
+ }
+ let mut binder = Binder {
+ state,
+ catalog: current_catalog,
+ database: current_database,
+ physical_tables,
+ table_functions: HashSet::new(),
+ };
+ let _: ControlFlow<()> = statements[0].visit(&mut binder);
+ Ok(statements.remove(0).to_string())
+}
+
+fn quoted_name(parts: &[&str]) -> ObjectName {
+ ObjectName::from(
+ parts
+ .iter()
+ .map(|part| Ident::with_quote('"', *part))
+ .collect::<Vec<_>>(),
+ )
+}
+
+/// A native provider's stored SQL may lack its creation namespace, even though
+/// its logical plan still holds the original table providers. Only export SQL
+/// whose physical table references are independent of the session defaults.
+pub(crate) fn validate_bound_view_query(query: &Query, normalize: bool) ->
DFResult<()> {
+ visit_view_table_dependencies(query, normalize, &mut |name| {
+ if name.0.len() < 3 {
+ return Err(DataFusionError::Plan(format!(
+ "Cannot export view with unqualified dependency '{name}': its
creation \
+ namespace is unavailable; use fully qualified
catalog.schema.table \
+ names in the view definition"
+ )));
+ }
+ Ok(())
+ })
+}
+
+/// Visit physical table names using DataFusion's sequential CTE visibility and
+/// recursive UNION branch scopes, including metadata prefetches from ignored
+/// query clauses. Binding, export validation, and catalog
+/// dependency discovery must agree on which references are physical tables.
+pub(crate) fn visit_view_table_dependencies(
+ query: &Query,
+ normalize: bool,
+ visit_relation: &mut dyn FnMut(&ObjectName) -> DFResult<()>,
+) -> DFResult<()> {
+ struct DependencyVisitor<'a> {
+ visible_ctes: &'a HashSet<String>,
+ visit_relation: &'a mut dyn FnMut(&ObjectName) -> DFResult<()>,
+ processed_cte_queries: HashSet<usize>,
+ normalize: bool,
+ skip_root_query: bool,
+ nested_queries: usize,
+ }
+ impl Visitor for DependencyVisitor<'_> {
+ type Break = DataFusionError;
+
+ fn pre_visit_query(&mut self, query: &Query) ->
ControlFlow<Self::Break> {
+ if self.skip_root_query {
+ self.skip_root_query = false;
+ return ControlFlow::Continue(());
+ }
+ if self.nested_queries == 0
+ && !self
+ .processed_cte_queries
+ .contains(&(query as *const Query as usize))
+ {
+ if let Err(error) = visit_query(
+ query,
+ self.visible_ctes,
+ self.normalize,
+ self.visit_relation,
+ ) {
+ return ControlFlow::Break(error);
+ }
+ }
+ self.nested_queries += 1;
+ ControlFlow::Continue(())
+ }
+
+ fn post_visit_query(&mut self, _query: &Query) ->
ControlFlow<Self::Break> {
+ self.nested_queries = self.nested_queries.saturating_sub(1);
+ ControlFlow::Continue(())
+ }
+
+ fn pre_visit_table_factor(&mut self, factor: &TableFactor) ->
ControlFlow<Self::Break> {
+ // Nested queries have already been checked in their own CTE scope.
+ if self.nested_queries != 0 {
+ return ControlFlow::Continue(());
+ }
+ if let TableFactor::Table {
+ name, args: None, ..
+ } = factor
+ {
+ let is_cte = match name.0.as_slice() {
+ [part] => part.as_ident().is_some_and(|identifier| {
+ self.visible_ctes.contains(
+
&IdentNormalizer::new(self.normalize).normalize(identifier.clone()),
+ )
+ }),
+ _ => false,
+ };
+ if !is_cte {
+ if let Err(error) = (self.visit_relation)(name) {
+ return ControlFlow::Break(error);
+ }
+ }
+ }
+ ControlFlow::Continue(())
+ }
+ }
+
+ fn visit_query(
+ query: &Query,
+ inherited_ctes: &HashSet<String>,
+ normalize: bool,
+ visit_relation: &mut dyn FnMut(&ObjectName) -> DFResult<()>,
+ ) -> DFResult<()> {
+ let mut visible_ctes = inherited_ctes.clone();
+ if let Some(with) = &query.with {
+ // DataFusion plans CTEs sequentially even with WITH RECURSIVE.
+ for cte in &with.cte_tables {
+ let name =
IdentNormalizer::new(normalize).normalize(cte.alias.name.clone());
+ if let (
+ true,
+ SetExpr::SetOperation {
+ op: SetOperator::Union,
+ left,
+ right,
+ ..
+ },
+ ) = (with.recursive, cte.query.body.as_ref())
+ {
+ // recursive_cte plans these operands directly. The static
+ // left operand cannot see the work table; only the right
can.
+ for (operand, recursive) in [(left, false), (right, true)]
{
+ let mut branch_ctes = visible_ctes.clone();
+ if recursive {
+ branch_ctes.insert(name.clone());
+ }
+ let mut visitor = DependencyVisitor {
+ visible_ctes: &branch_ctes,
+ visit_relation,
+ processed_cte_queries: HashSet::new(),
+ normalize,
+ skip_root_query: false,
+ nested_queries: 0,
+ };
+ if let ControlFlow::Break(error) =
+
datafusion::sql::sqlparser::ast::Visit::visit(operand, &mut visitor)
+ {
+ return Err(error);
+ }
+ }
+ } else {
+ visit_query(&cte.query, &visible_ctes, normalize,
visit_relation)?;
+ }
+ visible_ctes.insert(name);
+ }
+ }
+
+ // WITH definitions were processed in their own scopes above. Skip them
+ // during this visit, retaining original AST addresses for the binder's
+ // later mutable pass. The mutable pass only replaces names in place.
+ let mut visitor = DependencyVisitor {
+ visible_ctes: &visible_ctes,
+ visit_relation,
+ processed_cte_queries: query
+ .with
+ .iter()
+ .flat_map(|with| &with.cte_tables)
+ .map(|cte| cte.query.as_ref() as *const Query as usize)
+ .collect(),
+ normalize,
+ skip_root_query: true,
+ nested_queries: 0,
+ };
+ match datafusion::sql::sqlparser::ast::Visit::visit(query, &mut
visitor) {
+ ControlFlow::Break(error) => Err(error),
+ ControlFlow::Continue(()) => Ok(()),
+ }
+ }
+
+ // SQL planning also prefetches references from the complete AST, including
+ // WITH/ORDER/LIMIT fields that recursive_cte does not execute. Match that
+ // resolver's CTE visibility in a second pass without changing the actual
+ // anchor/recursive-branch classification above.
+ struct PrefetchVisitor<'a> {
+ visible_ctes: Vec<String>,
+ normalize: bool,
+ visit_relation: &'a mut dyn FnMut(&ObjectName) -> DFResult<()>,
+ }
+ impl Visitor for PrefetchVisitor<'_> {
+ type Break = DataFusionError;
+
+ fn pre_visit_query(&mut self, query: &Query) ->
ControlFlow<Self::Break> {
+ if let Some(with) = &query.with {
+ for cte in &with.cte_tables {
+ if !with.recursive {
+ datafusion::sql::sqlparser::ast::Visit::visit(cte,
self)?;
+ }
+ self.visible_ctes.push(
+
IdentNormalizer::new(self.normalize).normalize(cte.alias.name.clone()),
+ );
+ }
+ }
+ ControlFlow::Continue(())
+ }
+
+ fn post_visit_query(&mut self, query: &Query) ->
ControlFlow<Self::Break> {
+ if let Some(with) = &query.with {
+ self.visible_ctes
+ .truncate(self.visible_ctes.len() - with.cte_tables.len());
+ }
+ ControlFlow::Continue(())
+ }
+
+ fn pre_visit_table_factor(&mut self, factor: &TableFactor) ->
ControlFlow<Self::Break> {
+ if let TableFactor::Table {
+ name, args: None, ..
+ } = factor
+ {
+ let is_cte = match name.0.as_slice() {
+ [part] => part.as_ident().is_some_and(|identifier| {
+ self.visible_ctes.contains(
+
&IdentNormalizer::new(self.normalize).normalize(identifier.clone()),
+ )
+ }),
+ _ => false,
+ };
+ if !is_cte {
+ if let Err(error) = (self.visit_relation)(name) {
+ return ControlFlow::Break(error);
+ }
+ }
+ }
+ ControlFlow::Continue(())
+ }
+ }
+
+ let mut visited = HashSet::new();
+ let mut visit_once = |name: &ObjectName| {
+ if visited.insert(name as *const ObjectName as usize) {
+ visit_relation(name)?;
+ }
+ Ok(())
+ };
+ visit_query(query, &HashSet::new(), normalize, &mut visit_once)?;
+ let mut visitor = PrefetchVisitor {
+ visible_ctes: Vec::new(),
+ normalize,
+ visit_relation: &mut visit_once,
+ };
+ match datafusion::sql::sqlparser::ast::Visit::visit(query, &mut visitor) {
+ ControlFlow::Break(error) => Err(error),
+ ControlFlow::Continue(()) => Ok(()),
+ }
+}
+
pub(crate) async fn expand_sql(
state: &SessionState,
sql: &str,
@@ -557,7 +919,91 @@ fn bare_function_name(function:
&datafusion::sql::sqlparser::ast::Function) -> O
mod tests {
use std::collections::HashMap;
- use super::expand_sql;
+ use super::{bind_view_query, expand_sql};
+
+ #[test]
+ fn view_binding_preserves_sequential_and_recursive_cte_scopes() {
+ let state = datafusion::prelude::SessionContext::new().state();
+ let bound = bind_view_query(
+ &state,
+ "WITH t AS (SELECT id FROM t), u AS (SELECT id FROM t) SELECT id
FROM u",
+ "lake",
+ "db",
+ )
+ .unwrap();
+ assert_eq!(bound, "WITH t AS (SELECT id FROM \"lake\".\"db\".\"t\"), u
AS (SELECT id FROM t) SELECT id FROM u");
+ let recursive = "WITH RECURSIVE t AS (SELECT 1 AS id UNION ALL SELECT
id + 1 FROM t WHERE id < 2) SELECT id FROM t";
+ assert_eq!(
+ bind_view_query(&state, recursive, "lake", "db").unwrap(),
+ recursive
+ );
+ }
+
+ #[test]
+ fn view_binding_distinguishes_recursive_anchors_and_forward_references() {
+ let state = datafusion::prelude::SessionContext::new().state();
+ for (sql, expected) in [
+ (
+ "WITH RECURSIVE t AS (SELECT id FROM t) SELECT id FROM t",
+ "WITH RECURSIVE t AS (SELECT id FROM \"lake\".\"db\".\"t\")
SELECT id FROM t",
+ ),
+ (
+ "WITH RECURSIVE a AS (SELECT id FROM t), t AS (SELECT 1 AS id)
SELECT id FROM a",
+ "WITH RECURSIVE a AS (SELECT id FROM \"lake\".\"db\".\"t\"), t
AS (SELECT 1 AS id) SELECT id FROM a",
+ ),
+ (
+ "WITH RECURSIVE t AS (SELECT id FROM t UNION ALL SELECT id + 1
FROM t WHERE id < 3) SELECT id FROM t",
+ "WITH RECURSIVE t AS (SELECT id FROM \"lake\".\"db\".\"t\"
UNION ALL SELECT id + 1 FROM t WHERE id < 3) SELECT id FROM t",
+ ),
+ (
+ "WITH RECURSIVE t AS (WITH unused AS (SELECT id FROM source)
SELECT 1 AS id UNION ALL SELECT id + 1 FROM t WHERE id < 3) SELECT id FROM t",
+ "WITH RECURSIVE t AS (WITH unused AS (SELECT id FROM
\"lake\".\"db\".\"source\") SELECT 1 AS id UNION ALL SELECT id + 1 FROM t WHERE
id < 3) SELECT id FROM t",
+ ),
+ ] {
+ assert_eq!(bind_view_query(&state, sql, "lake", "db").unwrap(),
expected);
+ }
+ }
+
+ #[test]
+ fn
view_binding_keeps_table_functions_and_qualifies_catalog_scalar_functions() {
+ let state = datafusion::prelude::SessionContext::new().state();
+ assert_eq!(
+ bind_view_query(
+ &state,
+ "SELECT upper(v), custom_fn(v) FROM other.source",
+ "lake",
+ "db"
+ )
+ .unwrap(),
+ "SELECT upper(v), \"lake\".\"db\".\"custom_fn\"(v) FROM
\"lake\".\"other\".\"source\""
+ );
+ for sql in [
+ "SELECT * FROM generate_series(1, 2)",
+ "SELECT * FROM TABLE(generate_series(1, 2))",
+ ] {
+ assert_eq!(bind_view_query(&state, sql, "lake", "db").unwrap(),
sql);
+ }
+ }
+
+ #[test]
+ fn view_binding_uses_session_identifier_normalization() {
+ let mut state = datafusion::prelude::SessionContext::new().state();
+ state
+ .config_mut()
+ .options_mut()
+ .sql_parser
+ .enable_ident_normalization = false;
+ assert_eq!(
+ bind_view_query(
+ &state,
+ "WITH \"Source\" AS (SELECT id FROM \"Source\") SELECT id FROM
Source",
+ "lake",
+ "db"
+ )
+ .unwrap(),
+ "WITH \"Source\" AS (SELECT id FROM \"lake\".\"db\".\"Source\")
SELECT id FROM Source"
+ );
+ }
#[test]
fn vector_cast_preserves_function_dependency_detection() {
diff --git a/crates/integrations/datafusion/tests/sql_compatibility.rs
b/crates/integrations/datafusion/tests/sql_compatibility.rs
new file mode 100644
index 00000000..5e23948f
--- /dev/null
+++ b/crates/integrations/datafusion/tests/sql_compatibility.rs
@@ -0,0 +1,458 @@
+// 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.
+
+mod common;
+
+use std::sync::Arc;
+
+use datafusion::arrow::array::{Int32Array, RecordBatch};
+use datafusion::arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::ScalarValue;
+use paimon_datafusion::SQLContext;
+
+async fn rows(ctx: &SQLContext, sql: &str) -> Vec<Vec<String>> {
+ ctx.sql(sql)
+ .await
+ .unwrap_or_else(|error| panic!("{sql}: {error}"))
+ .collect()
+ .await
+ .unwrap()
+ .iter()
+ .flat_map(|batch| {
+ (0..batch.num_rows()).map(|row| {
+ batch
+ .columns()
+ .iter()
+ .map(|column| {
+ ScalarValue::try_from_array(column, row)
+ .unwrap()
+ .to_string()
+ })
+ .collect()
+ })
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn group_concat_preserves_distinct_order_separator_and_nulls() {
+ let ctx = SQLContext::new();
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(DISTINCT v ORDER BY v DESC SEPARATOR
'|') AS joined FROM (VALUES ('b'),('a'),('b'),(NULL),('')) t(v)").await,
+ vec![vec!["b|a|"]]
+ );
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(v ORDER BY k SEPARATOR '') AS joined
FROM (VALUES ('a',2),('b',1),(NULL,3)) t(v,k)").await,
+ vec![vec!["ba"]]
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT group_concat(v ORDER BY v) FROM (VALUES (2),(1),(NULL))
t(v)"
+ )
+ .await,
+ vec![vec!["1,2"]]
+ );
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(v SEPARATOR '|') IS NULL FROM (VALUES
(CAST(NULL AS STRING))) t(v)").await,
+ vec![vec!["true"]]
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT group_concat(v SEPARATOR '|') IS NULL FROM (VALUES ('x'))
t(v) WHERE false"
+ )
+ .await,
+ vec![vec!["true"]]
+ );
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(DISTINCT v ORDER BY v SEPARATOR '|')
FROM (VALUES (10),(2),(10),(NULL)) t(v)").await,
+ vec![vec!["2|10"]]
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT group_concat(v SEPARATOR '|') = '' FROM (VALUES
(''),(NULL)) t(v)"
+ )
+ .await,
+ vec![vec!["true"]]
+ );
+}
+
+#[tokio::test]
+async fn group_concat_concatenates_row_arguments_and_preserves_filter() {
+ let ctx = SQLContext::new();
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(a,b ORDER BY k SEPARATOR ';') FILTER
(WHERE k < 4) AS joined FROM (VALUES
('a',1,2),('b',2,1),(NULL,3,3),('c',NULL,0),('d',4,4)) t(a,b,k)").await,
+ vec![vec!["b2;a1"]]
+ );
+ common::assert_sql_error(&ctx, "SELECT group_concat('x' SEPARATOR NULL)",
"SEPARATOR").await;
+ common::assert_sql_error(
+ &ctx,
+ "SELECT group_concat(DISTINCT a,b SEPARATOR '|') FROM (VALUES
('a','bc'),('ab','c')) t(a,b)",
+ "DISTINCT supports one expression",
+ ).await;
+}
+
+#[tokio::test]
+async fn show_create_temporary_view_returns_recreatable_definition() {
+ let (_tmp, ctx) = common::setup_sql_context().await;
+ ctx.sql("CREATE TEMPORARY VIEW paimon.test_db.\"view.dot\" AS SELECT 7 AS
\"answer value\"")
+ .await
+ .unwrap();
+ let shown = rows(&ctx, "SHOW CREATE VIEW
paimon.test_db.\"view.dot\"").await;
+ assert_eq!(shown.len(), 1);
+ assert_eq!(&shown[0][..3], &["paimon", "test_db", "view.dot"]);
+ let definition = &shown[0][3];
+ assert!(
+ definition.starts_with("CREATE TEMPORARY VIEW "),
+ "{definition}"
+ );
+ assert!(definition.contains("\"answer value\""), "{definition}");
+ assert!(
+ definition.contains("SELECT 7 AS \"answer value\""),
+ "{definition}"
+ );
+ ctx.sql("DROP TEMPORARY VIEW paimon.test_db.\"view.dot\"")
+ .await
+ .unwrap();
+ ctx.sql(definition).await.unwrap();
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT \"answer value\" FROM paimon.test_db.\"view.dot\""
+ )
+ .await,
+ vec![vec!["7"]]
+ );
+}
+
+#[tokio::test]
+async fn show_create_view_rejects_temporary_tables() {
+ let (_tmp, ctx) = common::setup_sql_context().await;
+ ctx.sql("CREATE TEMPORARY TABLE paimon.test_db.v (id INT)")
+ .await
+ .unwrap();
+ common::assert_sql_error(&ctx, "SHOW CREATE VIEW paimon.test_db.v", "not a
view").await;
+}
+
+#[tokio::test]
+async fn show_create_view_supports_native_datafusion_views() {
+ let ctx = SQLContext::new();
+ ctx.sql("CREATE VIEW native_view AS SELECT 7 AS id")
+ .await
+ .unwrap();
+ let shown = rows(&ctx, "SHOW CREATE VIEW native_view").await;
+ assert_eq!(&shown[0][..3], &["datafusion", "public", "native_view"]);
+ assert!(shown[0][3].contains("AS SELECT 7 AS id"), "{}", shown[0][3]);
+ ctx.sql("DROP VIEW native_view").await.unwrap();
+ ctx.sql(&shown[0][3]).await.unwrap();
+ assert_eq!(
+ rows(&ctx, "SELECT id FROM native_view").await,
+ vec![vec!["7"]]
+ );
+}
+
+#[tokio::test]
+async fn show_create_view_round_trip_preserves_vector_values_and_type() {
+ let (_tmp, ctx) = common::setup_sql_context().await;
+ for (modifier, view) in [
+ ("", "datafusion.public.vector_view"),
+ ("TEMPORARY ", "paimon.test_db.vector_view"),
+ ] {
+ ctx.sql(&format!(
+ "CREATE {modifier}VIEW {view} AS SELECT CAST([1, 2] AS
VECTOR<FLOAT, 2>) AS embedding"
+ ))
+ .await
+ .unwrap();
+ let select = format!("SELECT embedding FROM {view}");
+ let original =
ctx.sql(&select).await.unwrap().collect().await.unwrap();
+ assert!(matches!(
+ original[0].schema().field(0).data_type(),
+ DataType::FixedSizeList(element, 2) if element.data_type() ==
&DataType::Float32
+ ));
+
+ let shown = rows(&ctx, &format!("SHOW CREATE VIEW {view}")).await;
+ ctx.sql(&format!("DROP {modifier}VIEW {view}"))
+ .await
+ .unwrap();
+ ctx.sql(&shown[0][3]).await.unwrap();
+ let recreated =
ctx.sql(&select).await.unwrap().collect().await.unwrap();
+ assert_eq!(recreated, original);
+ }
+}
+
+#[tokio::test]
+async fn show_create_view_preserves_creation_namespace() {
+ let (_tmp, ctx) = common::setup_sql_context().await;
+ ctx.sql("SET datafusion.catalog.default_catalog = 'datafusion'")
+ .await
+ .unwrap();
+ ctx.ctx().sql("CREATE SCHEMA other").await.unwrap();
+ let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32,
false)]));
+ for (name, id) in [
+ ("datafusion.public.source", 1),
+ ("datafusion.other.source", 2),
+ ] {
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![Arc::new(Int32Array::from(vec![id]))],
+ )
+ .unwrap();
+ ctx.ctx().register_batch(name, batch).unwrap();
+ }
+
+ let seed = "WITH RECURSIVE seed AS (SELECT id FROM
datafusion.public.source \
+ UNION ALL SELECT id FROM datafusion.other.source)";
+ // The destination and temporary catalog do not determine dependency
bindings.
+ for (modifier, view) in [
+ ("", "datafusion.public.bound_view"),
+ ("", "datafusion.other.bound_view"),
+ ("TEMPORARY ", "paimon.test_db.bound_view"),
+ ] {
+ for (query, expected) in [
+ ("SELECT id FROM source".to_string(), vec![vec!["1"]]),
+ (
+ format!("{seed}, source AS (SELECT id FROM source) SELECT id
FROM source"),
+ vec![vec!["1"]],
+ ),
+ (
+ format!("{seed}, a AS (SELECT id FROM source), source AS
(SELECT 99 AS id) SELECT id FROM a"),
+ vec![vec!["1"]],
+ ),
+ (
+ format!("{seed}, source AS (SELECT id FROM source UNION ALL
SELECT id + 1 FROM source WHERE id < 3) SELECT id FROM source ORDER BY id"),
+ vec![vec!["1"], vec!["2"], vec!["3"]],
+ ),
+ (
+ format!("{seed}, r AS (WITH unused AS (SELECT id FROM source)
SELECT 1 AS id UNION ALL SELECT id + 1 FROM r WHERE id < 3) SELECT id FROM r
ORDER BY id"),
+ vec![vec!["1"], vec!["2"], vec!["3"]],
+ ),
+ ] {
+ ctx.sql("SET datafusion.catalog.default_schema = 'public'")
+ .await
+ .unwrap();
+ ctx.sql(&format!("CREATE {modifier}VIEW {view} AS {query}"))
+ .await
+ .unwrap();
+ ctx.sql("SET datafusion.catalog.default_schema = 'other'")
+ .await
+ .unwrap();
+ let select = format!("SELECT id FROM {view} ORDER BY id");
+ assert_eq!(rows(&ctx, &select).await, expected);
+
+ let shown = rows(&ctx, &format!("SHOW CREATE VIEW {view}")).await;
+ let definition = &shown[0][3];
+ assert!(
+ definition.contains("FROM
\"datafusion\".\"public\".\"source\""),
+ "{definition}"
+ );
+ ctx.sql(&format!("DROP {modifier}VIEW {view}")).await.unwrap();
+ ctx.sql(definition).await.unwrap();
+ assert_eq!(rows(&ctx, &select).await, expected);
+ ctx.sql(&format!("DROP {modifier}VIEW {view}")).await.unwrap();
+ }
+ }
+}
+
+#[tokio::test]
+async fn show_create_direct_native_view_requires_bound_dependencies() {
+ let ctx = SQLContext::new();
+ ctx.ctx().sql("CREATE SCHEMA other").await.unwrap();
+ let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32,
false)]));
+ for (name, id) in [
+ ("datafusion.public.source", 1),
+ ("datafusion.other.source", 2),
+ ] {
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![Arc::new(Int32Array::from(vec![id]))],
+ )
+ .unwrap();
+ ctx.ctx().register_batch(name, batch).unwrap();
+ }
+
+ for destination in ["public", "other"] {
+ for (query, can_export) in [
+ ("SELECT id FROM source", false),
+ ("SELECT id FROM public.source", false),
+ (
+ "WITH source AS (SELECT id FROM source) SELECT id FROM source",
+ false,
+ ),
+ (
+ "WITH RECURSIVE seed AS (SELECT id FROM
datafusion.public.source \
+ UNION ALL SELECT id FROM datafusion.other.source), \
+ source AS (SELECT id FROM source) SELECT id FROM source",
+ false,
+ ),
+ (
+ "WITH RECURSIVE seed AS (SELECT id FROM
datafusion.public.source \
+ UNION ALL SELECT id FROM datafusion.other.source), \
+ a AS (SELECT id FROM source), source AS (SELECT 99 AS id)
SELECT id FROM a",
+ false,
+ ),
+ (
+ "WITH RECURSIVE seed AS (SELECT id FROM
datafusion.public.source \
+ UNION ALL SELECT id FROM datafusion.other.source), \
+ source AS (SELECT id FROM source UNION ALL SELECT id + 1 FROM
source WHERE id < 2) \
+ SELECT id FROM source WHERE id = 1",
+ false,
+ ),
+ ("SELECT id FROM datafusion.public.source", true),
+ (
+ "WITH RECURSIVE r AS (WITH unused AS (SELECT id FROM source)
SELECT 1 AS id UNION ALL SELECT id + 1 FROM r WHERE id < 2) SELECT id FROM r
WHERE id = 1",
+ false,
+ ),
+ (
+ "WITH RECURSIVE r AS (WITH unused AS (SELECT id FROM
datafusion.public.source) SELECT 1 AS id UNION ALL SELECT id + 1 FROM r WHERE
id < 2) SELECT id FROM r WHERE id = 1",
+ true,
+ ),
+ (
+ "WITH source AS (SELECT 1 AS id) SELECT id FROM source",
+ true,
+ ),
+ (
+ "WITH RECURSIVE source AS (SELECT id FROM
datafusion.public.source UNION ALL SELECT id + 1 FROM source WHERE id < 2)
SELECT id FROM source WHERE id = 1",
+ true,
+ ),
+ (
+ "WITH RECURSIVE seed AS (SELECT 1 AS id), source AS (SELECT id
FROM seed) SELECT id FROM source",
+ true,
+ ),
+ ("SELECT 1 AS id FROM generate_series(1, 1)", true),
+ ] {
+ ctx.sql("SET datafusion.catalog.default_schema = 'public'")
+ .await
+ .unwrap();
+ let view = format!("datafusion.{destination}.direct_native");
+ ctx.ctx()
+ .sql(&format!("CREATE VIEW {view} AS {query}"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ ctx.sql("SET datafusion.catalog.default_schema = 'other'")
+ .await
+ .unwrap();
+ let select = format!("SELECT id FROM {view}");
+ assert_eq!(rows(&ctx, &select).await, vec![vec!["1"]]);
+ let show = format!("SHOW CREATE VIEW {view}");
+ if can_export {
+ let shown = rows(&ctx, &show).await;
+ ctx.sql(&format!("DROP VIEW {view}")).await.unwrap();
+ ctx.sql(&shown[0][3]).await.unwrap();
+ } else {
+ common::assert_sql_error(&ctx, &show, "unqualified
dependency").await;
+ }
+ assert_eq!(rows(&ctx, &select).await, vec![vec!["1"]]);
+ ctx.sql(&format!("DROP VIEW {view}")).await.unwrap();
+ }
+ }
+}
+
+#[tokio::test]
+async fn group_concat_order_position_refers_to_aggregate_arguments() {
+ let ctx = SQLContext::new();
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT group_concat(v ORDER BY 1 SEPARATOR '|') FROM (VALUES
(1,'b'),(2,'a')) t(k,v)"
+ )
+ .await,
+ vec![vec!["a|b"]]
+ );
+ assert_eq!(
+ rows(&ctx, "SELECT group_concat(7 ORDER BY 1 SEPARATOR '|')").await,
+ vec![vec!["7"]]
+ );
+ assert_eq!(rows(&ctx, "SELECT group_concat(a,b ORDER BY 2 SEPARATOR ';')
FROM (VALUES ('a',2),('b',1)) t(a,b)").await,
+ vec![vec!["b1;a2"]]);
+ for position in [0, 2] {
+ common::assert_sql_error(
+ &ctx,
+ &format!("SELECT group_concat('x' ORDER BY {position} SEPARATOR
'|')"),
+ "position must be between",
+ )
+ .await;
+ }
+}
+
+#[tokio::test]
+async fn group_concat_evaluates_volatile_row_arguments_once() {
+ use datafusion::logical_expr::{create_udf, ColumnarValue, Volatility};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let ctx = SQLContext::new();
+ let calls = Arc::new(AtomicUsize::new(0));
+ let observed = Arc::clone(&calls);
+ ctx.ctx().register_udf(create_udf(
+ "probe_value",
+ vec![DataType::Int64],
+ DataType::Utf8,
+ Volatility::Volatile,
+ Arc::new(move |_| {
+ Ok(ColumnarValue::Scalar(ScalarValue::Utf8(
+ (observed.fetch_add(1, Ordering::SeqCst) == 0).then(||
"x".to_string()),
+ )))
+ }),
+ ));
+ for expression in [
+ "group_concat(probe_value(1), 'z' SEPARATOR '|')",
+ "group_concat(probe_value(1), 'z' ORDER BY 2 SEPARATOR '|')",
+ "group_concat(probe_value(1) SEPARATOR '|')",
+ "group_concat(probe_value(1) SEPARATOR '|') OVER ()",
+ ] {
+ calls.store(0, Ordering::SeqCst);
+ let expected = if expression.contains("'z'") {
+ "xz"
+ } else {
+ "x"
+ };
+ assert_eq!(
+ rows(&ctx, &format!("SELECT {expression} AS joined")).await,
+ vec![vec![expected]],
+ "{expression}"
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 1, "{expression}");
+ }
+ calls.store(0, Ordering::SeqCst);
+ for expression in [
+ "group_concat(probe_value(1), 'z' ORDER BY 1 SEPARATOR '|')",
+ "group_concat(probe_value(1) ORDER BY 1 SEPARATOR '|')",
+ ] {
+ common::assert_sql_error(&ctx, &format!("SELECT {expression}"),
"volatile").await;
+ }
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ assert_eq!(rows(&ctx,
+ "SELECT group_concat(v, 'z' ORDER BY 1 SEPARATOR '|') FROM (SELECT
probe_value(1) AS v) t").await,
+ vec![vec!["xz"]]);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn group_concat_formats_single_and_multiple_arguments_consistently() {
+ let ctx = SQLContext::new();
+ for value in [
+ "CAST(5 AS DOUBLE)",
+ "CAST('-0.0' AS DOUBLE)",
+ "CAST(1.25 AS DOUBLE)",
+ ] {
+ let result = rows(&ctx, &format!("SELECT group_concat(v SEPARATOR
'|'), group_concat(v, '' SEPARATOR '|') FROM (VALUES ({value})) t(v)")).await;
+ assert_eq!(result[0][0], result[0][1], "{value}: {result:?}");
+ }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 340bc831..8c3bd1e5 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -47,6 +47,28 @@ Not every DataFusion DDL/DML statement maps to a Paimon
table operation. For Pai
For the exact delegated SQL grammar, see the [DataFusion SQL
Reference](https://datafusion.apache.org/user-guide/sql/index.html).
+### SQL compatibility
+
+`GROUP_CONCAT` joins non-NULL values with a comma by default. `SEPARATOR`
accepts
+a string literal, including an empty string. Multiple arguments are
concatenated
+within each row; a row with any NULL argument is skipped. Empty groups and
+groups containing only NULL values return NULL. `DISTINCT`, aggregate `ORDER
BY`,
+and `FILTER` are supported. `DISTINCT` accepts one expression, and its ordering
+expressions must match that expression, as required by DataFusion's distinct
+aggregation.
+Numeric `ORDER BY` positions refer to the aggregate arguments. Calls reject
+positions that reference volatile expressions, because those
+arguments cannot safely be evaluated again as native aggregate sort keys.
+Compute such a value in a subquery first, then pass its column to
`GROUP_CONCAT`.
+String conversion follows DataFusion's `CAST(... AS STRING)` after typed
+deduplication and sorting.
+
+```sql
+SELECT group_concat(DISTINCT name ORDER BY name SEPARATOR ' | ') FROM users;
+```
+
+`GROUP_CONCAT` also works in Paimon persistent and temporary view definitions.
+
### DataFusion 55 integration
Paimon Parquet scans refresh supported dynamic predicates before reading each
@@ -244,6 +266,22 @@ the new view's owning catalog and database, not the
session's current database.
The canonical query is stored as both the default query and the `datafusion`
dialect definition.
+`SHOW CREATE VIEW view_name` returns the owning catalog, database, view name,
+and a fully qualified `CREATE VIEW` definition with its declared column names
+and types. The exported query includes the same type casts as view reads.
+It prefers the stored `datafusion` query and reads catalog metadata directly,
+without planning or executing the defining query. Temporary views shadow
+persistent objects and return `CREATE TEMPORARY VIEW`; session-native
+DataFusion views are also supported. Temporary definitions bind table and
+Catalog function names to the namespace used at creation, so recreating them
+after `USE` preserves their dependencies. Native views created through
+`SQLContext::sql` also bind their table dependencies at creation. Definitions
+created directly through `SessionContext` must fully qualify physical table
+references as `catalog.schema.table`; exports with unqualified dependencies
+are rejected because their creation namespace cannot be recovered reliably.
+Repeated exports and recreations keep the type projection stable. Table targets
+are rejected.
+
Persistent `CREATE VIEW` and `DROP VIEW` are currently implemented by REST
Catalog. `DROP VIEW` sends a direct delete request; `IF EXISTS` ignores only a
missing-view response. Bare, two-part, and three-part names are supported, but