Skip to content

Align input logical plan schema with target table schema for CTAs/INSERT #1105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions crates/core-executor/src/datafusion/type_planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,16 @@ impl TypePlanner for CustomTypePlanner {
SQLDataType::JSON => Ok(Some(DataType::Utf8)),
SQLDataType::Custom(a, b) => match a.to_string().to_uppercase().as_str() {
"VARIANT" => Ok(Some(DataType::Utf8)),
"TIMESTAMP_NTZ" => {
"TIMESTAMP_NTZ" | "TIMESTAMP_LTZ" | "TIMESTAMP_TZ" => {
let parsed_b: Option<u64> = b.iter().next().and_then(|s| s.parse().ok());
match parsed_b {
Some(0) => Ok(Some(DataType::Timestamp(TimeUnit::Second, None))),
Some(3) => Ok(Some(DataType::Timestamp(TimeUnit::Millisecond, None))),
// We coerce nanoseconds to microseconds as Apache Iceberg v2 doesn't support nanosecond precision
Some(6 | 9) => Ok(Some(DataType::Timestamp(TimeUnit::Microsecond, None))),
_ => not_impl_err!("Unsupported SQL TIMESTAMP_NTZ precision {parsed_b:?}"),
None | Some(6 | 9) => {
Ok(Some(DataType::Timestamp(TimeUnit::Microsecond, None)))
}
_ => not_impl_err!("Unsupported SQL TIMESTAMP_* precision {parsed_b:?}"),
}
}
"NUMBER" => {
Expand Down
35 changes: 31 additions & 4 deletions crates/core-executor/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ use core_metastore::{
TableIdent as MetastoreTableIdent,
};
use datafusion::arrow::array::{Int64Array, RecordBatch};
use datafusion::arrow::datatypes::{DataType, Field, Schema as ArrowSchema};
use datafusion::arrow::datatypes::{DataType, Field, Schema as ArrowSchema, SchemaRef};
use datafusion::catalog::MemoryCatalogProvider;
use datafusion::catalog::{CatalogProvider, SchemaProvider};
use datafusion::datasource::default_table_source::provider_as_source;
use datafusion::execution::session_state::SessionContextProvider;
use datafusion::execution::session_state::SessionState;
use datafusion::logical_expr::col;
use datafusion::logical_expr::{LogicalPlan, TableSource};
use datafusion::prelude::CsvReadOptions;
use datafusion::scalar::ScalarValue;
Expand All @@ -37,7 +38,7 @@ use datafusion_common::{
DataFusionError, ResolvedTableReference, TableReference, plan_datafusion_err,
};
use datafusion_expr::logical_plan::dml::{DmlStatement, InsertOp, WriteOp};
use datafusion_expr::{CreateMemoryTable, DdlStatement};
use datafusion_expr::{CreateMemoryTable, DdlStatement, Expr as DFExpr, Projection, TryCast};
use datafusion_iceberg::catalog::catalog::IcebergCatalog;
use df_catalog::catalog::CachingCatalog;
use df_catalog::information_schema::session_params::SessionProperty;
Expand Down Expand Up @@ -544,12 +545,12 @@ impl UserQuery {
.ok_or(ExecutionError::TableProviderNotFound {
table_name: name.table().to_string(),
})?;

let schema = target_table.schema();
let insert_plan = LogicalPlan::Dml(DmlStatement::new(
name,
provider_as_source(target_table),
WriteOp::Insert(InsertOp::Append),
input,
cast_input_to_target_schema(input, &schema)?,
));
return self.execute_logical_plan(insert_plan).await;
}
Expand Down Expand Up @@ -1940,3 +1941,29 @@ fn apply_show_filters(sql: String, filters: &[String]) -> String {
format!("{} WHERE {}", sql, filters.join(" AND "))
}
}

pub fn cast_input_to_target_schema(
input: Arc<LogicalPlan>,
target_schema: &SchemaRef,
) -> ExecutionResult<Arc<LogicalPlan>> {
let input_schema = input.schema().as_arrow();
let mut projections: Vec<DFExpr> = Vec::with_capacity(target_schema.fields().len());

for field in target_schema.fields() {
let name = field.name();
let data_type = field.data_type();
let input_field = input_schema
.field_with_name(name)
.context(ex_error::ArrowSnafu)?;
if input_field.data_type() == data_type {
projections.push(col(name));
} else {
projections.push(DFExpr::TryCast(TryCast::new(
Box::new(col(name)),
data_type.clone(),
)));
}
}
let projection = Projection::try_new(projections, input).context(ex_error::DataFusionSnafu)?;
Ok(Arc::new(LogicalPlan::Projection(projection)))
}
17 changes: 17 additions & 0 deletions crates/core-executor/src/tests/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,23 @@ test_query!(
"CREATE TABLE embucket.public.ts_table (ts TIMESTAMP_NTZ(9)) as VALUES ('2025-04-09T21:11:23');"
);

// CREATE TABLE with timestamp types
test_query!(
create_table_with_timestamps,
"SELECT * FROM timestamps",
setup_queries = [
"CREATE TABLE timestamps (
ntz TIMESTAMP_NTZ, ntz_0 TIMESTAMP_NTZ(0), ntz_3 TIMESTAMP_NTZ(3), ntz_6 TIMESTAMP_NTZ(6), ntz_9 TIMESTAMP_NTZ(9),
ltz TIMESTAMP_LTZ, ltz_0 TIMESTAMP_LTZ(0), ltz_3 TIMESTAMP_LTZ(3), ltz_6 TIMESTAMP_LTZ(6), ltz_9 TIMESTAMP_LTZ(9),
tz TIMESTAMP_TZ, tz_0 TIMESTAMP_TZ(0), tz_3 TIMESTAMP_TZ(3), tz_6 TIMESTAMP_TZ(6), tz_9 TIMESTAMP_TZ(9))
as VALUES (
'2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23',
'2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23',
'2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23'
);"
]
);

test_query!(
create_table_and_insert,
"SELECT * FROM embucket.public.test",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
source: crates/core-executor/src/tests/query.rs
description: "\"CREATE OR REPLACE TABLE t1 AS\n SELECT * FROM (VALUES\n ('2021-03-02 15:55:18.539000'::TIMESTAMP)\n ) AS t(start_tstamp);\""
---
Ok(
[
"+-------+",
"| count |",
"+-------+",
"| 1 |",
"+-------+",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
source: crates/core-executor/src/tests/query.rs
description: "\"SELECT * FROM timestamps\""
info: "Setup queries: CREATE TABLE timestamps (\n ntz TIMESTAMP_NTZ, ntz_0 TIMESTAMP_NTZ(0), ntz_3 TIMESTAMP_NTZ(3), ntz_6 TIMESTAMP_NTZ(6), ntz_9 TIMESTAMP_NTZ(9),\n ltz TIMESTAMP_LTZ, ltz_0 TIMESTAMP_LTZ(0), ltz_3 TIMESTAMP_LTZ(3), ltz_6 TIMESTAMP_LTZ(6), ltz_9 TIMESTAMP_LTZ(9),\n tz TIMESTAMP_TZ, tz_0 TIMESTAMP_TZ(0), tz_3 TIMESTAMP_TZ(3), tz_6 TIMESTAMP_TZ(6), tz_9 TIMESTAMP_TZ(9))\n as VALUES (\n '2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23',\n '2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23',\n '2025-04-09T21:11:23','2025-04-09T22:11:23','2025-04-09T23:11:23','2025-04-09T20:11:23','2025-04-09T19:11:23'\n );"
---
Ok(
[
"+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+",
"| ntz | ntz_0 | ntz_3 | ntz_6 | ntz_9 | ltz | ltz_0 | ltz_3 | ltz_6 | ltz_9 | tz | tz_0 | tz_3 | tz_6 | tz_9 |",
"+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+",
"| 2025-04-09T21:11:23 | 2025-04-09T22:11:23 | 2025-04-09T23:11:23 | 2025-04-09T20:11:23 | 2025-04-09T19:11:23 | 2025-04-09T21:11:23 | 2025-04-09T22:11:23 | 2025-04-09T23:11:23 | 2025-04-09T20:11:23 | 2025-04-09T19:11:23 | 2025-04-09T21:11:23 | 2025-04-09T22:11:23 | 2025-04-09T23:11:23 | 2025-04-09T20:11:23 | 2025-04-09T19:11:23 |",
"+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+",
],
)