adriangb commented on code in PR #21322: URL: https://github.com/apache/datafusion/pull/21322#discussion_r3037082870
########## datafusion/functions/src/core/cast_to_type.rs: ########## @@ -0,0 +1,147 @@ +// 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. + +//! [`CastToTypeFunc`]: Implementation of the `cast_to_type` + +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::{ + Result, datatype::DataTypeExt, internal_err, utils::take_function_args, +}; +use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; +use datafusion_expr::{ + Coercion, ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs, + ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, +}; +use datafusion_macros::user_doc; + +/// Casts the first argument to the data type of the second argument. +/// +/// Only the type of the second argument is used; its value is ignored. +/// This is useful in macros or generic SQL where you need to preserve +/// or match types dynamically. +/// +/// For example: +/// ```sql +/// select cast_to_type('42', NULL::INTEGER); +/// ``` +#[user_doc( + doc_section(label = "Other Functions"), + description = "Casts the first argument to the data type of the second argument. Only the type of the second argument is used; its value is ignored.", + syntax_example = "cast_to_type(expression, reference)", + sql_example = r#"```sql +> select cast_to_type('42', NULL::INTEGER) as a; ++----+ +| a | ++----+ +| 42 | ++----+ + +> select cast_to_type(1 + 2, NULL::DOUBLE) as b; ++-----+ +| b | ++-----+ +| 3.0 | ++-----+ +```"#, + argument( + name = "expression", + description = "Expression to cast. The expression can be a constant, column, or function, and any combination of operators." + ), + argument( + name = "reference", + description = "Reference expression whose data type determines the target cast type. The value is ignored." + ) +)] +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct CastToTypeFunc { + signature: Signature, +} + +impl Default for CastToTypeFunc { + fn default() -> Self { + Self::new() + } +} + +impl CastToTypeFunc { + pub fn new() -> Self { + Self { + signature: Signature::coercible( + vec![ + Coercion::new_exact(TypeSignatureClass::Any), + Coercion::new_exact(TypeSignatureClass::Any), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for CastToTypeFunc { + fn name(&self) -> &str { + "cast_to_type" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be called instead") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let nullable = args.arg_fields.iter().any(|f| f.is_nullable()); Review Comment: For DuckDB it is also nullable: ```sql CREATE TABLE test AS SELECT cast_to_type('42', NULL::INTEGER) AS val; SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name = 'test'; ``` ``` ┌─────────────┬───────────┬─────────────┐ │ column_name │ data_type │ is_nullable │ │ varchar │ varchar │ varchar │ ├─────────────┼───────────┼─────────────┤ │ val │ INTEGER │ YES │ └─────────────┴───────────┴─────────────┘ ``` But apparently even casting a non-nullable column makes a nullable output, which doesn't make sense, it would error if it can't cast: ```sql CREATE TABLE data (x INT NOT NULL); INSERT INTO data VALUES (1); CREATE TABLE test AS SELECT cast(x AS INT) AS val FROM data; SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name = 'test'; ``` ``` ┌─────────────┬───────────┬─────────────┐ │ column_name │ data_type │ is_nullable │ │ varchar │ varchar │ varchar │ ├─────────────┼───────────┼─────────────┤ │ val │ INTEGER │ YES │ └─────────────┴───────────┴─────────────┘ ``` So I feel this is more of a limitation of DuckDB than anything. DataFusion does preserve / compute nullability through similar expressions: ``` > create table test as select cast('42' AS INT) AS val; 0 row(s) fetched. Elapsed 0.002 seconds. > DESCRIBE test; +-------------+-----------+-------------+ | column_name | data_type | is_nullable | +-------------+-----------+-------------+ | val | Int32 | NO | +-------------+-----------+-------------+ 1 row(s) fetched. Elapsed 0.000 seconds. > drop table test; 0 row(s) fetched. Elapsed 0.000 seconds. > create table test as select arrow_cast('42', 'UInt16') AS val; 0 row(s) fetched. Elapsed 0.002 seconds. > DESCRIBE test; +-------------+-----------+-------------+ | column_name | data_type | is_nullable | +-------------+-----------+-------------+ | val | UInt16 | NO | +-------------+-----------+-------------+ 1 row(s) fetched. Elapsed 0.000 seconds. ``` I changed this in 7891a1fd0. Unlike `cast('42' AS NULL)` or `arrow_cast('42', 'Null')` which both fail `cast_to_type('42', null)` will succeed. My reasoning is that these expressions will be used programmatically thus it's more likely to hit an edge case like this and want to proceed instead of failing. I'm not sure why `arrow_cast('42', 'Null')` fails. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
