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 4a2437d8 feat(datafusion): extend aggregate, JSON and SQL dialect 
compatibility (#1304)
4a2437d8 is described below

commit 4a2437d808f0b45dee961c5062cf6c63df245c6b
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 13:21:55 2026 +0800

    feat(datafusion): extend aggregate, JSON and SQL dialect compatibility 
(#1304)
---
 .../datafusion/src/expression_compat.rs            | 362 ++++++++++++
 .../datafusion/src/extended_describe.rs            | 157 +++++
 crates/integrations/datafusion/src/json_output.rs  | 341 +++++++++++
 crates/integrations/datafusion/src/lib.rs          |   5 +
 crates/integrations/datafusion/src/scalar_extra.rs | 405 +++++++++++++
 .../datafusion/src/selection_aggregate.rs          | 234 ++++++++
 crates/integrations/datafusion/src/sql_context.rs  | 134 ++++-
 crates/integrations/datafusion/src/sql_function.rs |   4 +-
 .../datafusion/src/variant_functions.rs            |   2 +-
 .../datafusion/tests/remaining_compat.rs           | 635 +++++++++++++++++++++
 crates/paimon/src/io/cache/reader.rs               |  13 +-
 docs/src/sql.md                                    |  88 +++
 12 files changed, 2367 insertions(+), 13 deletions(-)

diff --git a/crates/integrations/datafusion/src/expression_compat.rs 
b/crates/integrations/datafusion/src/expression_compat.rs
new file mode 100644
index 00000000..142c82c7
--- /dev/null
+++ b/crates/integrations/datafusion/src/expression_compat.rs
@@ -0,0 +1,362 @@
+// 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::{DataFusionError, Result};
+use datafusion::execution::SessionState;
+use datafusion::sql::sqlparser::ast::{
+    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;
+
+pub(crate) fn is_aggregate(name: &str) -> bool {
+    matches!(
+        name,
+        "count_if"
+            | "any"
+            | "any_value"
+            | "first"
+            | "approx_count_distinct"
+            | "max_by"
+            | "min_by"
+            | "arg_max"
+            | "collect_list"
+            | "listagg"
+    )
+}
+fn error(message: impl Into<String>) -> DataFusionError {
+    DataFusionError::Plan(message.into())
+}
+fn expression(sql: &str) -> Result<Expr> {
+    Parser::new(&GenericDialect {})
+        .try_with_sql(sql)
+        .and_then(|mut p| p.parse_expr())
+        .map_err(|e| error(e.to_string()))
+}
+fn arguments(call: &Function) -> Result<Vec<Expr>> {
+    if !matches!(call.parameters, FunctionArguments::None) || 
call.uses_odbc_syntax {
+        return Err(error(
+            "Compatibility aggregates require ordinary positional arguments",
+        ));
+    }
+    let FunctionArguments::List(args) = &call.args else {
+        return Err(error("Expected positional arguments"));
+    };
+    args.args
+        .iter()
+        .map(|a| match a {
+            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Ok(e.clone()),
+            _ => Err(error("Expected positional expression arguments")),
+        })
+        .collect()
+}
+fn set_args(call: &mut Function, args: Vec<Expr>) {
+    if let FunctionArguments::List(list) = &mut call.args {
+        list.args = args
+            .into_iter()
+            .map(|e| FunctionArg::Unnamed(FunctionArgExpr::Expr(e)))
+            .collect();
+    }
+}
+fn lower_aggregate(call: &Function, name: &str) -> Result<Expr> {
+    let args = arguments(call)?;
+    let mut lowered = call.clone();
+    if !call.within_group.is_empty() && name != "listagg" {
+        return Err(error(format!("{name} does not accept WITHIN GROUP")));
+    }
+    let list = match &call.args {
+        FunctionArguments::List(list) => list,
+        _ => unreachable!(),
+    };
+    if list.clauses.iter().any(|clause| {
+        !matches!(
+            clause,
+            FunctionArgumentClause::OrderBy(_) | 
FunctionArgumentClause::IgnoreOrRespectNulls(_)
+        )
+    }) {
+        return Err(error(format!("Unsupported {name} argument modifier")));
+    }
+    let arity = match name {
+        "first" | "any_value" | "approx_count_distinct" | "listagg" => 1..=2,
+        "max_by" | "min_by" | "arg_max" => 2..=2,
+        _ => 1..=1,
+    };
+    if !arity.contains(&args.len()) {
+        return Err(error(format!(
+            "{name} expects {} to {} arguments",
+            arity.start(),
+            arity.end()
+        )));
+    }
+    match name {
+        "count_if" => {
+            lowered.name = ObjectName::from(vec![Ident::new("count")]);
+            set_args(
+                &mut lowered,
+                vec![expression(&format!(
+                    "CASE WHEN ({}) THEN 1 ELSE NULL END",
+                    args[0]
+                ))?],
+            );
+        }
+        "any" => {
+            lowered.name = ObjectName::from(vec![Ident::new("bool_or")]);
+        }
+        "first" | "any_value" => {
+            lowered.name = ObjectName::from(vec![Ident::new("first_value")]);
+            if let Some(flag) = args.get(1) {
+                let Expr::Value(value) = flag else {
+                    return Err(error(format!(
+                        "{name} ignoreNulls must be a boolean literal"
+                    )));
+                };
+                let Value::Boolean(ignore) = value.value else {
+                    return Err(error(format!(
+                        "{name} ignoreNulls must be a boolean literal"
+                    )));
+                };
+                if lowered.null_treatment.is_some()
+                    || list
+                        .clauses
+                        .iter()
+                        .any(|c| matches!(c, 
FunctionArgumentClause::IgnoreOrRespectNulls(_)))
+                {
+                    return Err(error("Specify NULL handling only once"));
+                }
+                lowered.null_treatment = Some(if ignore {
+                    NullTreatment::IgnoreNulls
+                } else {
+                    NullTreatment::RespectNulls
+                });
+            }
+            set_args(&mut lowered, vec![args[0].clone()]);
+        }
+        "approx_count_distinct" => {
+            if let Some(rsd) = args.get(1) {
+                let Expr::Value(value) = rsd else {
+                    return Err(error("relativeSD must be a numeric literal"));
+                };
+                let Value::Number(value, _) = &value.value else {
+                    return Err(error("relativeSD must be a numeric literal"));
+                };
+                let rsd = value
+                    .parse::<f64>()
+                    .map_err(|_| error("Invalid relativeSD"))?;
+                // Native HLL uses 2^14 registers, with relative standard 
error 1.04/sqrt(m).
+                if !rsd.is_finite() || !(0.008125..=0.39).contains(&rsd) {
+                    return Err(error(
+                        "relativeSD must be between 0.008125 and 0.39 for the 
native HLL precision",
+                    ));
+                }
+            }
+            lowered.name = 
ObjectName::from(vec![Ident::new("approx_distinct")]);
+            set_args(&mut lowered, vec![args[0].clone()]);
+            return expression(&format!("CAST({} AS BIGINT)", 
Expr::Function(lowered)));
+        }
+        "max_by" | "min_by" | "arg_max" => {
+            if call.over.is_some()
+                || call.null_treatment.is_some()
+                || !list.clauses.is_empty()
+                || list.duplicate_treatment == 
Some(DuplicateTreatment::Distinct)
+            {
+                return Err(error(format!(
+                    "{name} does not support OVER, DISTINCT or additional 
ordering/NULL modifiers"
+                )));
+            }
+            lowered.name = 
ObjectName::from(vec![Ident::new(format!("__paimon_{name}"))]);
+        }
+        "collect_list" => {
+            lowered.name = ObjectName::from(vec![Ident::new("array_agg")]);
+            if call.null_treatment == Some(NullTreatment::RespectNulls)
+                || list.clauses.iter().any(|c| {
+                    matches!(
+                        c,
+                        
FunctionArgumentClause::IgnoreOrRespectNulls(NullTreatment::RespectNulls)
+                    )
+                })
+            {
+                return Err(error("collect_list does not support RESPECT 
NULLS"));
+            }
+            if let FunctionArguments::List(list) = &mut lowered.args {
+                list.clauses
+                    .retain(|c| !matches!(c, 
FunctionArgumentClause::IgnoreOrRespectNulls(_)));
+            }
+            lowered.null_treatment = Some(NullTreatment::IgnoreNulls);
+            let Expr::Function(mut coalesce) = expression("coalesce(NULL, 
ARRAY[])")? else {
+                unreachable!()
+            };
+            set_args(
+                &mut coalesce,
+                vec![Expr::Function(lowered), expression("ARRAY[]")?],
+            );
+            return Ok(Expr::Function(coalesce));
+        }
+        "listagg" => {
+            lowered.name = ObjectName::from(vec![Ident::new("string_agg")]);
+            if args.len() == 1 {
+                set_args(&mut lowered, vec![args[0].clone(), 
expression("''")?]);
+            }
+            if !lowered.within_group.is_empty() {
+                if list
+                    .clauses
+                    .iter()
+                    .any(|c| matches!(c, FunctionArgumentClause::OrderBy(_)))
+                {
+                    return Err(error("Specify LISTAGG ordering only once"));
+                }
+                let mut order = std::mem::take(&mut lowered.within_group);
+                // Ordered-set literals are values, not SELECT-list positions.
+                for key in &mut order {
+                    key.expr = Expr::Nested(Box::new(key.expr.clone()));
+                }
+                if let FunctionArguments::List(list) = &mut lowered.args {
+                    list.clauses.push(FunctionArgumentClause::OrderBy(order));
+                }
+            }
+        }
+        _ => unreachable!(),
+    }
+    Ok(Expr::Function(lowered))
+}
+
+struct Rewriter<'a> {
+    state: &'a SessionState,
+    changed: bool,
+    projections: Vec<Vec<(usize, Expr)>>,
+}
+impl VisitorMut for Rewriter<'_> {
+    type Break = DataFusionError;
+    fn pre_visit_select(&mut self, select: &mut Select) -> 
ControlFlow<Self::Break> {
+        self.projections.push(
+            select
+                .projection
+                .iter()
+                .enumerate()
+                .filter_map(|(i, item)| match item {
+                    SelectItem::UnnamedExpr(expr) => Some((i, expr.clone())),
+                    _ => None,
+                })
+                .collect(),
+        );
+        ControlFlow::Continue(())
+    }
+    fn post_visit_select(&mut self, select: &mut Select) -> 
ControlFlow<Self::Break> {
+        for (index, original) in self.projections.pop().unwrap() {
+            if let SelectItem::UnnamedExpr(current) = 
&select.projection[index] {
+                if current != &original {
+                    select.projection[index] = SelectItem::ExprWithAlias {
+                        expr: current.clone(),
+                        alias: Ident::with_quote('"', original.to_string()),
+                    };
+                }
+            }
+        }
+        ControlFlow::Continue(())
+    }
+    fn post_visit_expr(&mut self, node: &mut Expr) -> ControlFlow<Self::Break> 
{
+        let replacement = (|| -> Result<Option<Expr>> {
+            if let Expr::Function(call) = node {
+                if call.name.0.len() == 1 {
+                    if let Some(id) = call.name.0[0].as_ident() {
+                        let name = if id.quote_style.is_some() {
+                            id.value.clone()
+                        } else {
+                            id.value.to_ascii_lowercase()
+                        };
+                        let registered = 
self.state.scalar_functions().contains_key(&name)
+                            || 
self.state.aggregate_functions().contains_key(&name)
+                            || 
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);
+                        }
+                    }
+                }
+            }
+            let (negated, any, input, pattern, escape, insensitive) = match 
node {
+                Expr::Like {
+                    negated,
+                    any,
+                    expr,
+                    pattern,
+                    escape_char: Some(escape),
+                } => (*negated, *any, expr, pattern, escape, false),
+                Expr::ILike {
+                    negated,
+                    any,
+                    expr,
+                    pattern,
+                    escape_char: Some(escape),
+                } => (*negated, *any, expr, pattern, escape, true),
+                _ => return Ok(None),
+            };
+            let Value::SingleQuotedString(escape) = &escape.value else {
+                return Err(error(
+                    "LIKE ESCAPE must be a single-character string literal",
+                ));
+            };
+            if escape.chars().count() != 1 {
+                return Err(error("LIKE ESCAPE must contain exactly one 
character"));
+            }
+            if escape == "\\" {
+                return Ok(None);
+            }
+            if any {
+                return Err(error("LIKE ANY with a custom escape is not 
supported"));
+            }
+            let mut replacement =
+                
expression(&format!("__paimon_like(NULL,NULL,NULL,{insensitive})"))?;
+            if let Expr::Function(call) = &mut replacement {
+                set_args(
+                    call,
+                    vec![
+                        (**input).clone(),
+                        (**pattern).clone(),
+                        expression(&format!("'{}'", escape.replace('\'', 
"''")))?,
+                        expression(if insensitive { "TRUE" } else { "FALSE" 
})?,
+                    ],
+                );
+            }
+            if negated {
+                replacement = expression(&format!("NOT ({replacement})"))?;
+            }
+            Ok(Some(replacement))
+        })();
+        match replacement {
+            Ok(Some(replacement)) => {
+                *node = replacement;
+                self.changed = true;
+                ControlFlow::Continue(())
+            }
+            Ok(None) => ControlFlow::Continue(()),
+            Err(error) => ControlFlow::Break(error),
+        }
+    }
+}
+pub(crate) fn rewrite(statement: &mut Statement, state: &SessionState) -> 
Result<bool> {
+    let mut rewriter = Rewriter {
+        state,
+        changed: false,
+        projections: Vec::new(),
+    };
+    match statement.visit(&mut rewriter) {
+        ControlFlow::Break(error) => Err(error),
+        _ => Ok(rewriter.changed),
+    }
+}
diff --git a/crates/integrations/datafusion/src/extended_describe.rs 
b/crates/integrations/datafusion/src/extended_describe.rs
new file mode 100644
index 00000000..fb658d9e
--- /dev/null
+++ b/crates/integrations/datafusion/src/extended_describe.rs
@@ -0,0 +1,157 @@
+// 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 crate::SQLContext;
+use datafusion::arrow::{
+    array::StringArray,
+    datatypes::{DataType, Field, Schema},
+    record_batch::RecordBatch,
+};
+use datafusion::common::{DataFusionError, Result};
+use datafusion::prelude::DataFrame;
+use datafusion::sql::sqlparser::{
+    ast::{DescribeAlias, HiveDescribeFormat, ObjectName, Statement},
+    dialect::GenericDialect,
+    keywords::Keyword,
+    parser::Parser,
+    tokenizer::Token,
+};
+use std::{collections::BTreeMap, sync::Arc};
+
+pub(crate) fn parse_describe(sql: &str) -> Result<Option<Statement>> {
+    let mut parser = Parser::new(&GenericDialect {})
+        .try_with_sql(sql)
+        .map_err(|e| DataFusionError::Plan(e.to_string()))?;
+    if !(parser.parse_keyword(Keyword::DESCRIBE) || 
parser.parse_keyword(Keyword::DESC)) {
+        return Ok(None);
+    }
+    let _ = parser.parse_keyword(Keyword::TABLE);
+    let format = if parser.parse_keyword(Keyword::EXTENDED) {
+        HiveDescribeFormat::Extended
+    } else if parser.parse_keyword(Keyword::FORMATTED) {
+        HiveDescribeFormat::Formatted
+    } else {
+        return Ok(None);
+    };
+    let _ = parser.parse_keyword(Keyword::TABLE);
+    let table_name = parser
+        .parse_object_name(false)
+        .map_err(|e| DataFusionError::Plan(e.to_string()))?;
+    let _ = parser.consume_token(&Token::SemiColon);
+    if parser.peek_token().token != Token::EOF {
+        return Err(DataFusionError::Plan(
+            "Expected exactly one DESCRIBE statement".into(),
+        ));
+    }
+    Ok(Some(Statement::ExplainTable {
+        describe_alias: DescribeAlias::Describe,
+        hive_format: Some(format),
+        has_table_keyword: true,
+        table_name,
+    }))
+}
+pub(crate) async fn describe(ctx: &SQLContext, name: &ObjectName) -> 
Result<DataFrame> {
+    let mut name = name.clone();
+    for part in &mut name.0 {
+        if let 
datafusion::sql::sqlparser::ast::ObjectNamePart::Identifier(ident) = part {
+            ident.value = crate::sql_context::normalize_schema_identifier(
+                ident,
+                ctx.ctx().enable_ident_normalization(),
+            );
+        }
+    }
+    let native = format!("DESCRIBE {name}");
+    if ctx.temp_table_for(&name).await?.is_some() {
+        return ctx.ctx().sql(&native).await;
+    }
+    let Ok((catalog, catalog_name, id)) = ctx.resolve_catalog_and_table(&name) 
else {
+        return ctx.ctx().sql(&native).await;
+    };
+    let table = match catalog.load_table(&id).await {
+        Ok(paimon::catalog::LoadedTable::Paimon(table)) => table,
+        Ok(_) => return ctx.ctx().sql(&native).await,
+        Err(paimon::Error::TableNotExist { .. }) => return 
ctx.ctx().sql(&native).await,
+        Err(error) => return Err(crate::to_datafusion_error(error)),
+    };
+    let mut names = Vec::new();
+    let mut types = Vec::new();
+    let mut comments = Vec::new();
+    for field in table.schema().fields() {
+        names.push(field.name().to_string());
+        types.push(field.data_type().to_string());
+        comments.push(field.description().unwrap_or("").to_string());
+    }
+    let properties = table
+        .schema()
+        .options()
+        .iter()
+        .map(|(key, value)| {
+            let normalized = key.to_ascii_lowercase().replace('_', "-");
+            let sensitive = ["access-key", "secret", "password", "token", 
"credential"]
+                .iter()
+                .any(|part| normalized.contains(part));
+            (
+                key.clone(),
+                if sensitive {
+                    "<redacted>".to_string()
+                } else {
+                    value.clone()
+                },
+            )
+        })
+        .collect::<BTreeMap<_, _>>();
+    let properties =
+        serde_json::to_string(&properties).map_err(|e| 
DataFusionError::External(Box::new(e)))?;
+    for (key, value) in [
+        ("# Catalog", catalog_name),
+        ("# Database", id.database().to_string()),
+        (
+            "# Table",
+            id.table_name().map_err(crate::to_datafusion_error)?,
+        ),
+        ("# Type", "PAIMON".to_string()),
+        ("# Schema ID", table.schema().id().to_string()),
+        ("# Location", table.location().to_string()),
+        (
+            "# Comment",
+            table.schema().comment().unwrap_or("").to_string(),
+        ),
+        (
+            "# Partition Keys",
+            table.schema().partition_keys().join(","),
+        ),
+        ("# Primary Keys", table.schema().primary_keys().join(",")),
+        ("# Properties", properties),
+    ] {
+        names.push(key.to_string());
+        types.push(value);
+        comments.push(String::new());
+    }
+    let batch = RecordBatch::try_new(
+        Arc::new(Schema::new(vec![
+            Field::new("column_name", DataType::Utf8, false),
+            Field::new("data_type", DataType::Utf8, false),
+            Field::new("comment", DataType::Utf8, false),
+        ])),
+        vec![
+            Arc::new(StringArray::from(names)),
+            Arc::new(StringArray::from(types)),
+            Arc::new(StringArray::from(comments)),
+        ],
+    )?;
+    ctx.ctx().read_batch(batch)
+}
diff --git a/crates/integrations/datafusion/src/json_output.rs 
b/crates/integrations/datafusion/src/json_output.rs
new file mode 100644
index 00000000..c7250790
--- /dev/null
+++ b/crates/integrations/datafusion/src/json_output.rs
@@ -0,0 +1,341 @@
+// 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 crate::variant_functions::{variant_arrow_type, variant_children};
+use base64::Engine;
+use datafusion::arrow::array::{
+    Array, ArrayRef, BinaryArray, Float64Array, ListArray, MapArray, 
StringArray, StringBuilder,
+    StructArray,
+};
+use datafusion::arrow::compute::cast;
+use datafusion::arrow::datatypes::DataType;
+use datafusion::arrow::util::display::array_value_to_string;
+use datafusion::common::{
+    config::ConfigOptions, tree_node::Transformed, DFSchema, DataFusionError, 
Result, ScalarValue,
+};
+use datafusion::logical_expr::{
+    expr::Cast, expr_rewriter::FunctionRewrite, registry::FunctionRegistry, 
ColumnarValue, Expr,
+    ExprSchemable, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, 
Volatility,
+};
+use datafusion::prelude::SessionContext;
+use paimon::variant::{VariantKind, VariantRef};
+use std::{collections::BTreeMap, sync::Arc};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum Kind {
+    Json,
+    Object,
+    Cast,
+    TryCast,
+}
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct Output {
+    kind: Kind,
+    signature: Signature,
+}
+fn error(message: impl Into<String>) -> DataFusionError {
+    DataFusionError::Execution(message.into())
+}
+fn udf(kind: Kind) -> ScalarUDF {
+    ScalarUDF::from(Output {
+        kind,
+        signature: Signature::user_defined(Volatility::Immutable),
+    })
+}
+pub(crate) fn register(ctx: &mut SessionContext) {
+    SessionContext::register_udf(ctx, udf(Kind::Json));
+    SessionContext::register_udf(ctx, udf(Kind::Object));
+    let cast = Arc::new(udf(Kind::Cast));
+    let try_cast = Arc::new(udf(Kind::TryCast));
+    SessionContext::register_udf(ctx, (*cast).clone());
+    SessionContext::register_udf(ctx, (*try_cast).clone());
+    ctx.register_function_rewrite(Arc::new(VariantStringCast { cast, try_cast 
}))
+        .expect("register Variant CAST rewrite");
+}
+#[derive(Debug)]
+struct VariantStringCast {
+    cast: Arc<ScalarUDF>,
+    try_cast: Arc<ScalarUDF>,
+}
+impl FunctionRewrite for VariantStringCast {
+    fn name(&self) -> &str {
+        "paimon_variant_string_cast"
+    }
+    fn rewrite(
+        &self,
+        expr: Expr,
+        schema: &DFSchema,
+        _: &ConfigOptions,
+    ) -> Result<Transformed<Expr>> {
+        let (input, target, try_cast) = match &expr {
+            Expr::Cast(c) => (c.expr.as_ref(), &c.field, false),
+            Expr::TryCast(c) => (c.expr.as_ref(), &c.field, true),
+            _ => return Ok(Transformed::no(expr)),
+        };
+        if !matches!(
+            target.data_type(),
+            DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8
+        ) {
+            return Ok(Transformed::no(expr));
+        }
+        let input_type = input.get_type(schema)?;
+        let decoded = match &input_type {
+            DataType::Dictionary(_, inner) => inner.as_ref(),
+            other => other,
+        };
+        if decoded != &variant_arrow_type() {
+            return Ok(Transformed::no(expr));
+        }
+        let func = if try_cast { &self.try_cast } else { &self.cast };
+        let output = func.call(vec![input.clone()]);
+        Ok(Transformed::yes(Expr::Cast(Cast::new_from_field(
+            Box::new(output),
+            Arc::clone(target),
+        ))))
+    }
+}
+impl ScalarUDFImpl for Output {
+    fn name(&self) -> &str {
+        match self.kind {
+            Kind::Json => "to_json",
+            Kind::Object => "json_object",
+            Kind::Cast => "__paimon_variant_string",
+            Kind::TryCast => "__paimon_try_variant_string",
+        }
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+    fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+        if self.kind == Kind::Object {
+            if !types.len().is_multiple_of(2) {
+                return Err(DataFusionError::Plan(
+                    "json_object requires key/value pairs".into(),
+                ));
+            }
+            return Ok(types
+                .iter()
+                .enumerate()
+                .map(|(i, t)| {
+                    if i % 2 == 0 {
+                        DataType::Utf8
+                    } else {
+                        t.clone()
+                    }
+                })
+                .collect());
+        }
+        if types.len() != 1 {
+            return Err(DataFusionError::Plan(format!(
+                "{} expects one argument",
+                self.name()
+            )));
+        }
+        Ok(types.to_vec())
+    }
+    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Utf8)
+    }
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?
+            .iter()
+            .map(decoded)
+            .collect::<Result<Vec<_>>>()?;
+        let len = arrays.first().map_or(args.number_rows.max(1), |a| a.len());
+        let mut output = StringBuilder::new();
+        for row in 0..len {
+            if self.kind == Kind::Object {
+                let mut fields = BTreeMap::new();
+                for pair in arrays.as_chunks::<2>().0 {
+                    if pair[0].is_null(row) {
+                        return Err(error("json_object keys cannot be NULL"));
+                    }
+                    let key = pair[0]
+                        .as_any()
+                        .downcast_ref::<StringArray>()
+                        .ok_or_else(|| error("json_object key must be a 
string"))?
+                        .value(row);
+                    fields.insert(key.to_string(), serialize(pair[1].as_ref(), 
row)?);
+                }
+                output.append_value(object(fields)?);
+            } else if arrays[0].data_type() == &DataType::Null || 
arrays[0].is_null(row) {
+                output.append_null();
+            } else if self.kind == Kind::Json {
+                output.append_value(serialize(arrays[0].as_ref(), row)?);
+            } else {
+                let input = &arrays[0];
+                let value = (|| {
+                    let (values, metadata) = variant_children(input.as_ref())?
+                        .ok_or_else(|| error("Expected Variant input"))?;
+                    let variant = VariantRef::new(values.value(row), 
metadata.value(row), 0)
+                        .map_err(crate::to_datafusion_error)?;
+                    if variant.kind().map_err(crate::to_datafusion_error)? == 
VariantKind::Null {
+                        return Ok(None);
+                    }
+                    crate::variant_functions::cast_to_string(variant).map(Some)
+                })();
+                match value {
+                    Ok(Some(value)) => output.append_value(value),
+                    Ok(None) => output.append_null(),
+                    Err(_) if self.kind == Kind::TryCast => 
output.append_null(),
+                    Err(e) => return Err(e),
+                }
+            }
+        }
+        let output: ArrayRef = Arc::new(output.finish());
+        if args
+            .args
+            .iter()
+            .all(|v| matches!(v, ColumnarValue::Scalar(_)))
+        {
+            Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+                output.as_ref(),
+                0,
+            )?))
+        } else {
+            Ok(ColumnarValue::Array(output))
+        }
+    }
+}
+fn decoded(input: &ArrayRef) -> Result<ArrayRef> {
+    match input.data_type() {
+        DataType::Dictionary(_, inner) => Ok(cast(input, inner)?),
+        _ => Ok(Arc::clone(input)),
+    }
+}
+fn quoted(input: &str) -> Result<String> {
+    serde_json::to_string(input).map_err(|e| error(e.to_string()))
+}
+fn object(fields: BTreeMap<String, String>) -> Result<String> {
+    fields
+        .into_iter()
+        .map(|(key, value)| Ok(format!("{}:{value}", quoted(&key)?)))
+        .collect::<Result<Vec<_>>>()
+        .map(|fields| format!("{{{}}}", fields.join(",")))
+}
+fn serialize(input: &dyn Array, row: usize) -> Result<String> {
+    if input.data_type() == &DataType::Null || input.is_null(row) {
+        return Ok("null".into());
+    }
+    if input.data_type() == &variant_arrow_type() {
+        let (values, metadata) =
+            variant_children(input)?.ok_or_else(|| error("Expected Variant 
input"))?;
+        return VariantRef::new(values.value(row), metadata.value(row), 0)
+            .and_then(|v| v.to_json())
+            .map_err(crate::to_datafusion_error);
+    }
+    match input.data_type() {
+        DataType::Dictionary(_, inner) => serialize(cast(&input.slice(row, 1), 
inner)?.as_ref(), 0),
+        DataType::Struct(fields) => {
+            let array = input.as_any().downcast_ref::<StructArray>().unwrap();
+            let mut output = BTreeMap::new();
+            for (field, column) in fields.iter().zip(array.columns()) {
+                output.insert(field.name().clone(), serialize(column.as_ref(), 
row)?);
+            }
+            object(output)
+        }
+        DataType::Map(_, _) => {
+            let entries = input
+                .as_any()
+                .downcast_ref::<MapArray>()
+                .unwrap()
+                .value(row);
+            let mut output = BTreeMap::new();
+            let key_nulls = entries.column(0).logical_nulls();
+            for index in 0..entries.len() {
+                if key_nulls.as_ref().is_some_and(|nulls| 
nulls.is_null(index)) {
+                    return Err(error("JSON map keys cannot be NULL"));
+                }
+                let key = array_value_to_string(entries.column(0).as_ref(), 
index)?;
+                output.insert(key, serialize(entries.column(1).as_ref(), 
index)?);
+            }
+            object(output)
+        }
+        DataType::List(_)
+        | DataType::LargeList(_)
+        | DataType::FixedSizeList(_, _)
+        | DataType::ListView(_)
+        | DataType::LargeListView(_) => {
+            let field = match input.data_type() {
+                DataType::List(f)
+                | DataType::LargeList(f)
+                | DataType::FixedSizeList(f, _)
+                | DataType::ListView(f)
+                | DataType::LargeListView(f) => Arc::clone(f),
+                _ => unreachable!(),
+            };
+            let array = cast(&input.slice(row, 1), &DataType::List(field))?;
+            let values = 
array.as_any().downcast_ref::<ListArray>().unwrap().value(0);
+            (0..values.len())
+                .map(|i| serialize(values.as_ref(), i))
+                .collect::<Result<Vec<_>>>()
+                .map(|values| format!("[{}]", values.join(",")))
+        }
+        DataType::Binary
+        | DataType::BinaryView
+        | DataType::LargeBinary
+        | DataType::FixedSizeBinary(_) => {
+            let value = cast(&input.slice(row, 1), &DataType::Binary)?;
+            quoted(
+                &base64::engine::general_purpose::STANDARD.encode(
+                    value
+                        .as_any()
+                        .downcast_ref::<BinaryArray>()
+                        .unwrap()
+                        .value(0),
+                ),
+            )
+        }
+        DataType::Boolean
+        | DataType::Int8
+        | DataType::Int16
+        | DataType::Int32
+        | DataType::Int64
+        | DataType::UInt8
+        | DataType::UInt16
+        | DataType::UInt32
+        | DataType::UInt64
+        | DataType::Decimal32(_, _)
+        | DataType::Decimal64(_, _)
+        | DataType::Decimal128(_, _)
+        | DataType::Decimal256(_, _) => Ok(array_value_to_string(input, row)?),
+        DataType::Float16 | DataType::Float32 | DataType::Float64 => {
+            let value = cast(&input.slice(row, 1), &DataType::Float64)?;
+            if !value
+                .as_any()
+                .downcast_ref::<Float64Array>()
+                .unwrap()
+                .value(0)
+                .is_finite()
+            {
+                return Err(error(
+                    "Non-finite values cannot be represented as JSON numbers",
+                ));
+            }
+            Ok(array_value_to_string(input, row)?)
+        }
+        DataType::Utf8
+        | DataType::LargeUtf8
+        | DataType::Utf8View
+        | DataType::Date32
+        | DataType::Date64
+        | DataType::Time32(_)
+        | DataType::Time64(_)
+        | DataType::Timestamp(_, _) => quoted(&array_value_to_string(input, 
row)?),
+        other => Err(error(format!("to_json does not support {other}"))),
+    }
+}
diff --git a/crates/integrations/datafusion/src/lib.rs 
b/crates/integrations/datafusion/src/lib.rs
index b34d0a32..19e0ec3b 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -44,6 +44,8 @@ mod catalog;
 mod compat_functions;
 mod delete;
 mod error;
+mod expression_compat;
+mod extended_describe;
 mod filter_pushdown;
 mod format_partition_analyze;
 mod format_partition_ddl;
@@ -55,6 +57,7 @@ mod full_text_search;
 mod golden_warehouse;
 mod hybrid_search;
 mod json_functions;
+mod json_output;
 mod lateral_vector_search;
 mod lateral_views;
 mod memory;
@@ -67,6 +70,8 @@ mod regex_operators;
 mod relation_planner;
 pub mod runtime;
 mod scalar_compat;
+mod scalar_extra;
+mod selection_aggregate;
 mod show_metadata;
 mod sql_context;
 mod sql_function;
diff --git a/crates/integrations/datafusion/src/scalar_extra.rs 
b/crates/integrations/datafusion/src/scalar_extra.rs
new file mode 100644
index 00000000..3fc7161f
--- /dev/null
+++ b/crates/integrations/datafusion/src/scalar_extra.rs
@@ -0,0 +1,405 @@
+// 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 chrono::{Datelike, Months, NaiveDate, NaiveDateTime, TimeZone};
+use datafusion::arrow::array::timezone::Tz;
+use datafusion::arrow::array::{
+    Array, ArrayRef, BooleanArray, BooleanBuilder, Date32Array, Int64Array, 
Int64Builder,
+    NullArray, StringArray, StringBuilder, TimestampMicrosecondArray,
+};
+use datafusion::arrow::datatypes::{DataType, TimeUnit};
+use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, 
Volatility,
+};
+use datafusion::prelude::SessionContext;
+use regex::{Regex, RegexBuilder};
+use std::{collections::HashMap, sync::Arc};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum Kind {
+    Assert,
+    Conv,
+    DateDiff,
+    ConvertTz,
+    Like,
+}
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct Extra {
+    kind: Kind,
+    signature: Signature,
+}
+fn error(message: impl Into<String>) -> DataFusionError {
+    DataFusionError::Execution(message.into())
+}
+pub(crate) fn register(ctx: &SessionContext) {
+    for kind in [
+        Kind::Assert,
+        Kind::Conv,
+        Kind::DateDiff,
+        Kind::ConvertTz,
+        Kind::Like,
+    ] {
+        ctx.register_udf(ScalarUDF::from(Extra {
+            kind,
+            signature: Signature::user_defined(Volatility::Immutable),
+        }));
+    }
+}
+fn result(args: &ScalarFunctionArgs, array: ArrayRef) -> Result<ColumnarValue> 
{
+    if args
+        .args
+        .iter()
+        .all(|a| matches!(a, ColumnarValue::Scalar(_)))
+    {
+        Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+            array.as_ref(),
+            0,
+        )?))
+    } else {
+        Ok(ColumnarValue::Array(array))
+    }
+}
+impl ScalarUDFImpl for Extra {
+    fn name(&self) -> &str {
+        match self.kind {
+            Kind::Assert => "assert_true",
+            Kind::Conv => "conv",
+            Kind::DateDiff => "date_diff",
+            Kind::ConvertTz => "convert_tz",
+            Kind::Like => "__paimon_like",
+        }
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+    fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+        Ok(match (self.kind, types.len()) {
+            (Kind::Assert, 1 | 2) => {
+                if !matches!(types[0], DataType::Boolean | DataType::Null) {
+                    return Err(DataFusionError::Plan(
+                        "assert_true requires a boolean condition".into(),
+                    ));
+                }
+                let mut out = vec![DataType::Boolean];
+                if types.len() == 2 {
+                    out.push(DataType::Utf8);
+                }
+                out
+            }
+            (Kind::Conv, 3) => vec![DataType::Utf8, DataType::Int64, 
DataType::Int64],
+            (Kind::DateDiff, 2) => vec![DataType::Date32, DataType::Date32],
+            (Kind::DateDiff, 3) => vec![
+                DataType::Utf8,
+                DataType::Timestamp(TimeUnit::Microsecond, None),
+                DataType::Timestamp(TimeUnit::Microsecond, None),
+            ],
+            (Kind::ConvertTz, 3) => {
+                if matches!(types[0], DataType::Timestamp(_, Some(_))) {
+                    return Err(DataFusionError::Plan(
+                        "convert_tz expects a timezone-less datetime".into(),
+                    ));
+                }
+                vec![DataType::Utf8; 3]
+            }
+            (Kind::Like, 4) => vec![
+                DataType::Utf8,
+                DataType::Utf8,
+                DataType::Utf8,
+                DataType::Boolean,
+            ],
+            _ => {
+                return Err(DataFusionError::Plan(format!(
+                    "Invalid {} argument count",
+                    self.name()
+                )))
+            }
+        })
+    }
+    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+        Ok(match self.kind {
+            Kind::Assert => DataType::Null,
+            Kind::Conv => DataType::Utf8,
+            Kind::DateDiff => DataType::Int64,
+            Kind::ConvertTz => DataType::Timestamp(TimeUnit::Microsecond, 
None),
+            Kind::Like => DataType::Boolean,
+        })
+    }
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+        let len = arrays[0].len();
+        let out: ArrayRef = match self.kind {
+            Kind::Assert => {
+                let condition = 
arrays[0].as_any().downcast_ref::<BooleanArray>().unwrap();
+                for row in 0..len {
+                    if condition.is_null(row) || !condition.value(row) {
+                        let message = arrays
+                            .get(1)
+                            .filter(|a| !a.is_null(row))
+                            .map(|a| 
a.as_any().downcast_ref::<StringArray>().unwrap().value(row))
+                            .unwrap_or("assertion failed");
+                        return Err(error(message));
+                    }
+                }
+                Arc::new(NullArray::new(len))
+            }
+            Kind::Conv => {
+                let input = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+                let from = 
arrays[1].as_any().downcast_ref::<Int64Array>().unwrap();
+                let to = 
arrays[2].as_any().downcast_ref::<Int64Array>().unwrap();
+                let mut output = StringBuilder::new();
+                for row in 0..len {
+                    if arrays.iter().any(|a| a.is_null(row)) {
+                        output.append_null();
+                        continue;
+                    }
+                    match conv(input.value(row), from.value(row), 
to.value(row)) {
+                        Some(v) => output.append_value(v),
+                        None => output.append_null(),
+                    }
+                }
+                Arc::new(output.finish())
+            }
+            Kind::DateDiff => {
+                let mut output = Int64Builder::new();
+                if arrays.len() == 2 {
+                    let end = 
arrays[0].as_any().downcast_ref::<Date32Array>().unwrap();
+                    let start = 
arrays[1].as_any().downcast_ref::<Date32Array>().unwrap();
+                    for row in 0..len {
+                        if end.is_null(row) || start.is_null(row) {
+                            output.append_null();
+                        } else {
+                            output.append_value(
+                                i64::from(end.value(row)) - 
i64::from(start.value(row)),
+                            );
+                        }
+                    }
+                } else {
+                    let unit = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+                    let start = arrays[1]
+                        .as_any()
+                        .downcast_ref::<TimestampMicrosecondArray>()
+                        .unwrap();
+                    let end = arrays[2]
+                        .as_any()
+                        .downcast_ref::<TimestampMicrosecondArray>()
+                        .unwrap();
+                    for row in 0..len {
+                        if arrays.iter().any(|a| a.is_null(row)) {
+                            output.append_null();
+                            continue;
+                        }
+                        output.append_value(date_diff(
+                            unit.value(row),
+                            start.value(row),
+                            end.value(row),
+                        )?);
+                    }
+                }
+                Arc::new(output.finish())
+            }
+            Kind::ConvertTz => {
+                let input = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+                let from = 
arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
+                let to = 
arrays[2].as_any().downcast_ref::<StringArray>().unwrap();
+                let values = (0..len)
+                    .map(|row| {
+                        if arrays.iter().any(|a| a.is_null(row)) {
+                            return None;
+                        }
+                        convert_tz(input.value(row), from.value(row), 
to.value(row))
+                    })
+                    .collect::<Vec<_>>();
+                Arc::new(TimestampMicrosecondArray::from(values))
+            }
+            Kind::Like => {
+                let input = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+                let pattern = 
arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
+                let escape = 
arrays[2].as_any().downcast_ref::<StringArray>().unwrap();
+                let insensitive = 
arrays[3].as_any().downcast_ref::<BooleanArray>().unwrap();
+                let mut cache: HashMap<(String, String, bool), Regex> = 
HashMap::new();
+                let mut output = BooleanBuilder::new();
+                for row in 0..len {
+                    if arrays.iter().any(|a| a.is_null(row)) {
+                        output.append_null();
+                        continue;
+                    }
+                    let key = (
+                        pattern.value(row).to_string(),
+                        escape.value(row).to_string(),
+                        insensitive.value(row),
+                    );
+                    if !cache.contains_key(&key) {
+                        cache.insert(key.clone(), like_regex(&key.0, &key.1, 
key.2)?);
+                    }
+                    
output.append_value(cache[&key].is_match(input.value(row)));
+                }
+                Arc::new(output.finish())
+            }
+        };
+        result(&args, out)
+    }
+}
+fn conv(input: &str, from: i64, to: i64) -> Option<String> {
+    let base = to.checked_abs()?;
+    if !(2..=36).contains(&from) || !(2..=36).contains(&base) {
+        return None;
+    }
+    let input = input.trim_start();
+    let negative = input.starts_with('-');
+    let digits = input.strip_prefix(['-', '+']).unwrap_or(input);
+    let mut bits = 0u64;
+    for c in digits.chars() {
+        let Some(d) = c.to_digit(from as u32) else {
+            break;
+        };
+        bits = bits.saturating_mul(from as u64).saturating_add(d as u64);
+    }
+    if negative {
+        bits = bits.wrapping_neg();
+    }
+    let negative = to < 0 && (bits as i64) < 0;
+    let mut number = if negative {
+        (bits as i64).unsigned_abs()
+    } else {
+        bits
+    };
+    let mut result = Vec::new();
+    loop {
+        result.push(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[(number % base as 
u64) as usize]);
+        number /= base as u64;
+        if number == 0 {
+            break;
+        }
+    }
+    if negative {
+        result.push(b'-');
+    }
+    result.reverse();
+    String::from_utf8(result).ok()
+}
+fn date_diff(unit: &str, start: i64, end: i64) -> Result<i64> {
+    let duration = i128::from(end) - i128::from(start);
+    let divisor = match unit.to_ascii_lowercase().trim_end_matches('s') {
+        "microsecond" => Some(1),
+        "millisecond" => Some(1_000),
+        "second" => Some(1_000_000),
+        "minute" => Some(60_000_000),
+        "hour" => Some(3_600_000_000),
+        "day" => Some(86_400_000_000),
+        "week" => Some(604_800_000_000),
+        _ => None,
+    };
+    if let Some(divisor) = divisor {
+        return i64::try_from(duration / divisor).map_err(|_| error("date_diff 
overflow"));
+    }
+    let start = chrono::DateTime::from_timestamp_micros(start)
+        .ok_or_else(|| error("date_diff timestamp out of range"))?
+        .naive_utc();
+    let end = chrono::DateTime::from_timestamp_micros(end)
+        .ok_or_else(|| error("date_diff timestamp out of range"))?
+        .naive_utc();
+    let (earlier, later, sign) = if start <= end {
+        (start, end, 1)
+    } else {
+        (end, start, -1)
+    };
+    let mut months = (i64::from(later.year()) - i64::from(earlier.year())) * 12
+        + i64::from(later.month())
+        - i64::from(earlier.month());
+    let candidate = earlier
+        .checked_add_months(Months::new(
+            u32::try_from(months).map_err(|_| error("date_diff calendar 
overflow"))?,
+        ))
+        .ok_or_else(|| error("date_diff calendar overflow"))?;
+    if candidate > later {
+        months -= 1;
+    }
+    let months = months * sign;
+    match unit.to_ascii_lowercase().trim_end_matches('s') {
+        "month" => Ok(months),
+        "quarter" => Ok(months / 3),
+        "year" => Ok(months / 12),
+        _ => Err(error(format!("Unsupported date_diff unit: {unit}"))),
+    }
+}
+fn convert_tz(input: &str, from: &str, to: &str) -> Option<i64> {
+    let value = NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M:%S%.f")
+        .or_else(|_| NaiveDateTime::parse_from_str(input, 
"%Y-%m-%dT%H:%M:%S%.f"))
+        .ok()
+        .or_else(|| {
+            NaiveDate::parse_from_str(input, "%Y-%m-%d")
+                .ok()?
+                .and_hms_opt(0, 0, 0)
+        })?;
+    let from = timezone(from)?;
+    let to = timezone(to)?;
+    Some(
+        from.from_local_datetime(&value)
+            .single()?
+            .with_timezone(&to)
+            .naive_local()
+            .and_utc()
+            .timestamp_micros(),
+    )
+}
+fn timezone(zone: &str) -> Option<Tz> {
+    if let Some(offset) = zone.strip_prefix(['+', '-']) {
+        let digits = match offset.as_bytes() {
+            [h1, h2] => [*h1, *h2, b'0', b'0'],
+            [h1, h2, m1, m2] | [h1, h2, b':', m1, m2] => [*h1, *h2, *m1, *m2],
+            _ => return None,
+        };
+        // Arrow validates the total offset, but accepts minute fields such as 
60.
+        if !digits.iter().all(u8::is_ascii_digit)
+            || (digits[0] - b'0') * 10 + digits[1] - b'0' >= 24
+            || (digits[2] - b'0') * 10 + digits[3] - b'0' >= 60
+        {
+            return None;
+        }
+    }
+    zone.parse().ok()
+}
+fn like_regex(pattern: &str, escape: &str, insensitive: bool) -> Result<Regex> 
{
+    let mut esc = escape.chars();
+    let escape = esc.next().ok_or_else(|| error("Empty LIKE escape"))?;
+    if esc.next().is_some() {
+        return Err(error("LIKE escape must be one character"));
+    }
+    let mut chars = pattern.chars();
+    let mut regex = String::from("\\A");
+    while let Some(c) = chars.next() {
+        if c == escape {
+            let next = chars
+                .next()
+                .ok_or_else(|| error("LIKE pattern ends with its escape 
character"))?;
+            regex.push_str(&regex::escape(&next.to_string()));
+        } else {
+            match c {
+                '%' => regex.push_str(".*"),
+                '_' => regex.push('.'),
+                _ => regex.push_str(&regex::escape(&c.to_string())),
+            }
+        }
+    }
+    regex.push_str("\\z");
+    RegexBuilder::new(&regex)
+        .case_insensitive(insensitive)
+        .dot_matches_new_line(true)
+        .build()
+        .map_err(|e| error(e.to_string()))
+}
diff --git a/crates/integrations/datafusion/src/selection_aggregate.rs 
b/crates/integrations/datafusion/src/selection_aggregate.rs
new file mode 100644
index 00000000..a01deeaa
--- /dev/null
+++ b/crates/integrations/datafusion/src/selection_aggregate.rs
@@ -0,0 +1,234 @@
+// 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::{Array, ArrayRef, BooleanArray};
+use datafusion::arrow::compute::{and, filter, is_not_null, SortOptions};
+use datafusion::arrow::datatypes::{DataType, FieldRef};
+use datafusion::common::{Result, ScalarValue};
+use datafusion::functions_aggregate::first_last::first_value_udaf;
+use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs};
+use datafusion::logical_expr::utils::AggregateOrderSensitivity;
+use datafusion::logical_expr::{
+    Accumulator, AggregateUDF, AggregateUDFImpl, EmitTo, GroupsAccumulator, 
Signature, Volatility,
+};
+use datafusion::physical_expr::PhysicalSortExpr;
+use datafusion::prelude::SessionContext;
+use std::sync::Arc;
+
+// Adapt native first_value's ordering and state without evaluating either 
input twice.
+#[derive(Debug, PartialEq, Eq, Hash)]
+struct Selection {
+    name: &'static str,
+    descending: bool,
+    ignore_nulls: bool,
+    signature: Signature,
+}
+pub(crate) fn register(ctx: &SessionContext) {
+    for (name, descending, ignore_nulls) in [
+        ("__paimon_max_by", true, false),
+        ("__paimon_min_by", false, false),
+        ("__paimon_arg_max", true, true),
+    ] {
+        ctx.register_udaf(AggregateUDF::from(Selection {
+            name,
+            descending,
+            ignore_nulls,
+            signature: Signature::any(2, Volatility::Immutable),
+        }));
+    }
+}
+impl Selection {
+    fn ordering(&self, args: &AccumulatorArgs) -> [PhysicalSortExpr; 1] {
+        [PhysicalSortExpr {
+            expr: Arc::clone(&args.exprs[1]),
+            options: SortOptions {
+                descending: self.descending,
+                nulls_first: false,
+            },
+        }]
+    }
+}
+impl AggregateUDFImpl for Selection {
+    fn name(&self) -> &str {
+        self.name
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        Ok(arg_types[0].clone())
+    }
+    fn return_field(&self, fields: &[FieldRef]) -> Result<FieldRef> {
+        first_value_udaf().return_field(&fields[..1])
+    }
+    fn accumulator(&self, args: AccumulatorArgs) -> Result<Box<dyn 
Accumulator>> {
+        let ordering = self.ordering(&args);
+        let native = first_value_udaf().accumulator(AccumulatorArgs {
+            order_bys: &ordering,
+            ignore_nulls: self.ignore_nulls,
+            exprs: &args.exprs[..1],
+            expr_fields: &args.expr_fields[..1],
+            ..args
+        })?;
+        Ok(Box::new(SelectionAccumulator {
+            native,
+            ignore_null_values: self.ignore_nulls,
+        }))
+    }
+    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
+        // An empty partial group has no selected key, even if input keys are 
NOT NULL.
+        let key = Arc::new(
+            args.input_fields[1]
+                .as_ref()
+                .clone()
+                .with_name(format!("{}[key]", args.name))
+                .with_nullable(true),
+        );
+        first_value_udaf().state_fields(StateFieldsArgs {
+            ordering_fields: &[key],
+            input_fields: &args.input_fields[..1],
+            ..args
+        })
+    }
+    fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
+        let ordering = self.ordering(&args);
+        first_value_udaf().groups_accumulator_supported(AccumulatorArgs {
+            order_bys: &ordering,
+            ..args
+        })
+    }
+    fn create_groups_accumulator(
+        &self,
+        args: AccumulatorArgs,
+    ) -> Result<Box<dyn GroupsAccumulator>> {
+        let ordering = self.ordering(&args);
+        let native = 
first_value_udaf().create_groups_accumulator(AccumulatorArgs {
+            order_bys: &ordering,
+            ignore_nulls: self.ignore_nulls,
+            exprs: &args.exprs[..1],
+            expr_fields: &args.expr_fields[..1],
+            ..args
+        })?;
+        Ok(Box::new(SelectionGroupsAccumulator {
+            native,
+            ignore_null_values: self.ignore_nulls,
+        }))
+    }
+    fn order_sensitivity(&self) -> AggregateOrderSensitivity {
+        // The key is a normal argument. Native state compares it internally.
+        AggregateOrderSensitivity::Insensitive
+    }
+}
+fn eligibility(
+    values: &[ArrayRef],
+    ignore_null_values: bool,
+    opt_filter: Option<&BooleanArray>,
+) -> Result<Option<BooleanArray>> {
+    let mut mask = None;
+    for value in 
std::iter::once(&values[1]).chain(ignore_null_values.then_some(&values[0])) {
+        if value.logical_null_count() > 0 {
+            let valid = is_not_null(value.as_ref())?;
+            mask = Some(match mask {
+                Some(original) => and(&original, &valid)?,
+                None => valid,
+            });
+        }
+    }
+    if let Some(original) = opt_filter {
+        // Native grouped first_value reads filter value bits without its 
validity bitmap.
+        let valid = if original.null_count() == 0 {
+            original.clone()
+        } else {
+            BooleanArray::from(
+                original
+                    .iter()
+                    .map(|value| value.unwrap_or(false))
+                    .collect::<Vec<_>>(),
+            )
+        };
+        mask = Some(match mask {
+            Some(mask) => and(&mask, &valid)?,
+            None => valid,
+        });
+    }
+    Ok(mask)
+}
+#[derive(Debug)]
+struct SelectionAccumulator {
+    native: Box<dyn Accumulator>,
+    ignore_null_values: bool,
+}
+impl Accumulator for SelectionAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        let Some(mask) = eligibility(values, self.ignore_null_values, None)? 
else {
+            return self.native.update_batch(values);
+        };
+        let values = values
+            .iter()
+            .map(|value| filter(value.as_ref(), &mask).map_err(Into::into))
+            .collect::<Result<Vec<_>>>()?;
+        self.native.update_batch(&values)
+    }
+    fn evaluate(&mut self) -> Result<ScalarValue> {
+        self.native.evaluate()
+    }
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {
+        self.native.state()
+    }
+    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+        self.native.merge_batch(states)
+    }
+    fn size(&self) -> usize {
+        self.native.size() + std::mem::size_of::<Self>()
+    }
+}
+struct SelectionGroupsAccumulator {
+    native: Box<dyn GroupsAccumulator>,
+    ignore_null_values: bool,
+}
+impl GroupsAccumulator for SelectionGroupsAccumulator {
+    fn update_batch(
+        &mut self,
+        values: &[ArrayRef],
+        group_indices: &[usize],
+        opt_filter: Option<&BooleanArray>,
+        total_num_groups: usize,
+    ) -> Result<()> {
+        let mask = eligibility(values, self.ignore_null_values, opt_filter)?;
+        self.native
+            .update_batch(values, group_indices, mask.as_ref(), 
total_num_groups)
+    }
+    fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef> {
+        self.native.evaluate(emit_to)
+    }
+    fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
+        self.native.state(emit_to)
+    }
+    fn merge_batch(
+        &mut self,
+        values: &[ArrayRef],
+        group_indices: &[usize],
+        opt_filter: Option<&BooleanArray>,
+        total_num_groups: usize,
+    ) -> Result<()> {
+        self.native
+            .merge_batch(values, group_indices, opt_filter, total_num_groups)
+    }
+    fn size(&self) -> usize {
+        self.native.size() + std::mem::size_of::<Self>()
+    }
+}
diff --git a/crates/integrations/datafusion/src/sql_context.rs 
b/crates/integrations/datafusion/src/sql_context.rs
index b3d88315..979f6aef 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -170,11 +170,14 @@ impl SQLContextBuilder {
             state_builder = state_builder.with_runtime_env(runtime_env);
         }
         let state = state_builder.build();
