From 7cdbe431b1b9ccfac8e34e5704e4622743622563 Mon Sep 17 00:00:00 2001 From: xyz Date: Sun, 8 May 2022 18:32:22 +0800 Subject: [PATCH] feat: support cast between integer and bool Signed-off-by: xyz --- e2e_test/v2/batch/types/cast.slt | 20 +++++++++++++++++++ src/expr/src/expr/expr_unary.rs | 6 ++++++ src/expr/src/vector_op/cast.rs | 33 ++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/e2e_test/v2/batch/types/cast.slt b/e2e_test/v2/batch/types/cast.slt index 686e98d44eadd..9c596a64ac16e 100644 --- a/e2e_test/v2/batch/types/cast.slt +++ b/e2e_test/v2/batch/types/cast.slt @@ -37,3 +37,23 @@ query T values('1999-01-08 04:05:06'::timestamp::timestamp); ---- 1999-01-08 04:05:06 + +query T +values(10::integer::boolean); +---- +t + +query T +values(0::integer::boolean); +---- +f + +query T +values(false::boolean::integer); +---- +0 + +query T +values(true::boolean::integer); +---- +1 diff --git a/src/expr/src/expr/expr_unary.rs b/src/expr/src/expr/expr_unary.rs index c4002d3bdec1b..8fa04c9642dfe 100644 --- a/src/expr/src/expr/expr_unary.rs +++ b/src/expr/src/expr/expr_unary.rs @@ -102,6 +102,12 @@ macro_rules! gen_cast { { varchar, boolean, str_to_bool }, { boolean, varchar, bool_to_str }, + { boolean, int16, general_cast }, + { boolean, int32, general_cast }, + { boolean, int64, general_cast }, + { int16, boolean, int16_to_bool }, + { int32, boolean, int32_to_bool }, + { int64, boolean, int64_to_bool }, { int16, int32, general_cast }, { int16, int64, general_cast }, diff --git a/src/expr/src/vector_op/cast.rs b/src/expr/src/vector_op/cast.rs index f9fa0a6ec6e19..9e9f9deb957ae 100644 --- a/src/expr/src/vector_op/cast.rs +++ b/src/expr/src/vector_op/cast.rs @@ -213,6 +213,22 @@ pub fn bool_to_str(input: bool) -> Result { } } +macro_rules! integer_to_bool { + ($func_name:ident, $type:ty) => { + #[inline(always)] + pub fn $func_name(input: $type) -> Result { + match input { + 0 => Ok(false), + _ => Ok(true), + } + } + }; +} + +integer_to_bool!(int16_to_bool, i16); +integer_to_bool!(int32_to_bool, i32); +integer_to_bool!(int64_to_bool, i64); + #[cfg(test)] mod tests { #[test] @@ -238,4 +254,21 @@ mod tests { "Parse error: Can't cast string to time (expected format is HH:MM:SS[.MS])".to_string() ); } + + #[test] + fn integer_cast_to_bool() { + use super::*; + + assert_eq!(int16_to_bool(16).unwrap(), true); + assert_eq!(int32_to_bool(32).unwrap(), true); + assert_eq!(int64_to_bool(64).unwrap(), true); + + assert_eq!(int16_to_bool(-16).unwrap(), true); + assert_eq!(int32_to_bool(-32).unwrap(), true); + assert_eq!(int64_to_bool(-64).unwrap(), true); + + assert_eq!(int16_to_bool(0).unwrap(), false); + assert_eq!(int32_to_bool(0).unwrap(), false); + assert_eq!(int64_to_bool(0).unwrap(), false); + } }