Skip to content

Commit

Permalink
feat: support cast between integer and bool
Browse files Browse the repository at this point in the history
Signed-off-by: xyz <[email protected]>
  • Loading branch information
xiaoyong-z committed May 8, 2022
1 parent 3e8fe1e commit 7cdbe43
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
20 changes: 20 additions & 0 deletions e2e_test/v2/batch/types/cast.slt
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions src/expr/src/expr/expr_unary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
33 changes: 33 additions & 0 deletions src/expr/src/vector_op/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,22 @@ pub fn bool_to_str(input: bool) -> Result<String> {
}
}

macro_rules! integer_to_bool {
($func_name:ident, $type:ty) => {
#[inline(always)]
pub fn $func_name(input: $type) -> Result<bool> {
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]
Expand All @@ -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);
}
}

0 comments on commit 7cdbe43

Please sign in to comment.