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 cccc24d5 feat(datafusion): support lateral collection generators
(#1292)
cccc24d5 is described below
commit cccc24d5b27a0f92373829111f9228c389ed9a31
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 09:16:09 2026 +0800
feat(datafusion): support lateral collection generators (#1292)
* feat(datafusion): support lateral collection generators
* fix(datafusion): distinguish generator aliases from query clauses
---
crates/integrations/datafusion/src/catalog.rs | 3 +-
.../integrations/datafusion/src/lateral_views.rs | 567 +++++++++++++++++++++
crates/integrations/datafusion/src/lib.rs | 1 +
crates/integrations/datafusion/src/sql_context.rs | 14 +-
crates/integrations/datafusion/src/sql_function.rs | 4 +-
.../datafusion/tests/feature_combination.rs | 65 +++
.../integrations/datafusion/tests/lateral_views.rs | 169 ++++++
docs/src/sql.md | 25 +
8 files changed, 841 insertions(+), 7 deletions(-)
diff --git a/crates/integrations/datafusion/src/catalog.rs
b/crates/integrations/datafusion/src/catalog.rs
index 76b79c2b..f98e0f75 100644
--- a/crates/integrations/datafusion/src/catalog.rs
+++ b/crates/integrations/datafusion/src/catalog.rs
@@ -1426,7 +1426,8 @@ async fn validate_view_dependencies(
}
fn view_relation_identifiers(view: &View, catalog_name: &str) ->
DFResult<Vec<Identifier>> {
- let parseable =
crate::regex_operators::parseable_sql(view.query_for("datafusion"))?;
+ 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 =
Parser::parse_sql(&GenericDialect {},
parseable.as_ref()).map_err(|error| {
plan_datafusion_err!(
diff --git a/crates/integrations/datafusion/src/lateral_views.rs
b/crates/integrations/datafusion/src/lateral_views.rs
new file mode 100644
index 00000000..bd19c149
--- /dev/null
+++ b/crates/integrations/datafusion/src/lateral_views.rs
@@ -0,0 +1,567 @@
+// 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.
+
+use datafusion::arrow::array::{
+ new_empty_array, Array, ArrayRef, BooleanArray, FixedSizeListArray,
Int32Array, LargeListArray,
+ ListArray, MapArray, StructArray, UInt64Array,
+};
+use datafusion::arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use datafusion::arrow::compute::take;
+use datafusion::arrow::datatypes::{DataType, Field, Fields};
+use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
Volatility,
+};
+use datafusion::prelude::SessionContext;
+use datafusion::sql::sqlparser::{
+ ast::{
+ self, visit_expressions_mut, Expr, FunctionArg, FunctionArgExpr,
FunctionArguments,
+ SetExpr, Statement, VisitMut, VisitorMut,
+ },
+ dialect::GenericDialect,
+ parser::Parser,
+};
+use std::ops::ControlFlow;
+use std::sync::Arc;
+
+fn plan_error(message: &str) -> DataFusionError {
+ DataFusionError::Plan(message.into())
+}
+fn decoded(mut ty: &DataType) -> &DataType {
+ while let DataType::Dictionary(_, v) = ty {
+ ty = v;
+ }
+ ty
+}
+fn output_fields(ty: &DataType) -> Result<Fields> {
+ let mut fields = vec![Field::new("pos", DataType::Int32, true)];
+ match decoded(ty) {
+ DataType::List(f) | DataType::LargeList(f) |
DataType::FixedSizeList(f, _) => {
+ fields.push(Field::new("col", f.data_type().clone(), true))
+ }
+ DataType::Map(f, _) => {
+ let DataType::Struct(entries) = f.data_type() else {
+ return Err(plan_error("Invalid map entries"));
+ };
+ fields.push(Field::new("key", entries[0].data_type().clone(),
true));
+ fields.push(Field::new("value", entries[1].data_type().clone(),
true));
+ }
+ DataType::Null => fields.push(Field::new("col", DataType::Null, true)),
+ _ => return Err(plan_error("explode expects an array or map")),
+ }
+ Ok(fields.into())
+}
+#[derive(Debug, PartialEq, Eq, Hash)]
+struct Explode {
+ signature: Signature,
+}
+pub(crate) fn register(ctx: &SessionContext) {
+ ctx.register_udf(ScalarUDF::from(Explode {
+ signature: Signature::user_defined(Volatility::Immutable),
+ }));
+}
+impl ScalarUDFImpl for Explode {
+ fn name(&self) -> &str {
+ "__paimon_explode"
+ }
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+ fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+ let [ty, flag] = types else {
+ return Err(plan_error("explode expects collection and outer
flag"));
+ };
+ output_fields(ty)?;
+ if !matches!(flag, DataType::Boolean | DataType::Null) {
+ return Err(plan_error("explode outer flag must be BOOLEAN"));
+ }
+ Ok(vec![decoded(ty).clone(), DataType::Boolean])
+ }
+ fn return_type(&self, types: &[DataType]) -> Result<DataType> {
+ Ok(DataType::List(Arc::new(Field::new(
+ "item",
+ DataType::Struct(output_fields(&types[0])?),
+ true,
+ ))))
+ }
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+ let input = &arrays[0];
+ let outer = arrays[1].as_any().downcast_ref::<BooleanArray>().unwrap();
+ let fields = output_fields(input.data_type())?;
+ let values: ArrayRef = match input.data_type() {
+ DataType::List(_) => input
+ .as_any()
+ .downcast_ref::<ListArray>()
+ .unwrap()
+ .values()
+ .clone(),
+ DataType::LargeList(_) => input
+ .as_any()
+ .downcast_ref::<LargeListArray>()
+ .unwrap()
+ .values()
+ .clone(),
+ DataType::FixedSizeList(_, _) => input
+ .as_any()
+ .downcast_ref::<FixedSizeListArray>()
+ .unwrap()
+ .values()
+ .clone(),
+ DataType::Map(_, _) => Arc::new(
+ input
+ .as_any()
+ .downcast_ref::<MapArray>()
+ .unwrap()
+ .entries()
+ .clone(),
+ ),
+ _ => new_empty_array(&DataType::Null),
+ };
+ let mut offsets = vec![0i32];
+ let mut indices = Vec::new();
+ let mut positions = Vec::new();
+ for row in 0..input.len() {
+ if outer.is_null(row) {
+ return Err(plan_error("explode outer flag must be non-null"));
+ }
+ let (start, len) = if input.is_null(row) {
+ (0, 0)
+ } else {
+ match input.data_type() {
+ DataType::List(_) => {
+ let a =
input.as_any().downcast_ref::<ListArray>().unwrap();
+ (
+ a.value_offsets()[row] as usize,
+ a.value_length(row) as usize,
+ )
+ }
+ DataType::LargeList(_) => {
+ let a =
input.as_any().downcast_ref::<LargeListArray>().unwrap();
+ (
+ a.value_offsets()[row] as usize,
+ a.value_length(row) as usize,
+ )
+ }
+ DataType::FixedSizeList(_, _) => {
+ let a =
input.as_any().downcast_ref::<FixedSizeListArray>().unwrap();
+ (a.value_offset(row) as usize, a.value_length() as
usize)
+ }
+ DataType::Map(_, _) => {
+ let a =
input.as_any().downcast_ref::<MapArray>().unwrap();
+ (
+ a.value_offsets()[row] as usize,
+ a.value_length(row) as usize,
+ )
+ }
+ _ => (0, 0),
+ }
+ };
+ if len == 0 && outer.value(row) {
+ indices.push(None);
+ positions.push(None);
+ }
+ for pos in 0..len {
+ positions
+ .push(Some(i32::try_from(pos).map_err(|_| {
+ plan_error("explode position exceeds INT range")
+ })?));
+ indices.push(Some((start + pos) as u64));
+ }
+ offsets.push(
+ i32::try_from(indices.len())
+ .map_err(|_| plan_error("explode batch exceeds Arrow list
offset range"))?,
+ );
+ }
+ let selected = take(values.as_ref(), &UInt64Array::from(indices),
None)?;
+ let mut columns: Vec<ArrayRef> =
vec![Arc::new(Int32Array::from(positions))];
+ if let DataType::Map(_, _) = input.data_type() {
+ let entries =
selected.as_any().downcast_ref::<StructArray>().unwrap();
+ columns.extend(entries.columns().iter().cloned());
+ } else {
+ columns.push(selected);
+ }
+ let entries = Arc::new(StructArray::try_new(fields.clone(), columns,
None)?);
+ let output = Arc::new(ListArray::try_new(
+ Arc::new(Field::new("item", DataType::Struct(fields), true)),
+ OffsetBuffer::new(ScalarBuffer::from(offsets)),
+ entries,
+ None,
+ )?);
+ if args
+ .args
+ .iter()
+ .all(|a| matches!(a, ColumnarValue::Scalar(_)))
+ {
+ Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ output.as_ref(),
+ 0,
+ )?))
+ } else {
+ Ok(ColumnarValue::Array(output))
+ }
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct ExplodeRelationPlanner;
+impl datafusion::logical_expr::planner::RelationPlanner for
ExplodeRelationPlanner {
+ fn plan_relation(
+ &self,
+ relation: ast::TableFactor,
+ context: &mut dyn
datafusion::logical_expr::planner::RelationPlannerContext,
+ ) -> Result<datafusion::logical_expr::planner::RelationPlanning> {
+ use datafusion::logical_expr::planner::{PlannedRelation,
RelationPlanning};
+ use datafusion::logical_expr::{Expr as LogicalExpr, ExprSchemable,
LogicalPlanBuilder};
+ let ast::TableFactor::NestedJoin {
+ table_with_joins,
+ alias: wrapper_alias,
+ } = &relation
+ else {
+ return Ok(RelationPlanning::Original(Box::new(relation)));
+ };
+ let Some(join) = table_with_joins.joins.last() else {
+ return Ok(RelationPlanning::Original(Box::new(relation)));
+ };
+ let ast::TableFactor::Function {
+ name,
+ args,
+ alias: Some(alias),
+ lateral: true,
+ with_ordinality: false,
+ } = &join.relation
+ else {
+ return Ok(RelationPlanning::Original(Box::new(relation)));
+ };
+ if name.to_string() != "__paimon_lateral_explode"
+ || !matches!(
+ join.join_operator,
+ ast::JoinOperator::CrossJoin(ast::JoinConstraint::None)
+ )
+ {
+ return Ok(RelationPlanning::Original(Box::new(relation)));
+ }
+ let [FunctionArg::Unnamed(FunctionArgExpr::Expr(input)),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(outer))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(positional)))] =
+ args.as_slice()
+ else {
+ return Err(plan_error("Invalid lateral explode arguments"));
+ };
+ let (ast::Value::Boolean(outer), ast::Value::Boolean(positional)) =
+ (&outer.value, &positional.value)
+ else {
+ return Err(plan_error("Invalid lateral explode flags"));
+ };
+ let mut parent = table_with_joins.as_ref().clone();
+ parent.joins.pop();
+ let left = context.plan(ast::TableFactor::NestedJoin {
+ table_with_joins: Box::new(parent),
+ alias: None,
+ })?;
+ let input = context.sql_to_expr(input.clone(), left.schema())?;
+ let fields = output_fields(&input.get_type(left.schema())?)?;
+ let fields = fields
+ .iter()
+ .skip(if *positional { 0 } else { 1 })
+ .collect::<Vec<_>>();
+ if !alias.columns.is_empty() && alias.columns.len() != fields.len() {
+ return Err(plan_error("Wrong number of generator column aliases"));
+ }
+ let internal = format!("__paimon_explode_{}",
uuid::Uuid::new_v4().as_simple());
+ let mut columns = left
+ .schema()
+ .columns()
+ .into_iter()
+ .map(LogicalExpr::Column)
+ .collect::<Vec<_>>();
+ let mut expressions = columns.clone();
+ expressions.push(
+ ScalarUDF::from(Explode {
+ signature: Signature::user_defined(Volatility::Immutable),
+ })
+ .call(vec![input, datafusion::logical_expr::lit(*outer)])
+ .alias(&internal),
+ );
+ let expanded = LogicalPlanBuilder::from(left)
+ .project(expressions)?
+ .unnest_column(internal.as_str())?
+ .unnest_column(internal.as_str())?
+ .build()?;
+ for (index, field) in fields.iter().enumerate() {
+ let name = alias
+ .columns
+ .get(index)
+ .map(|c| context.normalize_ident(c.name.clone()))
+ .unwrap_or_else(|| field.name().clone());
+ columns.push(
+
LogicalExpr::Column(datafusion::common::Column::from_name(format!(
+ "{internal}.{}",
+ field.name()
+ )))
+ .alias_qualified(
+ Some(datafusion::common::TableReference::bare(
+ context.normalize_ident(alias.name.clone()),
+ )),
+ name,
+ ),
+ );
+ }
+ let plan = LogicalPlanBuilder::from(expanded)
+ .project(columns)?
+ .build()?;
+ Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
+ plan,
+ wrapper_alias.clone(),
+ ))))
+ }
+}
+
+pub(crate) fn rewrite(statement: &mut Statement) -> Result<bool> {
+ struct Lower {
+ changed: bool,
+ }
+ impl VisitorMut for Lower {
+ type Break = DataFusionError;
+ fn post_visit_select(&mut self, select: &mut ast::Select) ->
ControlFlow<Self::Break> {
+ if select.lateral_views.is_empty() {
+ return ControlFlow::Continue(());
+ }
+ if select.from.len() != 1 {
+ return ControlFlow::Break(plan_error(
+ "LATERAL VIEW requires one FROM relation; use explicit
joins",
+ ));
+ }
+ for view in std::mem::take(&mut select.lateral_views) {
+ let Expr::Function(function) = view.lateral_view else {
+ return ControlFlow::Break(plan_error("Unsupported LATERAL
VIEW expression"));
+ };
+ let name = function.name.to_string().to_ascii_lowercase();
+ if function.name.0.len() != 1
+ || !matches!(
+ name.as_str(),
+ "explode" | "explode_outer" | "posexplode" |
"posexplode_outer"
+ )
+ {
+ return ControlFlow::Break(plan_error(
+ "LATERAL VIEW supports explode and posexplode,
including outer variants",
+ ));
+ }
+ let FunctionArguments::List(args) = function.args else {
+ return ControlFlow::Break(plan_error("explode requires one
argument"));
+ };
+ if args.duplicate_treatment.is_some()
+ || !args.clauses.is_empty()
+ || function.filter.is_some()
+ || function.over.is_some()
+ || !function.within_group.is_empty()
+ {
+ return ControlFlow::Break(plan_error("Generator modifiers
are not supported"));
+ }
+ let [FunctionArg::Unnamed(FunctionArgExpr::Expr(input))] =
args.args.as_slice()
+ else {
+ return ControlFlow::Break(plan_error(
+ "explode requires one positional expression",
+ ));
+ };
+ if view.lateral_view_name.0.len() != 1 {
+ return ControlFlow::Break(plan_error(
+ "LATERAL VIEW alias must be a simple identifier",
+ ));
+ }
+ let positional = name.starts_with("pos");
+ let outer = view.outer || name.ends_with("_outer");
+ let aliases = if view.lateral_col_alias.is_empty() {
+ String::new()
+ } else {
+ format!(
+ "({})",
+ view.lateral_col_alias
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(",")
+ )
+ };
+ let sql=format!("SELECT * FROM parent CROSS JOIN LATERAL
__paimon_lateral_explode(NULL, {outer}, {positional}) AS
{}{aliases}",view.lateral_view_name);
+ let mut statement = match Parser::parse_sql(&GenericDialect
{}, &sql) {
+ Ok(mut s) => s.remove(0),
+ Err(e) => return
ControlFlow::Break(plan_error(&e.to_string())),
+ };
+ let _: ControlFlow<()> = visit_expressions_mut(&mut statement,
|expr| {
+ if matches!(expr,Expr::Value(v) if
v.value==ast::Value::Null) {
+ *expr = input.clone();
+ }
+ ControlFlow::Continue(())
+ });
+ if let Statement::Query(q) = statement {
+ if let SetExpr::Select(mut s) = *q.body {
+ let mut parent = select.from.remove(0);
+ parent.joins.push(s.from[0].joins.remove(0));
+ select.from.push(ast::TableWithJoins {
+ relation: ast::TableFactor::NestedJoin {
+ table_with_joins: Box::new(parent),
+ alias: None,
+ },
+ joins: vec![],
+ });
+ }
+ }
+ self.changed = true;
+ }
+ ControlFlow::Continue(())
+ }
+ }
+ let mut lower = Lower { changed: false };
+ match statement.visit(&mut lower) {
+ ControlFlow::Break(e) => Err(e),
+ _ => Ok(lower.changed),
+ }
+}
+
+/// sqlparser 0.62 mistakes query-ending clauses for an optional generator
alias.
+/// A tautological WHERE terminates the alias list without changing query
results.
+pub(crate) fn parseable_sql(sql: &str) -> Result<std::borrow::Cow<'_, str>> {
+ use datafusion::sql::sqlparser::{
+ keywords::Keyword as K,
+ tokenizer::{Token, Tokenizer},
+ };
+ let starts_expression = |token: &Token| match token {
+ Token::Word(word) => {
+ word.quote_style.is_some()
+ ||
(!datafusion::sql::sqlparser::keywords::RESERVED_FOR_COLUMN_ALIAS
+ .contains(&word.keyword)
+ && !matches!(
+ word.keyword,
+ K::AS
+ | K::BY
+ | K::WINDOW
+ | K::QUALIFY
+ | K::LIMIT
+ | K::OFFSET
+ | K::FETCH
+ | K::SORT
+ | K::DISTRIBUTE
+ | K::CLUSTER
+ | K::LATERAL
+ ))
+ }
+ Token::EOF
+ | Token::RParen
+ | Token::RBracket
+ | Token::Comma
+ | Token::SemiColon
+ | Token::Period => false,
+ _ => true,
+ };
+ let tokens = Tokenizer::new(&GenericDialect {}, sql)
+ .tokenize_with_location()
+ .map_err(|e| plan_error(&format!("SQL parse error: {e}")))?;
+ let significant = tokens
+ .iter()
+ .filter(|t| !matches!(t.token, Token::Whitespace(_)))
+ .collect::<Vec<_>>();
+ let mut depth = 0i32;
+ #[derive(Clone, Copy, PartialEq, Eq)]
+ enum Phase {
+ Function,
+ Arguments,
+ TableAlias,
+ Columns,
+ }
+ let mut active = std::collections::HashMap::new();
+ let mut positions = Vec::new();
+ for (index, token) in significant.iter().enumerate() {
+ if token.token == Token::RParen {
+ active.remove(&depth);
+ depth -= 1;
+ if active.get(&depth) == Some(&Phase::Arguments) {
+ active.insert(depth, Phase::TableAlias);
+ }
+ }
+ if matches!(&token.token,Token::Word(w) if w.keyword==K::VIEW)
+ && index > 0
+ && matches!(&significant[index-1].token,Token::Word(w) if
w.keyword==K::LATERAL)
+ {
+ active.insert(depth, Phase::Function);
+ }
+ if active.get(&depth) == Some(&Phase::TableAlias)
+ && matches!(
+ token.token,
+ Token::Word(_) | Token::SingleQuotedString(_) |
Token::DoubleQuotedString(_)
+ )
+ {
+ active.insert(depth, Phase::Columns);
+ continue;
+ }
+ if active.get(&depth) == Some(&Phase::Columns) {
+ if let Token::Word(word) = &token.token {
+ let next = significant.get(index + 1).map(|t| &t.token);
+ let ending = match word.keyword {
+ K::ORDER | K::SORT | K::DISTRIBUTE => {
+ matches!(next,Some(Token::Word(w)) if w.keyword==K::BY)
+ }
+ K::LIMIT | K::OFFSET | K::QUALIFY =>
next.is_some_and(starts_expression),
+ K::FETCH => {
+ matches!(next,Some(Token::Word(w)) if
matches!(w.keyword,K::FIRST|K::NEXT))
+ }
+ K::UNION | K::INTERSECT | K::EXCEPT => {
+ matches!(next, Some(Token::LParen))
+ || matches!(next,Some(Token::Word(w)) if
matches!(w.keyword,K::ALL|K::DISTINCT|K::SELECT))
+ }
+ K::WINDOW => {
+
matches!(significant.get(index+2).map(|t|&t.token),Some(Token::Word(w)) if
w.keyword==K::AS)
+ }
+ _ => false,
+ };
+ if ending {
+ let mut offset = 0;
+ for (line_index, line) in
sql.split_inclusive('\n').enumerate() {
+ if line_index + 1 == token.span.start.line as usize {
+ offset += line
+ .char_indices()
+ .nth(token.span.start.column as usize - 1)
+ .map(|(i, _)| i)
+ .unwrap_or(line.len());
+ break;
+ }
+ offset += line.len();
+ }
+ positions.push(offset);
+ active.remove(&depth);
+ } else if matches!(
+ word.keyword,
+ K::AS | K::WHERE | K::GROUP | K::CLUSTER | K::HAVING |
K::LATERAL
+ ) {
+ active.remove(&depth);
+ }
+ }
+ }
+ if token.token == Token::LParen {
+ if active.get(&depth) == Some(&Phase::Function) {
+ active.insert(depth, Phase::Arguments);
+ }
+ depth += 1;
+ }
+ }
+ if positions.is_empty() || Parser::parse_sql(&GenericDialect {},
sql).is_ok() {
+ return Ok(std::borrow::Cow::Borrowed(sql));
+ }
+ let mut output = sql.to_string();
+ for position in positions.into_iter().rev() {
+ output.insert_str(position, " WHERE TRUE ");
+ }
+ Ok(std::borrow::Cow::Owned(output))
+}
diff --git a/crates/integrations/datafusion/src/lib.rs
b/crates/integrations/datafusion/src/lib.rs
index d9fb191e..b34d0a32 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -56,6 +56,7 @@ mod golden_warehouse;
mod hybrid_search;
mod json_functions;
mod lateral_vector_search;
+mod lateral_views;
mod memory;
mod merge_condition;
mod merge_into;
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index f63be7ac..b3d88315 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -158,9 +158,10 @@ impl SQLContextBuilder {
.with_config(crate::lateral_vector_search::session_config())
.with_default_features()
.with_type_planner(Arc::new(crate::binary_cast::BinaryTypePlanner))
- .with_relation_planners(vec![Arc::new(
- crate::relation_planner::PaimonRelationPlanner::new(),
- )])
+ .with_relation_planners(vec![
+ Arc::new(crate::lateral_views::ExplodeRelationPlanner),
+
Arc::new(crate::relation_planner::PaimonRelationPlanner::new()),
+ ])
.with_optimizer_rules(crate::lateral_vector_search::optimizer_rules())
.with_query_planner(Arc::new(
crate::lateral_vector_search::PaimonQueryPlanner::new(),
@@ -172,6 +173,7 @@ impl SQLContextBuilder {
let ctx = SessionContext::new_with_state(state);
crate::compat_functions::register_compat_functions(&ctx);
crate::binary_cast::register(&ctx);
+ crate::lateral_views::register(&ctx);
crate::scalar_compat::register(&ctx);
crate::blob_descriptor_functions::register_blob_descriptor_functions(&ctx);
crate::variant_functions::register_variant_functions(&ctx);
@@ -501,7 +503,8 @@ impl SQLContext {
let changed = !persistent_definition && {
let binary_changed = crate::binary_cast::rewrite(&mut
statements[0])?;
let regex_changed = crate::regex_operators::rewrite(&mut
statements[0]);
- binary_changed || regex_changed
+ let lateral_changed = crate::lateral_views::rewrite(&mut
statements[0])?;
+ binary_changed || regex_changed || lateral_changed
};
let sql = if changed {
rewritten = statements[0].to_string();
@@ -2692,7 +2695,8 @@ fn validate_persistent_create_function(create_function:
&CreateFunction) -> DFRe
}
fn parse_sql_statements(sql: &str) -> DFResult<Vec<Statement>> {
- let parseable = crate::regex_operators::parseable_sql(sql)?;
+ let regex_sql = crate::regex_operators::parseable_sql(sql)?;
+ let parseable = crate::lateral_views::parseable_sql(regex_sql.as_ref())?;
let sql = parseable.as_ref();
let dialect = GenericDialect {};
let mut tokens = Tokenizer::new(&dialect, sql)
diff --git a/crates/integrations/datafusion/src/sql_function.rs
b/crates/integrations/datafusion/src/sql_function.rs
index 9d53b31c..0fd6a4bf 100644
--- a/crates/integrations/datafusion/src/sql_function.rs
+++ b/crates/integrations/datafusion/src/sql_function.rs
@@ -61,7 +61,8 @@ async fn expand_sql_internal(
current_database: &str,
candidate: Option<&Function>,
) -> DFResult<String> {
- let parseable = crate::regex_operators::parseable_sql(sql)?;
+ let regex_sql = crate::regex_operators::parseable_sql(sql)?;
+ let parseable = crate::lateral_views::parseable_sql(regex_sql.as_ref())?;
let mut statements = Parser::parse_sql(&GenericDialect {},
parseable.as_ref())
.map_err(|error| DataFusionError::Plan(format!("Invalid REST SQL:
{error}")))?;
if statements.len() != 1 {
@@ -149,6 +150,7 @@ async fn expand_statement_internal(
max_expanded_calls: usize,
candidate: Option<&Function>,
) -> DFResult<Statement> {
+ crate::lateral_views::rewrite(&mut statement)?;
let candidate_reference =
candidate.map(|function| (current_catalog.to_string(),
function.identifier().clone()));
let mut functions = HashMap::new();
diff --git a/crates/integrations/datafusion/tests/feature_combination.rs
b/crates/integrations/datafusion/tests/feature_combination.rs
new file mode 100644
index 00000000..0896e620
--- /dev/null
+++ b/crates/integrations/datafusion/tests/feature_combination.rs
@@ -0,0 +1,65 @@
+// 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 datafusion::common::ScalarValue;
+use paimon::{catalog::Identifier, Catalog};
+#[tokio::test]
+async fn six_sql_extensions_work_together() {
+ let (_tmp, catalog) = common::create_test_env();
+ let ctx = common::create_sql_context(catalog.clone()).await;
+ ctx.sql("CREATE TABLE default.events (id INT, txt STRING, b VARBINARY)
COMMENT 'events'")
+ .await
+ .unwrap();
+ ctx.sql("INSERT INTO default.events VALUES (1,'a,b',CAST('xy' AS
BINARY(4))), (2,NULL,CAST(NULL AS
BINARY))").await.unwrap().collect().await.unwrap();
+ ctx.sql("ALTER TABLE default.events ALTER COLUMN txt COMMENT 'tokens'")
+ .await
+ .unwrap();
+ ctx.sql("CALL sys.create_tag(table => concat('default.','events'), tag =>
concat('v','1'), snapshot_id => CAST(1+0 AS BIGINT))").await.unwrap();
+ let table = catalog
+ .get_table(&Identifier::new("default", "events"))
+ .await
+ .unwrap();
+ assert_eq!(table.schema().comment(), Some("events"));
+ assert_eq!(table.schema().fields()[1].description(), Some("tokens"));
+ assert_eq!(
+ table.tag_manager().get("v1").await.unwrap().unwrap().id(),
+ 1
+ );
+ let batches=ctx.sql("SELECT
id,p.pos,p.val,hex(b),typeof(p.val),size(split(txt,',')),hour(TIME '12:00:00')
FROM default.events LATERAL VIEW posexplode_outer(split(txt,',')) p AS pos,val
WHERE p.val RLIKE '^a$' OR p.val IS NULL ORDER BY
id,p.pos").await.unwrap().collect().await.unwrap();
+ let rows = batches
+ .iter()
+ .flat_map(|b| {
+ (0..b.num_rows()).map(|r| {
+ (0..b.num_columns())
+ .map(|c| {
+ ScalarValue::try_from_array(b.column(c), r)
+ .unwrap()
+ .to_string()
+ })
+ .collect::<Vec<_>>()
+ })
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ rows,
+ vec![
+ vec!["1", "0", "a", "78790000", "string", "2", "12"],
+ vec!["2", "NULL", "NULL", "NULL", "string", "NULL", "12"]
+ ]
+ );
+}
diff --git a/crates/integrations/datafusion/tests/lateral_views.rs
b/crates/integrations/datafusion/tests/lateral_views.rs
new file mode 100644
index 00000000..38b04a67
--- /dev/null
+++ b/crates/integrations/datafusion/tests/lateral_views.rs
@@ -0,0 +1,169 @@
+// 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.
+
+use datafusion::common::ScalarValue;
+use paimon_datafusion::SQLContext;
+#[tokio::test]
+async fn
lateral_posexplode_outer_preserves_parent_rows_and_zero_based_positions() {
+ let ctx = SQLContext::new();
+ for (suffix, expected) in [
+ ("LIMIT ALL", vec![vec!["1"], vec!["2"]]),
+ ("LIMIT (1)", vec![vec!["1"]]),
+ ("OFFSET (1)", vec![vec!["2"]]),
+ ] {
+ assert_eq!(rows(&ctx,&format!("SELECT lv.col FROM (VALUES
(ARRAY[1,2])) t(xs) LATERAL VIEW explode(xs) lv {suffix}")).await,expected);
+ }
+ assert_eq!(rows(&ctx,"SELECT lv.col, row_number() OVER (ORDER BY lv.col)
rn FROM (VALUES (ARRAY[1,2])) t(xs) LATERAL VIEW explode(xs) lv QUALIFY
rn=1").await,vec![vec!["1","1"]]);
+ let batches=ctx.sql("SELECT id, lv.pos, lv.val FROM (VALUES (1,
ARRAY[10,20]), (2, ARRAY[]), (3, CAST(NULL AS INT[])), (4, ARRAY[NULL]))
t(id,xs) LATERAL VIEW posexplode_outer(xs) lv AS pos, val ORDER BY
id,pos").await.unwrap().collect().await.unwrap();
+ let rows: Vec<_> = batches
+ .iter()
+ .flat_map(|b| {
+ (0..b.num_rows()).map(|r| {
+ (0..b.num_columns())
+ .map(|c| {
+ ScalarValue::try_from_array(b.column(c), r)
+ .unwrap()
+ .to_string()
+ })
+ .collect::<Vec<_>>()
+ })
+ })
+ .collect();
+ assert_eq!(
+ rows,
+ vec![
+ vec!["1", "0", "10"],
+ vec!["1", "1", "20"],
+ vec!["2", "NULL", "NULL"],
+ vec!["3", "NULL", "NULL"],
+ vec!["4", "0", "NULL"]
+ ]
+ );
+}
+
+async fn rows(ctx: &SQLContext, sql: &str) -> Vec<Vec<String>> {
+ ctx.sql(sql)
+ .await
+ .unwrap_or_else(|e| panic!("{sql}: {e}"))
+ .collect()
+ .await
+ .unwrap_or_else(|e| panic!("{sql}: {e}"))
+ .iter()
+ .flat_map(|b| {
+ (0..b.num_rows()).map(|r| {
+ (0..b.num_columns())
+ .map(|c| {
+ ScalarValue::try_from_array(b.column(c), r)
+ .unwrap()
+ .to_string()
+ })
+ .collect()
+ })
+ })
+ .collect()
+}
+#[tokio::test]
+async fn lateral_generators_cover_maps_chaining_filters_and_set_operations() {
+ let ctx = SQLContext::new();
+ assert_eq!(rows(&ctx,"SELECT lv.pos,lv.key,lv.value FROM (SELECT
map(ARRAY['a','b'], ARRAY[10,20]) AS m) t LATERAL VIEW posexplode(m) lv ORDER
BY lv.pos").await,vec![vec!["0","a","10"],vec!["1","b","20"]]);
+ assert_eq!(rows(&ctx,"SELECT lv.key,lv.value FROM (SELECT
map(ARRAY['a'],ARRAY[10]) AS m) t LATERAL VIEW explode(m)
lv").await,vec![vec!["a","10"]]);
+ assert_eq!(rows(&ctx,"SELECT a.x,b.y FROM (VALUES (ARRAY[1,2],ARRAY[3,4]))
t(xs,ys) LATERAL VIEW explode(xs) a AS x LATERAL VIEW explode(ys) b AS y WHERE
a.x=2 ORDER BY b.y").await,vec![vec!["2","3"],vec!["2","4"]]);
+ assert_eq!(rows(&ctx,"SELECT lv.x FROM (VALUES (ARRAY[1,2])) t(xs) LATERAL
VIEW explode(xs) lv AS x UNION ALL SELECT 3 ORDER BY
x").await,vec![vec!["1"],vec!["2"],vec!["3"]]);
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT lv.pos,lv.col FROM (VALUES (ARRAY[])) t(xs) LATERAL VIEW
posexplode(xs) lv"
+ )
+ .await,
+ Vec::<Vec<String>>::new()
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT lv.col FROM (VALUES (ARRAY[])) t(xs) LATERAL VIEW OUTER
explode(xs) lv"
+ )
+ .await,
+ vec![vec!["NULL"]]
+ );
+ assert_eq!(rows(&ctx,"SELECT \"L V\".\"Val X\" FROM (VALUES (ARRAY[7]))
t(xs) LATERAL VIEW explode(xs) \"L V\" AS \"Val X\"").await,vec![vec!["7"]]);
+}
+#[tokio::test]
+async fn lateral_explode_decodes_dictionary_collections_and_value_nulls() {
+ use datafusion::arrow::{
+ array::{Array, ArrayRef, DictionaryArray, Int32Array, Int8Array,
ListArray, RecordBatch},
+ datatypes::{Field, Int32Type, Int8Type, Schema},
+ };
+ use std::sync::Arc;
+ let values = ListArray::from_iter_primitive::<Int32Type, _, _>([
+ Some(vec![Some(10), Some(20)]),
+ None,
+ Some(vec![]),
+ ]);
+ let dict = Arc::new(
+ DictionaryArray::<Int8Type>::try_new(
+ Int8Array::from(vec![Some(0), Some(1), None, Some(2)]),
+ Arc::new(values),
+ )
+ .unwrap(),
+ );
+ let batch = RecordBatch::try_new(
+ Arc::new(Schema::new(vec![
+ Field::new("id", datafusion::arrow::datatypes::DataType::Int32,
false),
+ Field::new("xs", dict.data_type().clone(), true),
+ ])),
+ vec![
+ Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as ArrayRef,
+ dict,
+ ],
+ )
+ .unwrap();
+ let ctx = SQLContext::new();
+ ctx.ctx().register_batch("dict", batch).unwrap();
+ assert_eq!(rows(&ctx,"SELECT id,lv.pos,lv.col FROM dict LATERAL VIEW
posexplode_outer(xs) lv ORDER BY
id,lv.pos").await,vec![vec!["1","0","10"],vec!["1","1","20"],vec!["2","NULL","NULL"],vec!["3","NULL","NULL"],vec!["4","NULL","NULL"]]);
+}
+
+#[tokio::test]
+async fn
lateral_expansion_preserves_empty_parents_joins_and_dependent_generators() {
+ let ctx = SQLContext::new();
+ assert_eq!(rows(&ctx,"SELECT lv.col FROM (VALUES (ARRAY[1,2])) t(xs)
LATERAL VIEW explode(xs) 'lv' LIMIT (1)").await,vec![vec!["1"]]);
+ assert_eq!(rows(&ctx,"SELECT lv.col, row_number() OVER () AS rn FROM
(VALUES (ARRAY[1])) t(xs) LATERAL VIEW explode(xs) lv QUALIFY E'a' = 'a' AND
rn=1").await,vec![vec!["1","1"]]);
+ let mut union_rows = rows(&ctx,"SELECT a.\"limit\" AS x FROM (VALUES
(ARRAY[1])) t(xs) LATERAL VIEW explode(xs) a limit UNION ALL SELECT b.col FROM
(VALUES (ARRAY[2])) t(xs) LATERAL VIEW explode(xs) b LIMIT (2)").await;
+ union_rows.sort();
+ assert_eq!(union_rows, vec![vec!["1"], vec!["2"]]);
+ for (table_alias, column_alias) in [("limit", "col"), ("order", "by"),
("fetch", "first")] {
+ let sql = format!(
+ r#"SELECT "{table_alias}"."{column_alias}" AS x FROM (VALUES
(ARRAY[1])) t(xs) LATERAL VIEW explode(xs) {table_alias} {column_alias} UNION
ALL SELECT b.col FROM (VALUES (ARRAY[2])) t(xs) LATERAL VIEW explode(xs) b
LIMIT (2)"#
+ );
+ let mut actual = rows(&ctx, &sql).await;
+ actual.sort();
+ assert_eq!(actual, vec![vec!["1"], vec!["2"]], "{sql}");
+ }
+ assert_eq!(rows(&ctx,"SELECT COUNT(*) FROM (SELECT ARRAY[1] xs WHERE
FALSE) t LATERAL VIEW explode_outer(xs) lv").await,vec![vec!["0"]]);
+ assert_eq!(rows(&ctx,"SELECT a.id,b.id,lv.col FROM (VALUES (1,ARRAY[7,7]))
a(id,xs) JOIN (VALUES (1)) b(id) ON a.id=b.id LATERAL VIEW explode(a.xs)
lv").await,vec![vec!["1","1","7"],vec!["1","1","7"]]);
+ assert_eq!(rows(&ctx,"SELECT b.p,b.v FROM (SELECT
ARRAY[ARRAY[1,2],ARRAY[3]] items) t LATERAL VIEW explode(items) a AS xs LATERAL
VIEW posexplode(xs) b AS
p,v").await,vec![vec!["0","1"],vec!["1","2"],vec!["0","3"]]);
+ for sql in [
+ "SELECT lv.pos,lv.key,lv.value FROM (SELECT CASE WHEN FALSE THEN
map(ARRAY['a'],ARRAY[1]) ELSE NULL END m) t LATERAL VIEW posexplode_outer(m)
lv",
+ "SELECT lv.pos,lv.key,lv.value FROM (SELECT map(CAST(ARRAY[] AS
VARCHAR[]),CAST(ARRAY[] AS INT[])) m) t LATERAL VIEW posexplode_outer(m) lv",
+ ] {assert_eq!(rows(&ctx,sql).await,vec![vec!["NULL","NULL","NULL"]]);}
+ for sql in [
+ "SELECT * FROM (SELECT ARRAY[1] xs) t LATERAL VIEW posexplode(xs) lv
AS wrong",
+ "SELECT * FROM (SELECT 1 xs) t LATERAL VIEW explode(xs) lv",
+ "SELECT * FROM (SELECT ARRAY[1] xs) t LATERAL VIEW
unsupported_generator(xs) lv",
+ ] {
+ assert!(ctx.sql(sql).await.is_err(), "{sql}");
+ }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 63c647d8..9cd6d1ff 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -2005,6 +2005,31 @@ Only the required columns are read, reducing I/O:
SELECT name FROM paimon.my_db.users;
```
+### Lateral collection expansion
+
+SQLContext supports `LATERAL VIEW explode`, `posexplode`,
+`explode_outer`, and `posexplode_outer` for arrays and maps. The
+`LATERAL VIEW OUTER` spelling also preserves empty/NULL collections.
+
+```sql
+SELECT t.id, expanded.pos, expanded.value
+FROM events t
+LATERAL VIEW posexplode_outer(t.items) expanded AS pos, value;
+```
+
+Positions are zero-based INT values. Array defaults are `col`, or
+`pos, col`; map defaults are `key, value`, or `pos, key, value`.
+An explicit AS list must have the matching number of column names. A NULL array
+element remains an element with its position. Outer expansion of an empty or
+NULL collection emits one row with NULL positions and values; ordinary
+expansion emits no rows. Empty parent inputs emit no rows in either mode.
+
+Multiple lateral views can reference columns produced by earlier views.
+Qualified/quoted aliases, joins, filters, subqueries and set operations retain
+their normal SQL behavior. Use one FROM relation with explicit joins instead
+of comma-separated FROM items. Unsupported generators and modifiers report
+planning errors.
+
### Filter Pushdown
The following filter predicates are pushed down to the Paimon storage layer: