Skip to content

Commit 53b4ab9

Browse files
authored
fix(query): fix variant value can not cast to not null type (#17434)
* fix(query): fix variant value can not cast to not null type * add tests * fix
1 parent aa45b18 commit 53b4ab9

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/query/expression/src/evaluator.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,47 @@ impl<'a> Evaluator<'a> {
377377
.set_span(span))
378378
}
379379
}
380+
(
381+
DataType::Nullable(box DataType::Variant) | DataType::Variant,
382+
DataType::Boolean
383+
| DataType::Number(_)
384+
| DataType::String
385+
| DataType::Date
386+
| DataType::Timestamp,
387+
) => {
388+
// allow cast variant to not null types.
389+
let cast_fn = format!("to_{}", dest_type.to_string().to_lowercase());
390+
if let Some(new_value) = self.run_simple_cast(
391+
span,
392+
src_type,
393+
&dest_type.wrap_nullable(),
394+
value.clone(),
395+
&cast_fn,
396+
validity.clone(),
397+
options,
398+
)? {
399+
// remove wrapped null values.
400+
let new_value = match new_value {
401+
Value::Scalar(scalar) => {
402+
if scalar == Scalar::Null {
403+
Value::Scalar(Scalar::default_value(dest_type))
404+
} else {
405+
Value::Scalar(scalar)
406+
}
407+
}
408+
Value::Column(column) => {
409+
let nullable_column = column.as_nullable().unwrap();
410+
Value::Column(nullable_column.column.clone())
411+
}
412+
};
413+
Ok(new_value)
414+
} else {
415+
Err(ErrorCode::BadArguments(format!(
416+
"unable to cast type `{src_type}` to type `{dest_type}`"
417+
))
418+
.set_span(span))
419+
}
420+
}
380421
(DataType::Nullable(inner_src_ty), DataType::Nullable(inner_dest_ty)) => match value {
381422
Value::Scalar(Scalar::Null) => Ok(Value::Scalar(Scalar::Null)),
382423
Value::Scalar(_) => {

tests/sqllogictests/suites/base/03_common/03_0014_insert_into_select.test

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,5 +124,23 @@ DROP TABLE aggregate_table
124124
statement ok
125125
DROP TABLE test_insert
126126

127+
statement ok
128+
CREATE OR REPLACE TABLE t4(data variant);
129+
130+
statement ok
131+
INSERT INTO t4 values('{"user_id":1}'),('{"user_id":2}')
132+
133+
statement ok
134+
CREATE OR REPLACE TABLE t5(data variant, user_id uint8 not null);
135+
136+
statement ok
137+
INSERT INTO t5 SELECT data, data:user_id AS user_id FROM t4;
138+
139+
query TI
140+
SELECT * FROM t5;
141+
----
142+
{"user_id":1} 1
143+
{"user_id":2} 2
144+
127145
statement ok
128146
DROP DATABASE db1

0 commit comments

Comments
 (0)