Skip to content

Commit

Permalink
tidb_query: fix converting bytes to bool (#7486) (#7547)
Browse files Browse the repository at this point in the history
Signed-off-by: zhongzc <zhongzc_arch@outlook.com>
  • Loading branch information
sre-bot committed Apr 28, 2020
1 parent 85ab382 commit 191cb87
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 3 deletions.
57 changes: 56 additions & 1 deletion src/coprocessor/codec/data_type/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl AsMySQLBool for Bytes {
#[inline]
fn as_mysql_bool(&self, context: &mut EvalContext) -> Result<bool> {
Ok(!self.is_empty()
&& crate::coprocessor::codec::convert::bytes_to_int(context, self)? != 0)
&& crate::coprocessor::codec::convert::bytes_to_f64(context, self)? != 0f64)
}
}

Expand Down Expand Up @@ -120,6 +120,61 @@ mod tests {
use super::*;
use std::f64;

#[test]
fn test_bytes_as_bool() {
let tests: Vec<(&'static [u8], Option<bool>)> = vec![
(b"", Some(false)),
(b" 23", Some(true)),
(b"-1", Some(true)),
(b"1.11", Some(true)),
(b"1.11.00", None),
(b"xx", None),
(b"0x00", None),
(b"11.xx", None),
(b"xx.11", None),
(
b".0000000000000000000000000000000000000000000000000000001",
Some(true),
),
];

let mut ctx = EvalContext::default();
for (i, (v, expect)) in tests.into_iter().enumerate() {
let rb: Result<bool> = v.to_vec().as_mysql_bool(&mut ctx);
match expect {
Some(val) => {
assert_eq!(rb.unwrap(), val);
}
None => {
assert!(
rb.is_err(),
"index: {}, {:?} should not be converted, but got: {:?}",
i,
v,
rb
);
}
}
}

// test overflow
let mut ctx = EvalContext::default();
let val: Result<bool> = f64::INFINITY
.to_string()
.as_bytes()
.to_vec()
.as_mysql_bool(&mut ctx);
assert!(val.is_err());

let mut ctx = EvalContext::default();
let val: Result<bool> = f64::NEG_INFINITY
.to_string()
.as_bytes()
.to_vec()
.as_mysql_bool(&mut ctx);
assert!(val.is_err());
}

#[test]
fn test_real_as_bool() {
let tests: Vec<(f64, Option<bool>)> = vec![
Expand Down
4 changes: 2 additions & 2 deletions src/coprocessor/codec/datum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ impl Datum {
Datum::I64(i) => Some(i != 0),
Datum::U64(u) => Some(u != 0),
Datum::F64(f) => Some(f != 0f64),
Datum::Bytes(ref bs) => Some(!bs.is_empty() && convert::bytes_to_int(ctx, bs)? != 0),
Datum::Bytes(ref bs) => Some(!bs.is_empty() && convert::bytes_to_f64(ctx, bs)? != 0f64),
Datum::Time(t) => Some(!t.is_zero()),
Datum::Dur(d) => Some(!d.is_zero()),
Datum::Dec(d) => Some(!d.is_zero()),
Expand Down Expand Up @@ -1704,7 +1704,7 @@ mod tests {
(Datum::F64(-0.4), Some(true)),
(Datum::Null, None),
(b"".as_ref().into(), Some(false)),
(b"0.5".as_ref().into(), Some(false)),
(b"0.5".as_ref().into(), Some(true)),
(b"0".as_ref().into(), Some(false)),
(b"2".as_ref().into(), Some(true)),
(b"abc".as_ref().into(), Some(false)),
Expand Down

0 comments on commit 191cb87

Please sign in to comment.