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 efbae37a [datafusion] Align read_files projections and CSV/glob
behavior (#1438)
efbae37a is described below
commit efbae37a25b87c090b1f01bccc9fc126d092170e
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 17 19:44:17 2026 +0800
[datafusion] Align read_files projections and CSV/glob behavior (#1438)
---
crates/integrations/datafusion/src/catalog.rs | 6 +-
.../src/partition_functions/temporary_view.rs | 8 +-
.../integrations/datafusion/src/read_files/glob.rs | 27 +-
.../integrations/datafusion/src/read_files/mod.rs | 72 +++-
.../datafusion/src/read_files/options.rs | 22 +-
.../datafusion/src/read_files/projection.rs | 354 +++++++++++++++++
.../integrations/datafusion/src/read_files/raw.rs | 14 +-
crates/integrations/datafusion/src/sql_context.rs | 33 +-
.../datafusion/tests/read_files_access.rs | 12 +-
.../datafusion/tests/read_files_behavior.rs | 418 +++++++++++++++++++++
docs/src/sql.md | 30 +-
11 files changed, 947 insertions(+), 49 deletions(-)
diff --git a/crates/integrations/datafusion/src/catalog.rs
b/crates/integrations/datafusion/src/catalog.rs
index fa6c3bc7..157cef67 100644
--- a/crates/integrations/datafusion/src/catalog.rs
+++ b/crates/integrations/datafusion/src/catalog.rs
@@ -1103,7 +1103,11 @@ impl PaimonSchemaProvider {
identifier.database(),
)
.await?;
- let plan = state.create_logical_plan(&query).await?;
+ let plan = crate::read_files::sql(
+
&datafusion::prelude::SessionContext::new_with_state(state),
+ &query,
+ datafusion::execution::context::SQLOptions::new(),
+ ).await?.into_unoptimized_plan();
let plan = enforce_view_schema(plan, &view)?;
Ok(Some(Arc::new(datafusion::datasource::ViewTable::new(
plan,
diff --git
a/crates/integrations/datafusion/src/partition_functions/temporary_view.rs
b/crates/integrations/datafusion/src/partition_functions/temporary_view.rs
index 6e4435ed..2e9c804b 100644
--- a/crates/integrations/datafusion/src/partition_functions/temporary_view.rs
+++ b/crates/integrations/datafusion/src/partition_functions/temporary_view.rs
@@ -116,7 +116,13 @@ impl MetadataView {
&self.database,
)
.await?;
- let plan = state.create_logical_plan(&query).await?;
+ let plan = crate::read_files::sql(
+
&datafusion::prelude::SessionContext::new_with_state(state),
+ &query,
+ datafusion::execution::context::SQLOptions::new(),
+ )
+ .await?
+ .into_unoptimized_plan();
if plan.schema().as_arrow() != self.schema.as_ref() {
return Err(plan_datafusion_err!(
"metadata-dependent temporary view schema changed
since creation"
diff --git a/crates/integrations/datafusion/src/read_files/glob.rs
b/crates/integrations/datafusion/src/read_files/glob.rs
index 25520da9..91732f3e 100644
--- a/crates/integrations/datafusion/src/read_files/glob.rs
+++ b/crates/integrations/datafusion/src/read_files/glob.rs
@@ -20,6 +20,31 @@ use datafusion::error::Result;
use super::error;
+/// Hadoop uses `^`, rather than Rust glob's `!`, to negate a character class.
+pub(super) fn pattern(value: &str) -> Result<Pattern> {
+ if value.contains(['{', '}']) {
+ return Err(error("brace expansion in glob patterns is not supported"));
+ }
+ let mut translated = String::with_capacity(value.len());
+ let mut chars = value.chars().peekable();
+ while let Some(ch) = chars.next() {
+ translated.push(ch);
+ if ch == '[' {
+ match chars.peek() {
+ Some('^') => {
+ chars.next();
+ translated.push('!');
+ }
+ Some('!') => {
+ return Err(error("use [^...] to negate a glob character
class"));
+ }
+ _ => {}
+ }
+ }
+ }
+ Pattern::new(&translated).map_err(error)
+}
+
/// Match file or directory names at their specified depth. A matched directory
/// includes its descendants, just as a literal directory passed to read_files.
#[derive(Clone, Debug)]
@@ -34,7 +59,7 @@ impl PathGlob {
let components = pattern
.trim_end_matches('/')
.split('/')
- .map(|part| Pattern::new(part).map_err(error))
+ .map(self::pattern)
.collect::<Result<_>>()?;
Ok(Self {
components,
diff --git a/crates/integrations/datafusion/src/read_files/mod.rs
b/crates/integrations/datafusion/src/read_files/mod.rs
index 52d57b82..e6328d37 100644
--- a/crates/integrations/datafusion/src/read_files/mod.rs
+++ b/crates/integrations/datafusion/src/read_files/mod.rs
@@ -17,6 +17,7 @@
mod glob;
mod options;
+mod projection;
mod raw;
mod scoped;
pub(crate) mod store;
@@ -41,16 +42,37 @@ use datafusion::logical_expr::planner::{
use datafusion::logical_expr::{lit, LogicalPlan, LogicalPlanBuilder, Union};
use datafusion::object_store::{path::Path, ObjectMeta, ObjectStore,
ObjectStoreExt};
use datafusion::prelude::SessionContext;
-use datafusion::sql::sqlparser::ast::{FunctionArg, FunctionArgExpr,
TableFactor};
+use datafusion::sql::sqlparser::ast::{
+ FunctionArg, FunctionArgExpr, ObjectName, TableAliasColumnDef, TableFactor,
+};
use futures::TryStreamExt;
use url::Url;
use options::{Format, Options};
+pub(crate) use projection::sql;
+
+const GENERATED_METADATA: &str = "paimon.read_files.generated_metadata";
+
+fn metadata_expr(file: &File) -> Result<datafusion::logical_expr::Expr> {
+ Ok(lit(metadata(file)?).alias_with_metadata(
+ "_metadata",
+ Some(datafusion::common::metadata::FieldMetadata::from(
+ std::collections::HashMap::from([(GENERATED_METADATA.to_string(),
"true".to_string())]),
+ )),
+ ))
+}
fn error(message: impl std::fmt::Display) -> DataFusionError {
DataFusionError::Plan(format!("read_files: {message}"))
}
+fn is_read_files(name: &ObjectName) -> bool {
+ name.0.len() == 1
+ && name.0[0]
+ .as_ident()
+ .is_some_and(|i| i.value.eq_ignore_ascii_case("read_files"))
+}
+
fn parse_url(path: &str) -> Result<Url> {
let url = ListingTableUrl::parse(path)?;
let url: &Url = url.as_ref();
@@ -198,11 +220,7 @@ impl RelationPlanner for ReadFilesPlanner {
} => (name, args, alias),
_ => return Ok(RelationPlanning::Original(Box::new(relation))),
};
- if name.0.len() != 1
- || !name.0[0]
- .as_ident()
- .is_some_and(|i| i.value.eq_ignore_ascii_case("read_files"))
- {
+ if !is_read_files(name) {
return Ok(RelationPlanning::Original(Box::new(relation)));
}
let mut exprs = Vec::new();
@@ -230,9 +248,27 @@ impl RelationPlanner for ReadFilesPlanner {
.context_provider()
.get_table_function_source("read_files", exprs)?;
let plan = LogicalPlanBuilder::scan("read_files()", source,
None)?.build()?;
+ let mut alias = alias.clone();
+ if let Some(alias) = &mut alias {
+ if !alias.columns.is_empty()
+ && plan
+ .schema()
+ .fields()
+ .iter()
+ .any(|field|
field.metadata().contains_key(GENERATED_METADATA))
+ {
+ if alias.columns.len() + 1 != plan.schema().fields().len() {
+ return Err(error(
+ "table alias columns must match the number of data
columns",
+ ));
+ }
+ alias
+ .columns
+ .push(TableAliasColumnDef::from_name("_metadata"));
+ }
+ }
Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
- plan,
- alias.clone(),
+ plan, alias,
))))
}
}
@@ -390,6 +426,20 @@ async fn build(
.await?
}
};
+ // A real field can carry metadata from an earlier export. Provenance tags
+ // belong to this source binding and must never hide persisted user
columns.
+ let schema =
Arc::new(datafusion::arrow::datatypes::Schema::new_with_metadata(
+ schema
+ .fields()
+ .iter()
+ .map(|field| {
+ let mut metadata = field.metadata().clone();
+ metadata.remove(GENERATED_METADATA);
+ field.as_ref().clone().with_metadata(metadata)
+ })
+ .collect::<Vec<_>>(),
+ schema.metadata().clone(),
+ ));
let listing_options =
ListingOptions::new(file_format).with_file_extension("");
let has_source_metadata = schema
.fields()
@@ -409,7 +459,7 @@ async fn build(
let frame = if has_source_metadata {
frame
} else {
- frame.with_column("_metadata", lit(metadata(&file)?))?
+ frame.with_column("_metadata", metadata_expr(&file)?)?
};
plans.push(frame.into_unoptimized_plan());
}
@@ -435,6 +485,8 @@ fn metadata(file: &File) -> Result<ScalarValue> {
DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Microsecond, None),
false,
),
+ Field::new("file_block_start", DataType::Int64, false),
+ Field::new("file_block_length", DataType::Int64, false),
];
let values = [
ScalarValue::Utf8(Some(file.url.to_string())),
@@ -443,6 +495,8 @@ fn metadata(file: &File) -> Result<ScalarValue> {
)),
ScalarValue::Int64(Some(i64::try_from(file.meta.size).map_err(error)?)),
ScalarValue::TimestampMicrosecond(Some(file.meta.last_modified.timestamp_micros()),
None),
+ ScalarValue::Int64(Some(0)),
+
ScalarValue::Int64(Some(i64::try_from(file.meta.size).map_err(error)?)),
];
let arrays = values
.iter()
diff --git a/crates/integrations/datafusion/src/read_files/options.rs
b/crates/integrations/datafusion/src/read_files/options.rs
index 1299089d..1f62453e 100644
--- a/crates/integrations/datafusion/src/read_files/options.rs
+++ b/crates/integrations/datafusion/src/read_files/options.rs
@@ -150,6 +150,8 @@ impl Options {
"linesep",
"nullvalue",
"pathglobfilter",
+ "mode",
+ "schemaevolutionmode",
];
for name in values.keys() {
if !known.contains(&name.as_str()) {
@@ -163,20 +165,34 @@ impl Options {
let text = |key: &str| values.get(key).map(|expr| string(expr,
key)).transpose();
let flag = |key: &str| values.get(key).map(|expr| boolean(expr,
key)).transpose();
let byte = |key: &str| values.get(key).map(|expr| character(expr,
key)).transpose();
+ if text("mode")?.is_some_and(|mode|
!mode.eq_ignore_ascii_case("FAILFAST")) {
+ return Err(error("only mode => 'FAILFAST' is supported; PERMISSIVE
and DROPMALFORMED are not implemented"));
+ }
+ if text("schemaevolutionmode")?.is_some_and(|mode|
!mode.eq_ignore_ascii_case("none")) {
+ return Err(error("only schemaEvolutionMode => 'none' is
supported"));
+ }
Ok(Self {
path,
format: text("format")?.map(|v| Format::parse(&v)).transpose()?,
schema: text("schema")?,
header: flag("header")?,
delimiter: byte("sep")?,
- quote: byte("quote")?,
+ quote: text("quote")?
+ .map(|value| {
+ if value.is_empty() {
+ Ok(0)
+ } else {
+ character(values["quote"], "quote")
+ }
+ })
+ .transpose()?,
escape: Some(byte("escape")?.unwrap_or(b'\\')),
multi_line: flag("multiline")?.unwrap_or(false),
whole_text: flag("wholetext")?.unwrap_or(false),
line_sep: text("linesep")?,
null_value: text("nullvalue")?,
file_pattern: text("pathglobfilter")?
- .map(|v| Pattern::new(&v).map_err(error))
+ .map(|v| super::glob::pattern(&v))
.transpose()?,
specified: values.keys().cloned().collect(),
})
@@ -186,7 +202,7 @@ impl Options {
for name in &self.specified {
let valid = match name.as_str() {
"header" | "sep" | "quote" | "escape" | "nullvalue" => format
== Format::Csv,
- "multiline" => matches!(format, Format::Csv | Format::Json),
+ "multiline" | "mode" => matches!(format, Format::Csv |
Format::Json),
"wholetext" | "linesep" => format == Format::Text,
"schema" => !matches!(format, Format::Text | Format::Binary),
_ => true,
diff --git a/crates/integrations/datafusion/src/read_files/projection.rs
b/crates/integrations/datafusion/src/read_files/projection.rs
new file mode 100644
index 00000000..3be275ac
--- /dev/null
+++ b/crates/integrations/datafusion/src/read_files/projection.rs
@@ -0,0 +1,354 @@
+// 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 std::collections::HashMap;
+use std::ops::ControlFlow;
+use std::sync::{Arc, Mutex};
+
+use datafusion::catalog::{TableFunctionArgs, TableFunctionImpl};
+use datafusion::common::ExprSchema;
+use datafusion::dataframe::DataFrame;
+use datafusion::datasource::TableProvider;
+use datafusion::error::{DataFusionError, Result};
+use datafusion::execution::context::SQLOptions;
+use datafusion::execution::session_state::SessionState;
+use datafusion::logical_expr::{Expr, LogicalPlan};
+use datafusion::prelude::SessionContext;
+use datafusion::sql::sqlparser::ast::{
+ Cte, Ident, Query, Select, SelectItem, TableFactor, VisitMut, VisitorMut,
+};
+use datafusion::sql::sqlparser::{dialect::GenericDialect, parser::Parser};
+use datafusion::sql::unparser::Unparser;
+
+use super::{error, is_read_files, GENERATED_METADATA};
+
+/// The SQL planner has no hidden-column facility. Expand wildcards against the
+/// FROM schema before planning the real projection, excluding only generated
+/// metadata on direct read_files sources. Explicit exports through a subquery,
+/// CTE or view are ordinary visible columns.
+pub(crate) fn sql<'a>(
+ ctx: &'a SessionContext,
+ sql: &'a str,
+ options: SQLOptions,
+) -> futures::future::BoxFuture<'a, Result<DataFrame>> {
+ // Keep this additional planning layer off SQLContext's already large
future.
+ Box::pin(async move {
+ // The AST check below is authoritative; this avoids reparsing
ordinary SQL.
+ if !sql.to_ascii_lowercase().contains("read_files") {
+ return ctx.sql_with_options(sql, options).await;
+ }
+ let mut statements = Parser::parse_sql(&GenericDialect, sql)?;
+ let [statement] = statements.as_mut_slice() else {
+ return ctx.sql_with_options(sql, options).await;
+ };
+ struct FindSource;
+ impl VisitorMut for FindSource {
+ type Break = ();
+ fn pre_visit_table_factor(&mut self, factor: &mut TableFactor) ->
ControlFlow<()> {
+ let name = match factor {
+ TableFactor::Table {
+ name,
+ args: Some(_),
+ ..
+ }
+ | TableFactor::Function { name, .. } => name,
+ _ => return ControlFlow::Continue(()),
+ };
+ if is_read_files(name) {
+ ControlFlow::Break(())
+ } else {
+ ControlFlow::Continue(())
+ }
+ }
+ }
+ if statement.visit(&mut FindSource).is_continue() {
+ return ctx.sql_with_options(sql, options).await;
+ }
+ let mut state = ctx.state();
+ let Some(function) =
state.table_functions().get("read_files").cloned() else {
+ return ctx.sql_with_options(sql, options).await;
+ };
+ // Bind each source once for both schema planning and execution. The
cache
+ // belongs to this statement's cloned state, never to the shared
session.
+ state.register_udtf(
+ "read_files",
+ Arc::new(CachedSource {
+ function: function.function().clone(),
+ providers: Mutex::new(HashMap::new()),
+ }),
+ );
+ let mut rewriter = Wildcards {
+ state: state.clone(),
+ scopes: Vec::new(),
+ originals: Vec::new(),
+ rewritten: HashMap::new(),
+ };
+ if let ControlFlow::Break(error) = statement.visit(&mut rewriter) {
+ return Err(*error);
+ }
+ SessionContext::new_with_state(state)
+ .sql_with_options(&statement.to_string(), options)
+ .await
+ })
+}
+
+#[derive(Debug)]
+struct CachedSource {
+ function: Arc<dyn TableFunctionImpl>,
+ providers: Mutex<HashMap<String, Arc<dyn TableProvider>>>,
+}
+
+impl TableFunctionImpl for CachedSource {
+ fn call_with_args(&self, args: TableFunctionArgs) -> Result<Arc<dyn
TableProvider>> {
+ let key = format!("{:?}", args.exprs());
+ let mut providers = self
+ .providers
+ .lock()
+ .map_err(|_| error("source cache poisoned"))?;
+ if let Some(provider) = providers.get(&key) {
+ return Ok(provider.clone());
+ }
+ let provider = self.function.call_with_args(args)?;
+ providers.insert(key, provider.clone());
+ Ok(provider)
+ }
+}
+
+struct Wildcards {
+ state: SessionState,
+ scopes: Vec<Vec<ScopedCte>>,
+ originals: Vec<usize>,
+ rewritten: HashMap<usize, Query>,
+}
+
+#[derive(Clone)]
+struct ScopedCte {
+ cte: Cte,
+ // Identity of the original boxed AST node during this visit, never
dereferenced.
+ identity: usize,
+ recursive: bool,
+}
+
+fn direct_sources(factor: &TableFactor, state: &SessionState, sources: &mut
Vec<String>) {
+ match factor {
+ TableFactor::Table {
+ name,
+ args: Some(_),
+ alias,
+ ..
+ }
+ | TableFactor::Function { name, alias, .. }
+ if is_read_files(name) =>
+ {
+ sources.push(alias.as_ref().map_or_else(
+ || "read_files()".to_string(),
+ |alias| {
+ if alias.name.quote_style.is_none()
+ &&
state.config_options().sql_parser.enable_ident_normalization
+ {
+ alias.name.value.to_ascii_lowercase()
+ } else {
+ alias.name.value.clone()
+ }
+ },
+ ));
+ }
+ TableFactor::NestedJoin {
+ table_with_joins, ..
+ } => {
+ direct_sources(&table_with_joins.relation, state, sources);
+ for join in &table_with_joins.joins {
+ direct_sources(&join.relation, state, sources);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn aliased_source_join(factor: &TableFactor, state: &SessionState) -> bool {
+ let TableFactor::NestedJoin {
+ table_with_joins,
+ alias,
+ } = factor
+ else {
+ return false;
+ };
+ let mut sources = Vec::new();
+ direct_sources(factor, state, &mut sources);
+ (!sources.is_empty() && alias.is_some())
+ || aliased_source_join(&table_with_joins.relation, state)
+ || table_with_joins
+ .joins
+ .iter()
+ .any(|join| aliased_source_join(&join.relation, state))
+}
+
+impl Wildcards {
+ fn expand(&self, select: &mut Select) -> Result<()> {
+ if !select.projection.iter().any(|item| {
+ matches!(
+ item,
+ SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _)
+ )
+ }) {
+ return Ok(());
+ }
+ let mut sources = Vec::new();
+ for from in &select.from {
+ direct_sources(&from.relation, &self.state, &mut sources);
+ for join in &from.joins {
+ direct_sources(&join.relation, &self.state, &mut sources);
+ }
+ }
+ if sources.is_empty() {
+ return Ok(());
+ }
+ // DataFusion collapses all qualifiers under a parenthesized join alias
+ // before projecting. At that point generated and explicitly exported
+ // metadata cannot be distinguished reliably. Reject this unsupported
+ // wildcard shape instead of silently exposing or dropping a column.
+ if select.from.iter().any(|from| {
+ aliased_source_join(&from.relation, &self.state)
+ || from
+ .joins
+ .iter()
+ .any(|join| aliased_source_join(&join.relation,
&self.state))
+ }) {
+ return Err(error("wildcards on aliased parenthesized joins
containing read_files are not supported; alias the individual sources
instead"));
+ }
+ let ctes = self
+ .scopes
+ .last()
+ .unwrap()
+ .iter()
+ .map(|scoped| {
+ let mut cte = scoped.cte.clone();
+ if let Some(query) = self.rewritten.get(&scoped.identity) {
+ *cte.query = query.clone();
+ }
+ cte.to_string()
+ })
+ .collect::<Vec<_>>();
+ let prefix = if ctes.is_empty() {
+ String::new()
+ } else {
+ let recursive = if self.scopes.last().unwrap().iter().any(|cte|
cte.recursive) {
+ "RECURSIVE "
+ } else {
+ ""
+ };
+ format!("WITH {recursive}{} ", ctes.join(", "))
+ };
+ let from = select
+ .from
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(", ");
+ let mut projection = Vec::new();
+ for item in &select.projection {
+ if !matches!(
+ item,
+ SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _)
+ ) {
+ projection.push(item.clone());
+ continue;
+ }
+ let sql = format!("{prefix}SELECT {item} FROM {from}");
+ let state = self.state.clone();
+ let plan = crate::runtime::block_on_with_runtime(
+ async move { state.create_logical_plan(&sql).await },
+ "read_files: wildcard planning thread panicked",
+ )?;
+ let LogicalPlan::Projection(plan) = plan else {
+ return Err(error("expected a wildcard projection"));
+ };
+ for expr in plan.expr {
+ if let Expr::Column(column) = &expr {
+ let field = plan.input.schema().field_from_column(column)?;
+ if field.metadata().contains_key(GENERATED_METADATA)
+ && column
+ .relation
+ .as_ref()
+ .is_some_and(|name| sources.iter().any(|source|
source == name.table()))
+ {
+ continue;
+ }
+ }
+ projection.push(match expr {
+ Expr::Alias(alias) => SelectItem::ExprWithAlias {
+ expr: Unparser::default().expr_to_sql(&alias.expr)?,
+ alias: Ident::with_quote('"', alias.name),
+ },
+ expr =>
SelectItem::UnnamedExpr(Unparser::default().expr_to_sql(&expr)?),
+ });
+ }
+ }
+ select.projection = projection;
+ Ok(())
+ }
+}
+
+impl VisitorMut for Wildcards {
+ type Break = Box<DataFusionError>;
+
+ fn pre_visit_query(&mut self, query: &mut Query) ->
ControlFlow<Self::Break> {
+ let original = query as *const Query as usize;
+ let mut scope = self.scopes.last().cloned().unwrap_or_default();
+ // A nonrecursive CTE can refer only to preceding CTEs. In particular,
+ // do not plan its own original wildcard while expanding its body.
+ if let Some(index) = scope.iter().position(|cte| cte.identity ==
original) {
+ scope.truncate(index + usize::from(scope[index].recursive));
+ }
+ self.originals.push(original);
+ if let Some(with) = &query.with {
+ for cte in &with.cte_tables {
+ let normalizer =
datafusion::sql::planner::IdentNormalizer::new(
+ self.state
+ .config_options()
+ .sql_parser
+ .enable_ident_normalization,
+ );
+ scope.retain(|outer| {
+ normalizer.normalize(outer.cte.alias.name.clone())
+ != normalizer.normalize(cte.alias.name.clone())
+ });
+ scope.push(ScopedCte {
+ cte: cte.clone(),
+ identity: cte.query.as_ref() as *const Query as usize,
+ recursive: with.recursive,
+ });
+ }
+ }
+ self.scopes.push(scope);
+ ControlFlow::Continue(())
+ }
+
+ fn post_visit_select(&mut self, select: &mut Select) ->
ControlFlow<Self::Break> {
+ match self.expand(select) {
+ Ok(()) => ControlFlow::Continue(()),
+ Err(error) => ControlFlow::Break(Box::new(error)),
+ }
+ }
+
+ fn post_visit_query(&mut self, query: &mut Query) ->
ControlFlow<Self::Break> {
+ self.scopes.pop();
+ self.rewritten
+ .insert(self.originals.pop().unwrap(), query.clone());
+ ControlFlow::Continue(())
+ }
+}
diff --git a/crates/integrations/datafusion/src/read_files/raw.rs
b/crates/integrations/datafusion/src/read_files/raw.rs
index a9034d85..5994820d 100644
--- a/crates/integrations/datafusion/src/read_files/raw.rs
+++ b/crates/integrations/datafusion/src/read_files/raw.rs
@@ -34,7 +34,7 @@ use datafusion::datasource::file_format::csv::CsvFormat;
use datafusion::datasource::{TableProvider, TableType};
use datafusion::error::Result;
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
-use datafusion::logical_expr::{lit, Expr};
+use datafusion::logical_expr::Expr;
use datafusion::object_store::{ObjectStore, ObjectStoreExt};
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
@@ -46,7 +46,7 @@ use datafusion::prelude::SessionContext;
use futures::{stream, StreamExt, TryStreamExt};
use serde_json::Value;
-use super::{error, metadata, File, Format, Options};
+use super::{error, metadata_expr, File, Format, Options};
fn json_records(bytes: &[u8]) -> Result<Vec<Value>> {
match serde_json::from_slice::<Value>(bytes)
@@ -141,6 +141,13 @@ pub(super) async fn infer_csv_schema(
break;
}
}
+ if options.header == Some(false) {
+ fields = fields
+ .iter()
+ .enumerate()
+ .map(|(index, field)|
Arc::new(field.as_ref().clone().with_name(format!("_c{index}"))))
+ .collect();
+ }
Ok(Arc::new(Schema::new(fields)))
}
@@ -311,7 +318,7 @@ pub(super) async fn provider(
let frame = if source_metadata {
frame
} else {
- frame.with_column("_metadata", lit(metadata(&file)?))?
+ frame.with_column("_metadata", metadata_expr(&file)?)?
};
plans.push(frame.into_unoptimized_plan());
}
@@ -934,6 +941,7 @@ impl CsvInput {
#[cfg(test)]
mod tests {
use super::*;
+ use datafusion::logical_expr::lit;
#[test]
fn csv_eof_checks_quote_and_escape_state_across_chunks() {
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index d4316527..b676d671 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -782,12 +782,12 @@ impl SQLContext {
.map_err(|error| {
DataFusionError::Plan(format!("Invalid view
SQL: {error}"))
})?;
- self.ctx
- .sql_with_options(
- &Statement::CreateView(bound_view).to_string(),
- options,
- )
- .await
+ crate::read_files::sql(
+ &self.ctx,
+ &Statement::CreateView(bound_view).to_string(),
+ options,
+ )
+ .await
}
}
}
@@ -957,11 +957,9 @@ impl SQLContext {
¤t_database,
)
.await?;
- self.ctx
- .sql_with_options(&expanded.to_string(), options)
- .await
+ crate::read_files::sql(&self.ctx, &expanded.to_string(),
options).await
}
- _ => self.ctx.sql_with_options(sql, options).await,
+ _ => crate::read_files::sql(&self.ctx, sql, options).await,
}
}
@@ -1053,7 +1051,7 @@ impl SQLContext {
¤t_database,
)
.await?;
- self.ctx.sql_with_options(&expanded, sql_options).await
+ crate::read_files::sql(&self.ctx, &expanded, sql_options).await
}
async fn time_travel_provider(
@@ -1355,7 +1353,7 @@ impl SQLContext {
if let Some(query) = &ct.query {
// CREATE TEMPORARY TABLE ... AS SELECT ...
let query_sql = query.to_string();
- let df = self.ctx.sql_with_options(&query_sql, sql_options).await?;
+ let df = crate::read_files::sql(&self.ctx, &query_sql,
sql_options).await?;
let schema = df.schema().inner().clone();
let batches = df.collect().await?;
@@ -2029,7 +2027,7 @@ impl SQLContext {
async fn handle_merge_into(&self, merge: &Merge, options: SQLOptions) ->
DFResult<DataFrame> {
let merge = self.normalize_merge_into(merge).await?;
- self.ctx.sql_with_options(&merge.to_string(), options).await
+ crate::read_files::sql(&self.ctx, &merge.to_string(), options).await
}
async fn normalize_merge_into(&self, merge: &Merge) -> DFResult<Merge> {
@@ -2191,10 +2189,7 @@ impl SQLContext {
let source = insert.source.as_ref().ok_or_else(|| {
DataFusionError::Plan("INSERT OVERWRITE requires a source
query".into())
})?;
- let df = self
- .ctx
- .sql_with_options(&source.to_string(), sql_options)
- .await?;
+ let df = crate::read_files::sql(&self.ctx, &source.to_string(),
sql_options).await?;
let all_fields = table.schema().fields();
let non_static_fields: Vec<&PaimonDataField> = all_fields
@@ -2413,9 +2408,7 @@ impl SQLContext {
&state.config_options().catalog.default_schema,
)
.await?;
- self.ctx
- .sql_with_options(&expanded_query, sql_options)
- .await
+ crate::read_files::sql(&self.ctx, &expanded_query,
sql_options).await
})
.await?;
let logical_plan = df.logical_plan().clone();
diff --git a/crates/integrations/datafusion/tests/read_files_access.rs
b/crates/integrations/datafusion/tests/read_files_access.rs
index 9b7c253a..5fd6a5eb 100644
--- a/crates/integrations/datafusion/tests/read_files_access.rs
+++ b/crates/integrations/datafusion/tests/read_files_access.rs
@@ -220,7 +220,9 @@ async fn
planned_stores_are_captured_and_adls_containers_remain_separate() {
ctx.ctx()
.runtime_env()
.register_object_store(&url, original);
- let planned = ctx.sql("SELECT value FROM
read_files('abfss://[email protected]/imports/data.txt',
format => 'text')").await.unwrap();
+ let sql = "SELECT * FROM
read_files('abfss://[email protected]/imports/data.txt',
format => 'text')";
+ let planned = ctx.sql(sql).await.unwrap();
+ assert_eq!(planned.schema().fields().len(), 1);
let replacement = Arc::new(InMemory::new());
replacement
.put(&Path::from("imports/data.txt"), "replacement".into())
@@ -237,6 +239,14 @@ async fn
planned_stores_are_captured_and_adls_containers_remain_separate() {
.flatten(),
Some("original")
);
+ let replacement = ctx.sql(sql).await.unwrap().collect().await.unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(replacement[0].column(0), 0)
+ .unwrap()
+ .try_as_str()
+ .flatten(),
+ Some("replacement")
+ );
assert!(ctx.sql("SELECT * FROM
read_files('abfss://[email protected]/imports/data.txt',
format => 'text')").await.is_err());
}
diff --git a/crates/integrations/datafusion/tests/read_files_behavior.rs
b/crates/integrations/datafusion/tests/read_files_behavior.rs
new file mode 100644
index 00000000..6cba4097
--- /dev/null
+++ b/crates/integrations/datafusion/tests/read_files_behavior.rs
@@ -0,0 +1,418 @@
+// 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 std::sync::Arc;
+
+use datafusion::common::ScalarValue;
+use datafusion::object_store::{memory::InMemory, path::Path, ObjectStoreExt};
+use paimon_datafusion::SQLContext;
+
+async fn context(files: &[(&str, &[u8])]) -> SQLContext {
+ let store = Arc::new(InMemory::new());
+ for (path, bytes) in files {
+ store
+ .put(&Path::parse(*path).unwrap(), bytes.to_vec().into())
+ .await
+ .unwrap();
+ }
+ let ctx = SQLContext::new();
+ ctx.ctx()
+ .runtime_env()
+ .register_object_store(&url::Url::parse("memory://files").unwrap(),
store);
+ ctx
+}
+
+async fn columns(ctx: &SQLContext, sql: &str) -> Vec<String> {
+ let frame = ctx.sql(sql).await.unwrap();
+ let names = frame
+ .schema()
+ .fields()
+ .iter()
+ .map(|f| f.name().clone())
+ .collect();
+ frame.collect().await.unwrap();
+ names
+}
+
+async fn rows(ctx: &SQLContext, sql: &str) -> Vec<Vec<ScalarValue>> {
+ ctx.sql(sql)
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap()
+ .iter()
+ .flat_map(|batch| {
+ (0..batch.num_rows())
+ .map(|row| {
+ batch
+ .columns()
+ .iter()
+ .map(|column| ScalarValue::try_from_array(column,
row).unwrap())
+ .collect()
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn generated_metadata_is_hidden_from_wildcards_but_can_be_selected() {
+ let ctx = context(&[
+ ("data.csv", b"id,name\n1,Alice\n"),
+ ("data.json", b"{\"id\":1,\"name\":\"Alice\"}\n"),
+ ("data.txt", b"hello\n"),
+ ])
+ .await;
+ for (file, options, expected) in [
+ ("data.csv", "", vec!["id", "name"]),
+ ("data.json", "", vec!["id", "name"]),
+ ("data.txt", "", vec!["value"]),
+ (
+ "data.txt",
+ ", format => 'binaryFile'",
+ vec!["path", "modificationTime", "length", "content"],
+ ),
+ ] {
+ for star in ["*", "f.*"] {
+ let sql = format!("SELECT {star} FROM
read_files('memory://files/{file}'{options}) f");
+ assert_eq!(columns(&ctx, &sql).await, expected, "{sql}");
+ }
+ let sql =
+ format!("SELECT *, _metadata FROM
read_files('memory://files/{file}'{options}) f");
+ let mut expected = expected;
+ expected.push("_metadata");
+ assert_eq!(columns(&ctx, &sql).await, expected);
+ let values = rows(&ctx, &format!("SELECT _metadata.file_name,
_metadata.file_block_start, _metadata.file_block_length FROM
read_files('memory://files/{file}'{options})")).await;
+ assert_eq!(values[0][0], ScalarValue::Utf8(Some(file.into())));
+ assert_eq!(values[0][1], ScalarValue::Int64(Some(0)));
+ assert!(matches!(values[0][2], ScalarValue::Int64(Some(size)) if size
> 0));
+ }
+}
+
+#[tokio::test]
+async fn source_metadata_and_explicitly_exported_metadata_stay_visible() {
+ let mut ctx = context(&[
+ ("data.json", b"{\"id\":1,\"_metadata\":\"user data\"}\n"),
+ ("data.txt", b"hello\n"),
+ ])
+ .await;
+ assert_eq!(
+ columns(&ctx, "SELECT * FROM
read_files('memory://files/data.json')").await,
+ ["_metadata", "id"]
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT _metadata FROM read_files('memory://files/data.json')"
+ )
+ .await,
+ [vec![ScalarValue::Utf8(Some("user data".into()))]]
+ );
+ for sql in [
+ "SELECT * FROM (SELECT *, _metadata FROM
read_files('memory://files/data.txt')) v",
+ "WITH v AS (SELECT *, _metadata FROM
read_files('memory://files/data.txt')) SELECT * FROM v",
+ ] {
+ assert_eq!(columns(&ctx, sql).await, ["value", "_metadata"]);
+ }
+ for sql in [
+ "WITH v(value) AS (SELECT * FROM
read_files('memory://files/data.txt')) SELECT * FROM v",
+ "WITH a(value) AS (SELECT * FROM
read_files('memory://files/data.txt')), b AS (SELECT f.* FROM
read_files('memory://files/data.txt') f CROSS JOIN a) SELECT * FROM b",
+ ] {
+ assert_eq!(columns(&ctx, sql).await, ["value"]);
+ }
+ assert_eq!(columns(&ctx, "SELECT * FROM
read_files('memory://files/data.txt') f CROSS JOIN (SELECT 'user' AS _metadata)
t").await, ["value", "_metadata"]);
+ assert_eq!(columns(&ctx, "SELECT f.*, t.* FROM
read_files('memory://files/data.txt') f CROSS JOIN (SELECT 'user' AS _metadata)
t").await, ["value", "_metadata"]);
+ let warehouse = tempfile::tempdir().unwrap();
+ let mut options = paimon::Options::new();
+ options.set(
+ paimon::CatalogOptions::WAREHOUSE,
+ warehouse.path().to_str().unwrap(),
+ );
+ ctx.register_catalog(
+ "paimon",
+ Arc::new(paimon::FileSystemCatalog::new(options).unwrap()),
+ )
+ .await
+ .unwrap();
+ ctx.sql("CREATE TEMPORARY VIEW files AS SELECT * FROM
read_files('memory://files/data.txt')")
+ .await
+ .unwrap();
+ assert_eq!(columns(&ctx, "SELECT * FROM files").await, ["value"]);
+ ctx.sql(
+ "CREATE TEMPORARY TABLE imported AS SELECT * FROM
read_files('memory://files/data.txt')",
+ )
+ .await
+ .unwrap();
+ rows(
+ &ctx,
+ "INSERT INTO imported SELECT * FROM
read_files('memory://files/data.txt')",
+ )
+ .await;
+ assert_eq!(
+ rows(&ctx, "SELECT count(*) FROM imported").await,
+ [vec![ScalarValue::Int64(Some(2))]]
+ );
+}
+
+#[tokio::test]
+async fn headerless_csv_inference_uses_spark_column_names() {
+ let ctx = context(&[("data.csv", b"1,Alice\n2,Bob\n")]).await;
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT * FROM read_files('memory://files/data.csv', header =>
false)"
+ )
+ .await,
+ ["_c0", "_c1"]
+ );
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT _c1 FROM read_files('memory://files/data.csv', header =>
false) ORDER BY _c0"
+ )
+ .await,
+ [
+ vec![ScalarValue::Utf8(Some("Alice".into()))],
+ vec![ScalarValue::Utf8(Some("Bob".into()))]
+ ]
+ );
+}
+
+#[tokio::test]
+async fn glob_negation_uses_hadoop_character_classes() {
+ let ctx = context(&[("a.txt", b"a"), ("b.txt", b"b"), ("^.txt",
b"caret")]).await;
+ for path in ["memory://files/[^a].txt", "memory://files/"] {
+ let options = if path.ends_with('/') {
+ ", format => 'text', pathGlobFilter => '[^a].txt'"
+ } else {
+ ""
+ };
+ assert_eq!(
+ rows(
+ &ctx,
+ &format!("SELECT value FROM read_files('{path}'{options})
ORDER BY value")
+ )
+ .await,
+ [
+ vec![ScalarValue::Utf8(Some("b".into()))],
+ vec![ScalarValue::Utf8(Some("caret".into()))]
+ ]
+ );
+ }
+}
+
+#[tokio::test]
+async fn aliases_and_wildcard_options_preserve_visible_columns() {
+ let ctx = context(&[
+ ("data.csv", b"id,name\n1,Alice\n"),
+ ("data.txt", b"hello\n"),
+ ])
+ .await;
+ for sql in [
+ "SELECT * FROM \"read_files\"('memory://files/data.txt')",
+ "SELECT * FROM `read_files`('memory://files/data.txt')",
+ "SELECT * FROM read_files('memory://files/data.txt') f(value)",
+ "SELECT f.* FROM read_files('memory://files/data.txt') f(value)",
+ "SELECT \"file rows\".* FROM read_files('memory://files/data.txt') AS
\"file rows\"",
+ "WITH RECURSIVE t(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM t WHERE
n<2) SELECT f.* FROM read_files('memory://files/data.txt') f CROSS JOIN t",
+ ] {
+ assert_eq!(columns(&ctx, sql).await, ["value"], "{sql}");
+ }
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT * EXCEPT (id) FROM read_files('memory://files/data.csv')"
+ )
+ .await,
+ ["name"]
+ );
+ assert_eq!(columns(&ctx, "SELECT f.* EXCEPT (name), _metadata.file_name AS
file_name FROM read_files('memory://files/data.csv') f").await, ["id",
"file_name"]);
+ assert_eq!(
+ rows(
+ &ctx,
+ "SELECT v FROM read_files('memory://files/data.txt') f(v)"
+ )
+ .await,
+ [vec![ScalarValue::Utf8(Some("hello".into()))]]
+ );
+}
+
+#[tokio::test]
+async fn wildcard_replacements_preserve_aliases_for_outer_queries_and_ctas() {
+ let mut ctx = context(&[
+ ("data.txt", b"hello\n"),
+ ("mixed.json", b"{\"Mixed Name\":\"hello\"}\n"),
+ ])
+ .await;
+ for star in ["*", "f.*"] {
+ let query = format!("SELECT {star} REPLACE (upper(value) AS value)
FROM read_files('memory://files/data.txt') f");
+ assert_eq!(columns(&ctx, &query).await, ["value"]);
+ let values = rows(&ctx, &format!("SELECT q.value FROM ({query})
q")).await;
+ assert_eq!(values.len(), 1);
+ assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO"));
+ }
+ let query = r#"SELECT * REPLACE (upper("Mixed Name") AS "Mixed Name") FROM
read_files('memory://files/mixed.json')"#;
+ assert_eq!(columns(&ctx, query).await, ["Mixed Name"]);
+ let values = rows(&ctx, &format!(r#"SELECT q."Mixed Name" FROM ({query})
q"#)).await;
+ assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO"));
+
+ ctx.sql("CREATE VIEW datafusion.public.replaced_view AS SELECT * REPLACE
(upper(value) AS value) FROM
read_files('memory://files/data.txt')").await.unwrap();
+ assert_eq!(
+ columns(&ctx, "SELECT * FROM datafusion.public.replaced_view").await,
+ ["value"]
+ );
+ let values = rows(&ctx, "SELECT value FROM
datafusion.public.replaced_view").await;
+ assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO"));
+
+ let warehouse = tempfile::tempdir().unwrap();
+ let mut options = paimon::Options::new();
+ options.set(
+ paimon::CatalogOptions::WAREHOUSE,
+ warehouse.path().to_str().unwrap(),
+ );
+ ctx.register_catalog(
+ "paimon",
+ Arc::new(paimon::FileSystemCatalog::new(options).unwrap()),
+ )
+ .await
+ .unwrap();
+ ctx.sql("CREATE TEMPORARY TABLE replaced AS SELECT * REPLACE (upper(value)
AS value) FROM read_files('memory://files/data.txt')").await.unwrap();
+ assert_eq!(columns(&ctx, "SELECT * FROM replaced").await, ["value"]);
+ let values = rows(&ctx, "SELECT value FROM replaced").await;
+ assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO"));
+}
+
+#[tokio::test]
+async fn distinct_star_uses_data_columns_and_parquet_hides_metadata() {
+ use datafusion::arrow::array::{Int64Array, RecordBatch};
+ use datafusion::arrow::datatypes::{DataType, Field, Schema};
+ let batch = RecordBatch::try_new(
+ Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])),
+ vec![Arc::new(Int64Array::from(vec![1]))],
+ )
+ .unwrap();
+ let mut writer =
+ parquet::arrow::ArrowWriter::try_new(Vec::new(), batch.schema(),
None).unwrap();
+ writer.write(&batch).unwrap();
+ let bytes = writer.into_inner().unwrap();
+ let ctx = context(&[
+ ("duplicates/a.txt", b"same\n"),
+ ("duplicates/b.txt", b"same\n"),
+ ("data.parquet", &bytes),
+ ])
+ .await;
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT * FROM read_files('memory://files/data.parquet')"
+ )
+ .await,
+ ["id"]
+ );
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT *, _metadata FROM
read_files('memory://files/data.parquet')"
+ )
+ .await,
+ ["id", "_metadata"]
+ );
+ assert_eq!(rows(&ctx, "SELECT count(*) FROM (SELECT DISTINCT * FROM
read_files('memory://files/duplicates/')) v").await,
[vec![ScalarValue::Int64(Some(1))]]);
+ assert_eq!(rows(&ctx, "SELECT count(DISTINCT _metadata.file_name) FROM
read_files('memory://files/duplicates/')").await,
[vec![ScalarValue::Int64(Some(2))]]);
+ let error = ctx.sql("SELECT * FROM
(read_files('memory://files/duplicates/a.txt') f CROSS JOIN (SELECT 1 AS n) t)
j").await.unwrap_err().to_string();
+ assert!(
+ error.contains("alias the individual sources instead"),
+ "{error}"
+ );
+}
+
+#[tokio::test]
+async fn parquet_source_columns_do_not_inherit_generated_metadata_visibility()
{
+ use datafusion::arrow::array::{RecordBatch, StringArray};
+ use datafusion::arrow::datatypes::{DataType, Field, Schema};
+ let field = Field::new("_metadata", DataType::Utf8, false).with_metadata(
+ std::collections::HashMap::from([
+ ("paimon.read_files.generated_metadata".into(), "true".into()),
+ ("owner".into(), "user".into()),
+ ]),
+ );
+ let batch = RecordBatch::try_new(
+ Arc::new(Schema::new(vec![field])),
+ vec![Arc::new(StringArray::from(vec!["saved user metadata"]))],
+ )
+ .unwrap();
+ let mut writer =
+ parquet::arrow::ArrowWriter::try_new(Vec::new(), batch.schema(),
None).unwrap();
+ writer.write(&batch).unwrap();
+ let bytes = writer.into_inner().unwrap();
+ let ctx = context(&[("data.parquet", &bytes)]).await;
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT * FROM read_files('memory://files/data.parquet')"
+ )
+ .await,
+ ["_metadata"]
+ );
+ assert_eq!(
+ columns(
+ &ctx,
+ "SELECT * FROM read_files('memory://files/data.parquet') f(saved)"
+ )
+ .await,
+ ["saved"]
+ );
+ let values = rows(
+ &ctx,
+ "SELECT _metadata FROM read_files('memory://files/data.parquet')",
+ )
+ .await;
+ assert_eq!(
+ values[0][0].try_as_str().flatten(),
+ Some("saved user metadata")
+ );
+}
+
+#[tokio::test]
+async fn empty_quote_disables_csv_quoting_and_strict_mode_is_explicit() {
+ let ctx = context(&[
+ ("data.csv", b"\"literal\",tail\n"),
+ ("bad.json", b"not JSON\n"),
+ ])
+ .await;
+ let values = rows(&ctx, "SELECT v FROM
read_files('memory://files/data.csv', schema => 'v STRING, w STRING', quote =>
'', mode => 'FAILFAST', schemaEvolutionMode => 'none')").await;
+ assert_eq!(values.len(), 1);
+ assert_eq!(values[0][0].try_as_str().flatten(), Some("\"literal\""));
+ assert!(ctx
+ .sql("SELECT * FROM read_files('memory://files/bad.json', mode =>
'FAILFAST')")
+ .await
+ .is_err());
+ for options in [
+ "mode => 'PERMISSIVE'",
+ "mode => 'DROPMALFORMED'",
+ "pathGlobFilter => '{a,b}.csv'",
+ "schemaEvolutionMode => 'rescue'",
+ ] {
+ assert!(ctx
+ .sql(&format!(
+ "SELECT * FROM read_files('memory://files/data.csv',
{options})"
+ ))
+ .await
+ .is_err());
+ }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 8c3bd1e5..13fdac2f 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -196,25 +196,30 @@ Supported formats and options:
| Format | Behavior and options |
| --- | --- |
-| `csv` | Infer columns or use a DDL `schema`; `header`, `sep`/`delimiter`,
`quote`, `escape`, `nullValue`, `multiLine`. Without `schema`, headers default
to enabled; with `schema`, headers default to disabled. The default escape is
backslash. Quoted line breaks require `multiLine => true`. |
+| `csv` | Infer columns or use a DDL `schema`; `header`, `sep`/`delimiter`,
`quote`, `escape`, `nullValue`, `multiLine`, `mode => 'FAILFAST'`. Without
`schema`, headers default to enabled; with `schema`, headers default to
disabled. Headerless inference names columns `_c0`, `_c1`, etc. The default
escape is backslash; `quote => ''` disables quoting. Quoted line breaks require
`multiLine => true`. |
| `parquet` | Native Parquet schema, column pruning and predicate pushdown;
optional `schema`. |
-| `json` | One object per line by default, including `.jsonl`/`.ndjson` files.
`multiLine => true` reads one object or an array of objects per file. Optional
`schema`. |
+| `json` | One object per line by default, including `.jsonl`/`.ndjson` files.
`multiLine => true` reads one object or an array of objects per file. Optional
`schema` and `mode => 'FAILFAST'`. |
| `text` | One UTF-8 line per `value STRING` row; default separators are LF,
CRLF and CR. `lineSep` sets a separator; `wholeText => true` reads each file as
one row, including empty files. |
| `binaryFile` | One row per file: `path STRING`, `modificationTime
TIMESTAMP`, `length BIGINT`, `content BINARY`. Selecting only metadata avoids
reading file contents. |
Options are named, case-insensitive and must evaluate to constants. Duplicate,
unknown and format-inappropriate options are rejected. `format` can be omitted
for recognized extensions; mixed formats require an explicit format.
Directories
-are scanned recursively. Path globs support `*`, `?` and character classes.
+are scanned recursively. Path globs support `*`, `?` and character classes,
+including Hadoop-style negation `[^a]`. Unsupported brace expansion is
rejected.
Each wildcard matches one path component; a matched directory includes its
descendants.
`pathGlobFilter` (alias `fileNamePattern`) filters leaf names. Hidden path
components beginning with `.` or `_` are skipped. No matching files is an
error.
-Every source row exposes `_metadata` with `file_path`, `file_name`, `file_size`
-and `file_modification_time`, unless the data already contains a column named
-`_metadata`, which takes precedence. Unlike Databricks, the generated struct is
-currently included in `SELECT *`; select data columns explicitly when a stable
-output schema is needed.
+Every source row exposes `_metadata` with `file_path`, `file_name`,
`file_size`,
+`file_modification_time`, `file_block_start` and `file_block_length`, unless
the
+data already contains a column named `_metadata`, which takes precedence.
+`SQLContext.sql` excludes generated metadata from `SELECT *` and `alias.*`;
+select `_metadata` explicitly to include it. Metadata explicitly exported by
+a subquery, CTE or view remains an ordinary visible column. Each file is
exposed
+as one logical block with offset zero and length equal to the file size.
+Wildcard selection through an alias on a parenthesized join containing
+`read_files` is unsupported; alias the individual sources instead.
With DataFusion's default identifier normalization, quote the camel-case binary
column as `"modificationTime"` when selecting it explicitly.
CSV and Parquet inference uses DataFusion's inference limits. NDJSON inference
@@ -226,8 +231,13 @@ This is a supported subset of [Databricks
`read_files`](https://docs.databricks.
It does not add the `read_csv`, `read_parquet`, `read_json`, `read_text`,
`read_blob`
or `read_ndjson` aliases. Hive partition inference, compressed text inputs,
schema
hints/rescued-data modes, streaming ingestion, Avro, ORC, XML and
service-specific
-connections are not implemented. Malformed input fails rather than being
rescued
-or silently dropped. Whole-file text, binary content and multi-line JSON
+connections are not implemented. CSV/JSON currently use strict parsing,
including
+when `mode` is omitted; this differs from Databricks' default `PERMISSIVE`
mode.
+Use `mode => 'FAILFAST', schemaEvolutionMode => 'none'` for an explicit
strict-reading
+contract with rescued data disabled. Only `none` is supported for schema
evolution.
+Other parsing modes are rejected; malformed input fails rather than being
rescued or silently
+dropped. JSON single-quoted strings and non-finite numbers are also
unsupported.
+Whole-file text, binary content and multi-line JSON
materialize a file in memory; ordinary text and CSV are streamed in batches.
### REST Catalog Views and SQL Functions