From 80d545109b84148d28316edf6388ee1f33883f64 Mon Sep 17 00:00:00 2001 From: Daniel Akhterov Date: Mon, 15 Jun 2020 22:49:33 -0700 Subject: [PATCH] feat: implement `BIT` support in MSSQL --- sqlx-core/src/mssql/protocol/type_info.rs | 5 ++++ sqlx-core/src/mssql/types/bool.rs | 30 +++++++++++++++++++++++ sqlx-core/src/mssql/types/mod.rs | 1 + tests/mssql/types.rs | 6 +++++ 4 files changed, 42 insertions(+) create mode 100644 sqlx-core/src/mssql/types/bool.rs diff --git a/sqlx-core/src/mssql/protocol/type_info.rs b/sqlx-core/src/mssql/protocol/type_info.rs index f4c8e871..920d33c7 100644 --- a/sqlx-core/src/mssql/protocol/type_info.rs +++ b/sqlx-core/src/mssql/protocol/type_info.rs @@ -491,6 +491,7 @@ impl TypeInfo { DataType::BigInt => s.push_str("bigint"), DataType::Real => s.push_str("real"), DataType::Float => s.push_str("float"), + DataType::Bit => s.push_str("bit"), DataType::IntN => s.push_str(match self.size { 1 => "tinyint", @@ -536,6 +537,10 @@ impl TypeInfo { } } + DataType::BitN => { + s.push_str("bit"); + } + _ => unimplemented!("fmt: unsupported data type {:?}", self.ty), } } diff --git a/sqlx-core/src/mssql/types/bool.rs b/sqlx-core/src/mssql/types/bool.rs new file mode 100644 index 00000000..0df1cfb7 --- /dev/null +++ b/sqlx-core/src/mssql/types/bool.rs @@ -0,0 +1,30 @@ +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::mssql::protocol::type_info::{DataType, TypeInfo}; +use crate::mssql::{Mssql, MssqlTypeInfo, MssqlValueRef}; +use crate::types::Type; + +impl Type for bool { + fn type_info() -> MssqlTypeInfo { + MssqlTypeInfo(TypeInfo::new(DataType::BitN, 1)) + } +} + +impl Encode<'_, Mssql> for bool { + fn encode_by_ref(&self, buf: &mut Vec) -> IsNull { + buf.push(if *self { 1 } else { 0 }); + + IsNull::No + } +} + +impl Decode<'_, Mssql> for bool { + fn accepts(ty: &MssqlTypeInfo) -> bool { + matches!(ty.0.ty, DataType::Bit | DataType::BitN) + } + + fn decode(value: MssqlValueRef<'_>) -> Result { + Ok(value.as_bytes()?[0] == 1) + } +} diff --git a/sqlx-core/src/mssql/types/mod.rs b/sqlx-core/src/mssql/types/mod.rs index 1823bcfa..86505a85 100644 --- a/sqlx-core/src/mssql/types/mod.rs +++ b/sqlx-core/src/mssql/types/mod.rs @@ -2,6 +2,7 @@ use crate::encode::{Encode, IsNull}; use crate::mssql::protocol::type_info::{DataType, TypeInfo}; use crate::mssql::{Mssql, MssqlTypeInfo}; +mod bool; mod float; mod int; mod str; diff --git a/tests/mssql/types.rs b/tests/mssql/types.rs index a6f4284a..c3bb1076 100644 --- a/tests/mssql/types.rs +++ b/tests/mssql/types.rs @@ -35,3 +35,9 @@ test_type!(str(Mssql, "'this is foo'" == "this is foo", "''" == "", )); + +test_type!(bool( + Mssql, + "CAST(1 as BIT)" == true, + "CAST(0 as BIT)" == false +));