-        let ctx = SessionContext::new_with_state(state);
+        let mut 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::scalar_extra::register(&ctx);
+        crate::selection_aggregate::register(&ctx);
+        crate::json_output::register(&mut ctx);
         
crate::blob_descriptor_functions::register_blob_descriptor_functions(&ctx);
         crate::variant_functions::register_variant_functions(&ctx);
         crate::json_functions::register_json_functions(&ctx);
@@ -504,7 +507,9 @@ impl SQLContext {
             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])?;
-            binary_changed || regex_changed || lateral_changed
+            let compat_changed =
+                crate::expression_compat::rewrite(&mut statements[0], 
&self.ctx.state())?;
+            binary_changed || regex_changed || lateral_changed || 
compat_changed
         };
         let sql = if changed {
             rewritten = statements[0].to_string();
@@ -513,6 +518,11 @@ impl SQLContext {
             sql
         };
         match &statements[0] {
+            Statement::ExplainTable {
+                hive_format: Some(_),
+                table_name,
+                ..
+            } => crate::extended_describe::describe(self, table_name).await,
             Statement::Comment {
                 object_type,
                 object_name,
@@ -1414,7 +1424,7 @@ impl SQLContext {
     }
 
     /// The temporary table or view `name` resolves to in queries.
-    async fn temp_table_for(
+    pub(crate) async fn temp_table_for(
         &self,
         name: &ObjectName,
     ) -> DFResult<Option<(String, String, String, Arc<dyn TableProvider>)>> {
@@ -1627,6 +1637,64 @@ impl SQLContext {
                         enable_ident_normalization,
                     )?);
                 }
+                AlterTableOperation::ModifyColumn {
+                    col_name,
+                    data_type,
+                    options,
+                    column_position,
+                } => {
+                    if self.temp_table_for(name).await?.is_some() {
+                        return Err(DataFusionError::NotImplemented(
+                            "MODIFY COLUMN on temporary tables or views is not 
supported".into(),
+                        ));
+                    }
+                    if column_position.is_some() {
+                        return Err(DataFusionError::Plan(
+                            "MODIFY COLUMN FIRST/AFTER is not 
supported".into(),
+                        ));
+                    }
+                    let name = normalize_schema_identifier(col_name, 
enable_ident_normalization);
+                    let target = sql_data_type_to_paimon_type(data_type, 
true)?;
+                    if matches!(
+                        target,
+                        PaimonDataType::Row(_)
+                            | PaimonDataType::Array(_)
+                            | PaimonDataType::Map(_)
+                            | PaimonDataType::Multiset(_)
+                    ) {
+                        return Err(DataFusionError::NotImplemented("MODIFY 
COLUMN supports scalar types; nested field evolution requires preserving nested 
field IDs".into()));
+                    }
+                    changes.push(SchemaChange::UpdateColumnType {
+                        field_names: vec![name.clone()],
+                        new_data_type: target,
+                        keep_nullability: true,
+                    });
+                    let mut nullability = false;
+                    let mut comment = false;
+                    for option in options {
+                        match option {
+                            ColumnOption::Null | ColumnOption::NotNull if 
!nullability => {
+                                nullability = true;
+                                
changes.push(SchemaChange::update_column_nullability(
+                                    name.clone(),
+                                    matches!(option, ColumnOption::Null),
+                                ));
+                            }
+                            ColumnOption::Comment(value) if !comment => {
+                                comment = true;
+                                
changes.push(SchemaChange::update_column_comment(
+                                    name.clone(),
+                                    value.clone(),
+                                ));
+                            }
+                            _ => {
+                                return Err(DataFusionError::Plan(format!(
+                                    "Unsupported or repeated MODIFY COLUMN 
option: {option}"
+                                )))
+                            }
+                        }
+                    }
+                }
                 AlterTableOperation::RenameTable { table_name } => {
                     let new_name = match table_name {
                         RenameTableNameKind::To(name) | 
RenameTableNameKind::As(name) => {
@@ -2695,6 +2763,9 @@ fn validate_persistent_create_function(create_function: 
&CreateFunction) -> DFRe
 }
 
 fn parse_sql_statements(sql: &str) -> DFResult<Vec<Statement>> {
+    if let Some(statement) = crate::extended_describe::parse_describe(sql)? {
+        return Ok(vec![statement]);
+    }
     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();
@@ -4529,6 +4600,53 @@ mod tests {
         ));
     }
 
+    #[tokio::test]
+    async fn 
aggregate_compatibility_preserves_persistent_function_and_view_sql() {
+        let catalog = Arc::new(MockCatalog::new());
+        catalog.denied_functions.lock().unwrap().extend([
+            "max_by".to_string(),
+            "count_if".to_string(),
+            "collect_list".to_string(),
+        ]);
+        let ctx = make_sql_context(catalog.clone()).await;
+        ctx.sql("CREATE FUNCTION choose_value(x BIGINT) RETURNS BIGINT 
LANGUAGE SQL IMMUTABLE RETURN x + date_diff(DATE '2026-11-02',DATE 
'2026-11-01')").await.unwrap();
+        let function = catalog
+            .get_function(&Identifier::new("default", "choose_value"))
+            .await
+            .unwrap();
+        let definition = 
function.definition("datafusion").unwrap().sql().unwrap();
+        assert!(definition.contains("date_diff"), "{definition}");
+        assert!(!definition.contains("first_value"), "{definition}");
+        ctx.sql("CREATE VIEW chosen AS SELECT max_by(choose_value(v),100) AS 
answer FROM (VALUES (7),(7)) t(v)").await.unwrap();
+        let view = catalog
+            .get_view(&Identifier::new("default", "chosen"))
+            .await
+            .unwrap();
+        assert!(view.query_for("datafusion").contains("choose_value"));
+        assert!(view.query_for("datafusion").contains("max_by"));
+        assert!(!view.query_for("datafusion").contains("first_value"));
+        let batches = ctx
+            .sql("SELECT answer FROM chosen")
+            .await
+            .unwrap()
+            .collect()
+            .await
+            .unwrap();
+        assert_eq!(
+            
datafusion::common::ScalarValue::try_from_array(batches[0].column(0), 0)
+                .unwrap()
+                .to_string(),
+            "8"
+        );
+        let error = ctx
+            .sql("CREATE FUNCTION invalid_aggregate(x BIGINT) RETURNS BIGINT 
RETURN max_by(x,100)")
+            .await
+            .unwrap_err();
+        assert!(error
+            .to_string()
+            .contains("body must be a scalar expression"));
+    }
+
     #[tokio::test]
     async fn binary_cast_preserves_persistent_view_sql() {
         let catalog = Arc::new(MockCatalog::new());
@@ -6361,11 +6479,15 @@ mod tests {
     #[tokio::test]
     async fn recursive_rest_sql_functions_are_rejected() {
         let catalog = Arc::new(MockCatalog::new());
-        add_unary_sql_function(&catalog, "first", "second(x)", true);
-        add_unary_sql_function(&catalog, "second", "first(x)", true);
+        add_unary_sql_function(&catalog, "cycle_first", "cycle_second(x)", 
true);
+        add_unary_sql_function(&catalog, "cycle_second", "cycle_first(x)", 
true);
         let ctx = make_sql_context(catalog).await;
 
-        let error = ctx.sql("SELECT first(1)").await.unwrap_err().to_string();
+        let error = ctx
+            .sql("SELECT cycle_first(1)")
+            .await
+            .unwrap_err()
+            .to_string();
 
         assert!(error.contains("recursive"), "unexpected error: {error}");
     }
diff --git a/crates/integrations/datafusion/src/sql_function.rs 
b/crates/integrations/datafusion/src/sql_function.rs
index 0fd6a4bf..bd68491a 100644
--- a/crates/integrations/datafusion/src/sql_function.rs
+++ b/crates/integrations/datafusion/src/sql_function.rs
@@ -246,6 +246,7 @@ async fn expand_statement_internal(
             return Err(error);
         }
         if expanded_count == 0 {
+            crate::expression_compat::rewrite(&mut statement, state)?;
             crate::binary_cast::rewrite(&mut statement)?;
             crate::regex_operators::rewrite(&mut statement);
             return Ok(statement);
@@ -376,7 +377,8 @@ fn normalize_identifier(identifier: &Ident) -> String {
 }
 
 fn is_registered_function(state: &SessionState, name: &str) -> bool {
-    state.scalar_functions().contains_key(name)
+    crate::expression_compat::is_aggregate(name)
+        || state.scalar_functions().contains_key(name)
         || state.higher_order_functions().contains_key(name)
         || state.aggregate_functions().contains_key(name)
         || state.window_functions().contains_key(name)
diff --git a/crates/integrations/datafusion/src/variant_functions.rs 
b/crates/integrations/datafusion/src/variant_functions.rs
index c55f18c2..c94845da 100644
--- a/crates/integrations/datafusion/src/variant_functions.rs
+++ b/crates/integrations/datafusion/src/variant_functions.rs
@@ -516,7 +516,7 @@ fn cast_to_f64(variant: VariantRef<'_>) -> DFResult<f64> {
     }
 }
 
-fn cast_to_string(variant: VariantRef<'_>) -> DFResult<String> {
+pub(crate) fn cast_to_string(variant: VariantRef<'_>) -> DFResult<String> {
     match variant.kind().map_err(to_df_error)? {
         VariantKind::Object | VariantKind::Array => 
variant.to_json().map_err(to_df_error),
         VariantKind::Boolean => 
Ok(variant.get_boolean().map_err(to_df_error)?.to_string()),
diff --git a/crates/integrations/datafusion/tests/remaining_compat.rs 
b/crates/integrations/datafusion/tests/remaining_compat.rs
new file mode 100644
index 00000000..e0318d00
--- /dev/null
+++ b/crates/integrations/datafusion/tests/remaining_compat.rs
@@ -0,0 +1,635 @@
+// 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};
+use paimon_datafusion::SQLContext;
+
+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(|batch| {
+            (0..batch.num_rows()).map(|row| {
+                (0..batch.num_columns())
+                    .map(|col| {
+                        ScalarValue::try_from_array(batch.column(col), row)
+                            .unwrap()
+                            .to_string()
+                    })
+                    .collect()
+            })
+        })
+        .collect()
+}
+async fn rejects(ctx: &SQLContext, sql: &str) {
+    if let Ok(frame) = ctx.sql(sql).await {
+        assert!(frame.collect().await.is_err(), "{sql}");
+    }
+}
+
+#[tokio::test]
+async fn aggregate_rewrites_evaluate_volatile_values_once() {
+    use datafusion::arrow::datatypes::DataType;
+    use datafusion::logical_expr::{create_udf, ColumnarValue, Volatility};
+    use std::sync::{
+        atomic::{AtomicUsize, Ordering},
+        Arc,
+    };
+    let ctx = SQLContext::new();
+    let calls = Arc::new(AtomicUsize::new(0));
+    let counted = Arc::clone(&calls);
+    ctx.ctx().register_udf(create_udf(
+        "flip",
+        vec![DataType::Int64],
+        DataType::Int64,
+        Volatility::Volatile,
+        Arc::new(move |args| {
+            if counted.fetch_add(1, Ordering::SeqCst) == 0 {
+                Ok(args[0].clone())
+            } else {
+                Ok(ColumnarValue::Scalar(ScalarValue::Int64(None)))
+            }
+        }),
+    ));
+    for sql in [
+        "SELECT to_json(collect_list(flip(v))) FROM (VALUES (1)) t(v)",
+        "SELECT to_json(collect_list(flip(v))) FROM (VALUES (1)) t(v) GROUP BY 
v",
+        "SELECT arg_max(flip(v),v) FROM (VALUES (1)) t(v)",
+        "SELECT max_by(v,flip(v)) FROM (VALUES (1)) t(v)",
+        "SELECT min_by(v,flip(v)+0) FROM (VALUES (1)) t(v)",
+        "SELECT arg_max(v,flip(v)) FROM (VALUES (1)) t(v) GROUP BY v",
+    ] {
+        calls.store(0, Ordering::SeqCst);
+        let expected = if sql.contains("collect_list") {
+            "[1]"
+        } else {
+            "1"
+        };
+        assert_eq!(rows(&ctx, sql).await, vec![vec![expected]], "{sql}");
+        assert_eq!(calls.load(Ordering::SeqCst), 1, "{sql}");
+    }
+}
+
+#[tokio::test]
+async fn 
selection_aggregates_merge_native_state_across_batches_and_partitions() {
+    use datafusion::arrow::{
+        array::{Int64Array, RecordBatch},
+        datatypes::{DataType, Field, Schema},
+    };
+    use datafusion::datasource::MemTable;
+    use std::sync::Arc;
+    let ctx = SQLContext::new();
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("g", DataType::Int64, false),
+        Field::new("v", DataType::Int64, true),
+        Field::new("k", DataType::Int64, true),
+    ]));
+    let batch = |g: Vec<i64>, v: Vec<Option<i64>>, k: Vec<Option<i64>>| {
+        RecordBatch::try_new(
+            Arc::clone(&schema),
+            vec![
+                Arc::new(Int64Array::from(g)),
+                Arc::new(Int64Array::from(v)),
+                Arc::new(Int64Array::from(k)),
+            ],
+        )
+        .unwrap()
+    };
+    let partitions = vec![
+        vec![
+            batch(vec![1, 2], vec![Some(10), Some(200)], vec![Some(1), None]),
+            batch(vec![1, 3], vec![None, Some(300)], vec![Some(4), Some(10)]),
+        ],
+        vec![
+            batch(
+                vec![1, 2, 3],
+                vec![Some(30), Some(201), None],
+                vec![Some(3), None, Some(11)],
+            ),
+            batch(vec![1, 3], vec![Some(999), Some(301)], vec![None, 
Some(12)]),
+        ],
+    ];
+    ctx.ctx()
+        .register_table(
+            "selection_inputs",
+            Arc::new(MemTable::try_new(schema, partitions).unwrap()),
+        )
+        .unwrap();
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT g,arg_max(CAST(NULL AS BIGINT),1) FROM selection_inputs 
GROUP BY g ORDER BY g"
+        )
+        .await,
+        vec![vec!["1", "NULL"], vec!["2", "NULL"], vec!["3", "NULL"]]
+    );
+    assert_eq!(rows(&ctx,"SELECT 
g,max_by(v,k),min_by(v,k),arg_max(v,k),max_by(v,k) FILTER (WHERE v<300 OR v IS 
NULL) FROM selection_inputs GROUP BY g ORDER BY 
g").await,vec![vec!["1","NULL","10","30","NULL"],vec!["2","NULL","NULL","NULL","NULL"],vec!["3","301","300","301","NULL"]]);
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT max_by(v,k),min_by(v,k),arg_max(v,k) FROM selection_inputs"
+        )
+        .await,
+        vec![vec!["301", "10", "301"]]
+    );
+}
+
+#[tokio::test]
+async fn selection_aggregates_respect_logical_nulls_and_filter_validity() {
+    use datafusion::arrow::{
+        array::{Array, BooleanArray, DictionaryArray, Int64Array, Int8Array, 
RecordBatch},
+        datatypes::{DataType, Field, Int8Type, Schema},
+    };
+    use std::sync::Arc;
+    let ctx = SQLContext::new();
+    let v = DictionaryArray::<Int8Type>::try_new(
+        Int8Array::from(vec![0, 1]),
+        Arc::new(Int64Array::from(vec![Some(10), None])),
+    )
+    .unwrap();
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("g", DataType::Int64, false),
+        Field::new("v", v.data_type().clone(), true),
+        Field::new("k", DataType::Int64, false),
+        Field::new("p", DataType::Boolean, true),
+    ]));
+    ctx.ctx()
+        .register_batch(
+            "nullable_selection",
+            RecordBatch::try_new(
+                schema,
+                vec![
+                    Arc::new(Int64Array::from(vec![1, 1])),
+                    Arc::new(v),
+                    Arc::new(Int64Array::from(vec![1, 2])),
+                    Arc::new(BooleanArray::from(vec![Some(true), None])),
+                ],
+            )
+            .unwrap(),
+        )
+        .unwrap();
+    let global = rows(
+        &ctx,
+        "SELECT to_json(arg_max(v,k)),to_json(max_by(v,k)) FROM 
nullable_selection",
+    )
+    .await;
+    let grouped = rows(
+        &ctx,
+        "SELECT to_json(arg_max(v,k)),to_json(max_by(v,k)) FROM 
nullable_selection GROUP BY g",
+    )
+    .await;
+    let filtered = rows(
+        &ctx,
+        "SELECT max_by(k,k) FILTER(WHERE NOT p) FROM nullable_selection GROUP 
BY g",
+    )
+    .await;
+    assert_eq!(
+        (global, grouped, filtered),
+        (
+            vec![vec!["10".into(), "NULL".into()]],
+            vec![vec!["10".into(), "NULL".into()]],
+            vec![vec!["NULL".into()]]
+        )
+    );
+}
+
+#[tokio::test]
+async fn 
aggregate_rewrites_keep_filters_constant_keys_and_local_registrations() {
+    use datafusion::arrow::datatypes::DataType;
+    use datafusion::logical_expr::{create_udf, Volatility};
+    use std::sync::Arc;
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT array_length(collect_list(v) FILTER (WHERE p 
OR q)) FROM (VALUES (CAST(NULL AS INT),TRUE,FALSE),(7,FALSE,TRUE)) 
t(v,p,q)").await,vec![vec!["1"]]);
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT max_by(v,100),min_by(v,1.5),arg_max(v,0) FROM (VALUES 
('a'),('a')) t(v)"
+        )
+        .await,
+        vec![vec!["a", "a", "a"]]
+    );
+    assert_eq!(rows(&ctx,"SELECT array_length(collect_list(p OR q)) FROM 
(VALUES (NULL,FALSE),(FALSE,TRUE)) t(p,q)").await,vec![vec!["1"]]);
+    ctx.ctx().register_udf(create_udf(
+        "first",
+        vec![DataType::Int64],
+        DataType::Int64,
+        Volatility::Immutable,
+        Arc::new(|args| Ok(args[0].clone())),
+    ));
+    assert_eq!(
+        rows(&ctx, "SELECT first(v) FROM (VALUES (1),(2)) t(v)").await,
+        vec![vec!["1"], vec!["2"]]
+    );
+}
+
+#[tokio::test]
+async fn 
json_output_decodes_dictionary_value_nulls_and_preserves_nested_values() {
+    use datafusion::arrow::{
+        array::{Array, ArrayRef, DictionaryArray, Int8Array, RecordBatch, 
StringArray},
+        datatypes::{Field, Int8Type, Schema},
+    };
+    use std::sync::Arc;
+    let ctx = SQLContext::new();
+    let strings = DictionaryArray::<Int8Type>::try_new(
+        Int8Array::from(vec![Some(0), Some(1), None]),
+        Arc::new(StringArray::from(vec![None, Some("ok")])),
+    )
+    .unwrap();
+    let strings: ArrayRef = Arc::new(strings);
+    ctx.ctx()
+        .register_batch(
+            "dictionary_strings",
+            RecordBatch::try_new(
+                Arc::new(Schema::new(vec![Field::new(
+                    "s",
+                    strings.data_type().clone(),
+                    true,
+                )])),
+                vec![strings],
+            )
+            .unwrap(),
+        )
+        .unwrap();
+    assert_eq!(
+        rows(&ctx, "SELECT to_json(s) FROM dictionary_strings").await,
+        vec![vec!["NULL"], vec!["\"ok\""], vec!["NULL"]]
+    );
+    assert_eq!(
+        rows(&ctx, "SELECT 
to_json(NULL),to_json(named_struct('x',NULL))").await,
+        vec![vec!["NULL", "{\"x\":null}"]]
+    );
+    let variant = ctx
+        .sql("SELECT parse_json(s) AS v FROM (VALUES ('{\"a\":1}'),(NULL)) 
t(s)")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    let dictionary = DictionaryArray::<Int8Type>::try_new(
+        Int8Array::from(vec![Some(0), Some(1), None]),
+        Arc::clone(variant[0].column(0)),
+    )
+    .unwrap();
+    let dictionary: ArrayRef = Arc::new(dictionary);
+    ctx.ctx()
+        .register_batch(
+            "dictionary_variants",
+            RecordBatch::try_new(
+                Arc::new(Schema::new(vec![Field::new(
+                    "v",
+                    dictionary.data_type().clone(),
+                    true,
+                )])),
+                vec![dictionary],
+            )
+            .unwrap(),
+        )
+        .unwrap();
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT to_json(v),CAST(v AS STRING) AS cast_value,TRY_CAST(v AS 
STRING) AS try_value FROM dictionary_variants"
+        )
+        .await,
+        vec![
+            vec!["{\"a\":1}", "{\"a\":1}", "{\"a\":1}"],
+            vec!["NULL", "NULL", "NULL"],
+            vec!["NULL", "NULL", "NULL"]
+        ]
+    );
+    let json=rows(&ctx,"SELECT to_json(named_struct('n',NULL,'d',CAST(1.25 AS 
DECIMAL(8,2)),'b',decode('00ff','hex')))").await;
+    assert_eq!(
+        serde_json::from_str::<serde_json::Value>(&json[0][0]).unwrap(),
+        serde_json::json!({"n":null,"d":1.25,"b":"AP8="})
+    );
+}
+
+#[tokio::test]
+async fn 
ddl_compatibility_respects_name_resolution_and_does_not_mutate_shadowed_tables()
 {
+    let (_tmp, catalog) = common::create_test_env();
+    let ctx = common::create_sql_context(catalog.clone()).await;
+    ctx.sql("CREATE TABLE default.shadow (id INT)")
+        .await
+        .unwrap();
+    let id = Identifier::new("default", "shadow");
+    let before = catalog.get_table(&id).await.unwrap().schema().clone();
+    assert!(rows(&ctx, "DESCRIBE EXTENDED DEFAULT.SHADOW")
+        .await
+        .iter()
+        .any(|r| r[0] == "id"));
+    ctx.sql("CREATE TEMP VIEW default.shadow AS SELECT 99 AS temp_only")
+        .await
+        .unwrap();
+    assert!(rows(&ctx, "DESCRIBE TABLE EXTENDED DEFAULT.SHADOW")
+        .await
+        .iter()
+        .any(|r| r[0] == "temp_only"));
+    rejects(&ctx, "ALTER TABLE default.shadow MODIFY COLUMN id BIGINT").await;
+    assert_eq!(
+        catalog.get_table(&id).await.unwrap().schema().fields(),
+        before.fields()
+    );
+    ctx.sql("CREATE TABLE default.nested (r STRUCT<a INT>)")
+        .await
+        .unwrap();
+    ctx.sql("INSERT INTO default.nested VALUES (named_struct('a',7))")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    rejects(
+        &ctx,
+        "ALTER TABLE default.nested MODIFY COLUMN r STRUCT<a BIGINT>",
+    )
+    .await;
+    assert_eq!(
+        rows(&ctx, "SELECT r.a FROM default.nested").await,
+        vec![vec!["7"]]
+    );
+    ctx.sql("CREATE TABLE default.\"MixedCase\" (id INT)")
+        .await
+        .unwrap();
+    assert!(rows(&ctx, "DESCRIBE FORMATTED default.\"MixedCase\"")
+        .await
+        .iter()
+        .any(|r| r[0] == "# Table" && r[1] == "MixedCase"));
+    ctx.sql("SET datafusion.sql_parser.enable_ident_normalization = false")
+        .await
+        .unwrap();
+    assert!(rows(&ctx, "DESCRIBE EXTENDED default.MixedCase")
+        .await
+        .iter()
+        .any(|r| r[0] == "# Table" && r[1] == "MixedCase"));
+    let native = SQLContext::new();
+    native
+        .sql("CREATE VIEW native_view AS SELECT 1 AS x")
+        .await
+        .unwrap();
+    assert!(rows(&native, "DESCRIBE EXTENDED native_view")
+        .await
+        .iter()
+        .any(|r| r[0] == "x"));
+}
+
+#[tokio::test]
+async fn temporal_and_encoding_boundaries_are_explicit() {
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT conv('10',-10,2) IS 
NULL,conv('9223372036854775808',-10,10) IS 
NULL,conv('10',10,-2)").await,vec![vec!["true","true","1010"]]);
+    for zone in ["+08:60", "-09:99", "+0860", "-0060", "+24:00"] {
+        assert_eq!(
+            rows(&ctx, &format!("SELECT convert_tz('2026-11-01 
12:00:00','{zone}','UTC') IS NULL,convert_tz('2026-11-01 
12:00:00','UTC','{zone}') IS NULL")).await,
+            vec![vec!["true", "true"]],
+            "{zone}"
+        );
+    }
+    assert_eq!(rows(&ctx,"SELECT convert_tz('2026-11-01 
12:00:00','+08:30','UTC')=TIMESTAMP '2026-11-01 
03:30:00',convert_tz('2026-11-01 12:00:00','UTC','-0930')=TIMESTAMP '2026-11-01 
02:30:00',convert_tz('2026-11-01 12:00:00','+08','UTC')=TIMESTAMP '2026-11-01 
04:00:00'").await,vec![vec!["true","true","true"]]);
+    assert_eq!(rows(&ctx,"SELECT date_diff('month',TIMESTAMP '2024-01-31 
12:00:00',TIMESTAMP '2024-02-29 12:00:00'),date_diff('month',TIMESTAMP 
'2024-02-29 12:00:00',TIMESTAMP '2024-01-31 
12:00:00'),date_diff('hour',TIMESTAMP '2026-11-01 04:00:00',TIMESTAMP 
'2026-11-01 01:30:00')").await,vec![vec!["1","-1","-2"]]);
+    assert_eq!(rows(&ctx,"SELECT conv('18446744073709551616',10,16),conv('  
+1z',10,2),conv('bad',10,16),conv('ff',-9223372036854775808,10) IS 
NULL,convert_tz('2026-11-01 01:30:00','America/New_York','UTC') IS 
NULL,convert_tz('2026-11-01 12:00:00','invalid','UTC') IS 
NULL").await,vec![vec!["FFFFFFFFFFFFFFFF","1","0","true","true","true"]]);
+}
+
+#[tokio::test]
+async fn compatible_aggregates_preserve_null_filter_and_ordering_contracts() {
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT count_if(p), any(p), first(CASE WHEN v=8 THEN 
NULL ELSE v END,true), any_value(CASE WHEN v=8 THEN NULL ELSE v END,true), 
approx_count_distinct(v,0.05) FROM (VALUES 
(NULL,NULL),(FALSE,7),(TRUE,7),(NULL,8)) 
t(p,v)").await,vec![vec!["1","true","7","7","2"]]);
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT arrow_typeof(approx_count_distinct(v)) FROM (VALUES 
(1),(2)) t(v)"
+        )
+        .await,
+        vec![vec!["Int64"]]
+    );
+    assert_eq!(rows(&ctx,"SELECT max_by(v,k),min_by(v,k),arg_max(v,k) FROM 
(VALUES ('ignored',NULL),('a',1),('b',2),(NULL,3)) 
t(v,k)").await,vec![vec!["NULL","a","b"]]);
+    assert_eq!(rows(&ctx,"SELECT max_by(v,k),min_by(v,k),arg_max(v,k) FROM 
(VALUES ('a',CAST(NULL AS INT))) 
t(v,k)").await,vec![vec!["NULL","NULL","NULL"]]);
+    assert_eq!(rows(&ctx,"SELECT max_by(v,k) FILTER (WHERE k<3),listagg(v,',') 
WITHIN GROUP (ORDER BY k DESC) FROM (VALUES ('a',1),('b',2),(NULL,3)) 
t(v,k)").await,vec![vec!["b","b,a"]]);
+    assert_eq!(rows(&ctx,"SELECT listagg(v,',') WITHIN GROUP (ORDER BY 
100),listagg(v,',') WITHIN GROUP (ORDER BY 0) FROM (VALUES ('a'),('a')) 
t(v)").await,vec![vec!["a,a","a,a"]]);
+    assert_eq!(rows(&ctx,"SELECT 
array_length(collect_list(v)),array_length(collect_list(DISTINCT 
v)),listagg(v,',') WITHIN GROUP (ORDER BY v) FROM (VALUES 
('b'),(NULL),('a'),('a')) t(v)").await,vec![vec!["3","2","a,a,b"]]);
+    assert_eq!(rows(&ctx,"SELECT 
array_length(collect_list(v)),count_if(p),any(p) FROM (VALUES (CAST(NULL AS 
INT),CAST(NULL AS BOOLEAN))) t(v,p) WHERE 
FALSE").await,vec![vec!["0","0","NULL"]]);
+    assert_eq!(rows(&ctx,"SELECT k,count_if(p) OVER (ORDER BY k ROWS BETWEEN 
UNBOUNDED PRECEDING AND CURRENT ROW) FROM (VALUES (1,TRUE),(2,FALSE),(3,TRUE)) 
t(k,p) ORDER BY k").await,vec![vec!["1","1"],vec!["2","1"],vec!["3","2"]]);
+    rejects(&ctx, "SELECT approx_count_distinct(1,0.0001)").await;
+    rejects(&ctx, "SELECT first(1, 7)").await;
+    assert_eq!(rows(&ctx,"SELECT to_json(collect_list(v IGNORE 
NULLS)),to_json(collect_list(v) IGNORE NULLS) FROM (VALUES (1),(NULL)) 
t(v)").await,vec![vec!["[1]","[1]"]]);
+    rejects(
+        &ctx,
+        "SELECT collect_list(v) RESPECT NULLS FROM (VALUES (1),(NULL)) t(v)",
+    )
+    .await;
+}
+
+#[tokio::test]
+async fn json_output_and_variant_cast_preserve_structure_and_nulls() {
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT CAST(parse_json('{\"a\":1}') AS 
STRING),CAST(parse_json('\"hello\"') AS STRING),CAST(parse_json('null') AS 
STRING),TRY_CAST(parse_json('true') AS 
STRING)").await,vec![vec!["{\"a\":1}","hello","NULL","true"]]);
+    let r=rows(&ctx,"SELECT 
to_json(named_struct('a',ARRAY[1,NULL,3],'b',map(['x'],[TRUE]))),json_object('x',1,'y',NULL),to_json(parse_json('{\"s\":\"a\\nb\"}'))").await;
+    assert_eq!(
+        serde_json::from_str::<serde_json::Value>(&r[0][0]).unwrap(),
+        serde_json::json!({"a":[1,null,3],"b":{"x":true}})
+    );
+    assert_eq!(
+        serde_json::from_str::<serde_json::Value>(&r[0][1]).unwrap(),
+        serde_json::json!({"x":1,"y":null})
+    );
+    assert_eq!(
+        serde_json::from_str::<serde_json::Value>(&r[0][2]).unwrap(),
+        serde_json::json!({"s":"a\nb"})
+    );
+    assert_eq!(
+        rows(&ctx, "SELECT to_json(CAST(NULL AS STRING)),json_object()").await,
+        vec![vec!["NULL", "{}"]]
+    );
+    rejects(&ctx, "SELECT json_object(NULL,1)").await;
+    rejects(&ctx, "SELECT json_object('a')").await;
+}
+
+#[tokio::test]
+async fn custom_like_escape_supports_rows_unicode_and_negation() {
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT s LIKE p ESCAPE '!',s NOT LIKE p ESCAPE '!' 
FROM (VALUES ('a_x','a!_%'),('ab','a!_%'),('a!x','a!!%'),(NULL,'x')) 
t(s,p)").await,vec![vec!["true","false"],vec!["false","true"],vec!["true","false"],vec!["NULL","NULL"]]);
+    assert_eq!(
+        rows(
+            &ctx,
+            "SELECT '汉_字' LIKE '汉界_字' ESCAPE '界','Ab_' ILIKE 'a%!_' ESCAPE '!'"
+        )
+        .await,
+        vec![vec!["true", "true"]]
+    );
+    rejects(&ctx, "SELECT 'a' LIKE 'a!' ESCAPE '!'").await;
+    rejects(&ctx, "SELECT 'a' LIKE '%' ESCAPE '!!'").await;
+}
+
+#[tokio::test]
+async fn 
variant_string_cast_rejects_corruption_without_reinterpreting_ordinary_structs()
 {
+    use datafusion::arrow::{
+        array::{Array, ArrayRef, BinaryArray, RecordBatch, StructArray},
+        datatypes::{DataType, Field, Schema},
+    };
+    use std::sync::Arc;
+    let ctx = SQLContext::new();
+    let good = ctx
+        .sql("SELECT parse_json('{}') AS v")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    let DataType::Struct(fields) = good[0].column(0).data_type() else {
+        panic!("Expected Variant struct")
+    };
+    let malformed: ArrayRef = Arc::new(StructArray::new(
+        fields.clone(),
+        vec![
+            Arc::new(BinaryArray::from(vec![Some(&[255u8][..])])),
+            Arc::new(BinaryArray::from(vec![Some(&[][..])])),
+        ],
+        None,
+    ));
+    ctx.ctx()
+        .register_batch(
+            "malformed_variants",
+            RecordBatch::try_new(
+                Arc::new(Schema::new(vec![Field::new(
+                    "v",
+                    malformed.data_type().clone(),
+                    true,
+                )])),
+                vec![malformed],
+            )
+            .unwrap(),
+        )
+        .unwrap();
+    assert_eq!(
+        rows(&ctx, "SELECT TRY_CAST(v AS STRING) FROM 
malformed_variants").await,
+        vec![vec!["NULL"]]
+    );
+    rejects(&ctx, "SELECT CAST(v AS STRING) FROM malformed_variants").await;
+    let ordinary = rows(
+        &ctx,
+        "SELECT 
to_json(named_struct('value',decode('01','hex'),'metadata',decode('02','hex')))",
+    )
+    .await;
+    assert_eq!(
+        serde_json::from_str::<serde_json::Value>(&ordinary[0][0]).unwrap(),
+        serde_json::json!({"value":"AQ==","metadata":"Ag=="})
+    );
+}
+
+#[tokio::test]
+async fn scalar_compatibility_handles_dates_timezones_bases_and_assertions() {
+    let ctx = SQLContext::new();
+    assert_eq!(rows(&ctx,"SELECT 
assert_true(TRUE),conv('ff',16,10),conv('-1',10,16),conv('FFFFFFFFFFFFFFFF',16,-10),date_diff(DATE
 '2026-11-02',DATE '2026-11-01'),date_diff('hour',TIMESTAMP '2026-11-01 
01:30:00',TIMESTAMP '2026-11-01 
04:00:00')").await,vec![vec!["NULL","255","FFFFFFFFFFFFFFFF","-1","1","2"]]);
+    assert_eq!(rows(&ctx,"SELECT convert_tz('2026-11-01 
12:00:00','UTC','Asia/Shanghai')=TIMESTAMP '2026-11-01 
20:00:00',convert_tz('2026-03-08 02:30:00','America/New_York','UTC') IS 
NULL,conv('ff',1,10) IS NULL").await,vec![vec!["true","true","true"]]);
+    rejects(&ctx, "SELECT assert_true(FALSE,'bad input')").await;
+    rejects(&ctx, "SELECT assert_true(NULL)").await;
+    rejects(
+        &ctx,
+        "SELECT date_diff('nonsense',DATE '2026-11-01',DATE '2026-11-02')",
+    )
+    .await;
+}
+
+#[tokio::test]
+async fn modify_column_and_extended_describe_keep_data_and_field_identity() {
+    let (_tmp, catalog) = common::create_test_env();
+    let ctx = common::create_sql_context(catalog.clone()).await;
+    ctx.sql("CREATE TABLE default.compat_ddl (id INT NOT NULL COMMENT 
'identity',v STRING) COMMENT 'table info'").await.unwrap();
+    ctx.sql("INSERT INTO default.compat_ddl VALUES (7,'x')")
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    let id = Identifier::new("default", "compat_ddl");
+    let before = catalog.get_table(&id).await.unwrap().schema().clone();
+    ctx.sql("ALTER TABLE default.compat_ddl MODIFY COLUMN id BIGINT")
+        .await
+        .unwrap();
+    let after = catalog.get_table(&id).await.unwrap().schema().clone();
+    assert_eq!(before.fields()[0].id(), after.fields()[0].id());
+    assert_eq!(after.fields()[0].description(), Some("identity"));
+    assert!(!after.fields()[0].data_type().is_nullable());
+    assert_eq!(
+        rows(&ctx, "SELECT arrow_typeof(id) FROM default.compat_ddl").await,
+        vec![vec!["Int64"]]
+    );
+    rejects(
+        &ctx,
+        "ALTER TABLE default.compat_ddl MODIFY COLUMN v STRING NOT NULL 
COMMENT 'new value'",
+    )
+    .await;
+    assert_eq!(
+        catalog.get_table(&id).await.unwrap().schema().id(),
+        after.id()
+    );
+    ctx.sql(
+        "ALTER TABLE default.compat_ddl SET 
('alter-column-null-to-not-null.disabled'='false')",
+    )
+    .await
+    .unwrap();
+    ctx.sql("ALTER TABLE default.compat_ddl MODIFY COLUMN v STRING NOT NULL 
COMMENT 'new value'")
+        .await
+        .unwrap();
+    let updated = catalog.get_table(&id).await.unwrap().schema().clone();
+    assert_eq!(updated.fields()[1].id(), before.fields()[1].id());
+    assert_eq!(updated.fields()[1].description(), Some("new value"));
+    assert!(!updated.fields()[1].data_type().is_nullable());
+    ctx.sql("ALTER TABLE default.compat_ddl MODIFY COLUMN v STRING NULL")
+        .await
+        .unwrap();
+    assert!(catalog.get_table(&id).await.unwrap().schema().fields()[1]
+        .data_type()
+        .is_nullable());
+    assert_eq!(
+        rows(&ctx, "SELECT id,v FROM default.compat_ddl").await,
+        vec![vec!["7", "x"]]
+    );
+    ctx.sql("ALTER TABLE default.compat_ddl SET ('test.secret'='hidden')")
+        .await
+        .unwrap();
+    let describe = rows(&ctx, "DESCRIBE TABLE EXTENDED 
default.compat_ddl").await;
+    let properties = describe.iter().find(|r| r[0] == "# Properties").unwrap();
+    assert!(!properties[1].contains("hidden"));
+    assert!(properties[1].contains("<redacted>"));
+    assert!(describe.iter().any(|r| r[0] == "id" && r[2] == "identity"));
+    assert!(describe
+        .iter()
+        .any(|r| r[0] == "# Comment" && r[1] == "table info"));
+    assert_eq!(
+        describe,
+        rows(&ctx, "DESCRIBE EXTENDED default.compat_ddl").await
+    );
+    rejects(
+        &ctx,
+        "ALTER TABLE default.compat_ddl MODIFY COLUMN id INT FIRST",
+    )
+    .await;
+    rejects(
+        &ctx,
+        "ALTER TABLE default.compat_ddl MODIFY COLUMN v INT DEFAULT 9",
+    )
+    .await;
+    assert_eq!(
+        rows(&ctx, "SELECT id,v FROM default.compat_ddl").await,
+        vec![vec!["7", "x"]]
+    );
+}
diff --git a/crates/paimon/src/io/cache/reader.rs 
b/crates/paimon/src/io/cache/reader.rs
index cafb398a..2ab4cada 100644
--- a/crates/paimon/src/io/cache/reader.rs
+++ b/crates/paimon/src/io/cache/reader.rs
@@ -465,7 +465,7 @@ mod tests {
     }
 
     #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-    async fn coalesced_shared_stripe_collisions_do_not_wait_on_self() {
+    async fn coalesced_shared_stripe_collisions_preserve_data_and_cache_hits() 
{
         let directory = tempfile::tempdir().unwrap();
         let block_size = 256 * 1024;
         let data = Bytes::from(vec![42; 32 * block_size]);
@@ -495,21 +495,24 @@ mod tests {
             data.len() as u64,
             cache.clone(),
         );
+        // The focused batch_download_locks_deduplicate_and_skip_busy_stripes 
test
+        // checks lock behavior. This end-to-end read also publishes 32 disk 
blocks;
+        // allow slower CI filesystems the same budget as the disjoint-read 
fixture.
         let result = tokio::time::timeout(
-            std::time::Duration::from_secs(2),
+            std::time::Duration::from_secs(30),
             reader.read(0..data.len() as u64),
         )
         .await
-        .expect("colliding stripes must not wait for their own lock timeout")
+        .expect("coalesced shared read must complete")
         .unwrap();
         assert_eq!(result, data);
         assert_eq!(delegate.reads.load(Ordering::SeqCst), 1);
         let _fills = tokio::time::timeout(
-            std::time::Duration::from_secs(2),
+            std::time::Duration::from_secs(30),
             cache.fill_slots.clone().acquire_many_owned(8),
         )
         .await
-        .unwrap()
+        .expect("shared cache background fills must complete")
         .unwrap();
         assert_eq!(reader.read(0..data.len() as u64).await.unwrap(), data);
         assert_eq!(delegate.reads.load(Ordering::SeqCst), 1);
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 9cd6d1ff..0e872d05 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -815,6 +815,21 @@ ALTER TABLE paimon.my_db.users SET 
TBLPROPERTIES('data-evolution.enabled' = 'tru
 ALTER TABLE IF EXISTS paimon.my_db.users ADD COLUMN age INT;
 ```
 
+### Alternate column changes and extended descriptions
+
+`ALTER TABLE ... MODIFY COLUMN name type [NULL | NOT NULL] [COMMENT 'text']`
+uses existing scalar schema-evolution validation. Unspecified nullability and
+comments, field IDs and stored data are preserved. The existing
+`alter-column-null-to-not-null.disabled` policy still applies. Temporary 
objects,
+FIRST/AFTER, defaults and nested/container type changes are rejected before a
+schema update; nested field IDs must not be reassigned by a type declaration.
+
+`DESCRIBE [TABLE] EXTENDED table` and FORMATTED return Paimon columns with 
comments
+plus catalog/database/table, schema ID, location, table comment, keys and 
sorted
+table properties. Credential-like property values are redacted. Identifier
+normalization follows the session setting and quoted names are preserved.
+Temporary/native objects and views keep existing native DESCRIBE behavior.
+
 ### Table and column comments
 
 ```sql
@@ -1950,6 +1965,79 @@ SELECT
 FROM paimon.my_db.user_events;
 ```
 
+### Aggregate compatibility
+
+SQLContext accepts the following aggregates in queries and view definitions.
+Session registrations take priority, and stored REST definitions retain their
+original SQL. REST SQL function bodies must still be scalar expressions.
+Bare compatibility names follow built-in precedence; use a qualified catalog
+function name to call a persistent function with the same name.
+
+| Function | Contract |
+| --- | --- |
+| `count_if(condition)` | Counts TRUE; FALSE and NULL do not contribute; an 
empty group returns 0 |
+| `any(condition)` | Boolean OR; an empty or all-NULL group returns NULL |
+| `first(value[, ignoreNulls])`, `any_value(value[, ignoreNulls])` | Native 
first-value aggregation; the optional NULL flag must be a boolean literal; 
without ordering the chosen value is not deterministic |
+| `approx_count_distinct(value[, relativeSD])` | BIGINT estimate with native 
fixed-precision HLL; optional relativeSD must be a numeric literal between 
0.008125 and 0.39; smaller errors are rejected |
+| `max_by(value, key)`, `min_by(value, key)` | Select by greatest/least 
non-NULL key; a selected NULL value remains NULL; empty/all-NULL-key groups 
return NULL |
+| `arg_max(value, key)` | Like max_by but ignores rows where value or key is 
NULL |
+| `collect_list(value)` | Collects non-NULL values with duplicates; 
empty/all-NULL groups return an empty array |
+| `listagg(value[, delimiter]) WITHIN GROUP (ORDER BY ...)` | Native ordered 
string aggregation; NULL values are skipped; the default delimiter is empty |
+
+Native FILTER and supported ordering/DISTINCT clauses are retained. The 
selection
+aggregates reject DISTINCT, OVER, additional ordering and NULL modifiers. Tied
+keys may choose any eligible value. LISTAGG overflow and top-k selection forms
+are unsupported. Approximate counts use native HLL estimates rather than 
Spark's
+serialized HLL++ state.
+COLLECT_LIST always ignores NULLs and rejects RESPECT NULLS. Aggregate values 
and
+selection keys are evaluated once, including volatile expressions.
+
+### JSON output and Variant string casts
+
+`to_json(value)` produces compact JSON from structs, lists, maps, Variant and
+scalar values. SQL NULL returns SQL NULL; nested NULLs become JSON null. Binary
+values use padded Base64. Decimals retain their digits; non-finite floats are
+rejected. Temporal values use Arrow string formatting. Map keys must be 
non-NULL.
+Spark JSON formatting options are not supported.
+
+`json_object(key, value, ...)` constructs an object. Keys are converted to 
strings,
+NULL keys are rejected, NULL values are retained, and the last repeated key 
wins.
+`json_object()` returns `{}`.
+
+`CAST(variant_value AS STRING)` unwraps Variant strings, formats scalar values 
and
+serializes arrays/objects as JSON. SQL NULL and Variant JSON null become SQL 
NULL.
+TRY_CAST returns NULL for malformed Variant values. Only the exact Paimon 
Variant
+representation uses this conversion; ordinary casts retain native behavior.
+
+### Additional scalar compatibility
+
+| Function | Contract |
+| --- | --- |
+| `assert_true(condition[, message])` | Returns NULL for TRUE; FALSE or NULL 
raises an execution error with the optional message |
+| `conv(text, from_base, to_base)` | Source base 2 through 36 conversion of a 
64-bit value; a negative destination base formats a signed result; invalid 
bases, including negative source bases, return NULL |
+| `date_diff(end, start)` | BIGINT calendar days after native DATE coercion |
+| `date_diff(unit, start, end)` | Signed whole-unit difference at microsecond 
precision, from microsecond through week and calendar month/quarter/year; 
calendar fields use UTC and month-end clamping |
+| `convert_tz(datetime, from_zone, to_zone)` | Interprets a timezone-less 
datetime in the source zone, returning a timezone-less microsecond timestamp in 
the destination zone |
+
+CONV reads an optional sign and valid digit prefix, uses uppercase output, and
+saturates overflowing unsigned input at 2^64-1 before applying the sign. No 
valid
+digits means zero. NULL inputs propagate except that assert_true(NULL) fails.
+CONVERT_TZ accepts IANA zones and fixed offsets; invalid inputs, ambiguous 
local
+times and nonexistent local times return NULL.
+
+### Custom LIKE escape characters
+
+LIKE, NOT LIKE and ILIKE accept a one-character ESCAPE literal, including 
Unicode:
+
+```sql
+SELECT value LIKE 'item!_%' ESCAPE '!' FROM events;
+```
+
+The escape quotes the next pattern character. `%` matches any number of Unicode
+characters and `_` matches one, including newlines. A trailing escape is an 
error;
+NULL values/patterns return NULL. The backslash path remains native. LIKE ANY
+with a custom escape is unsupported.
+
 ### Compatibility Functions
 
 `SQLContext` registers the following functions without requiring a catalog:

Reply via email to