From 6dfc91daf7e5ca407d8b82f289b27d791e776393 Mon Sep 17 00:00:00 2001 From: Ryan Leckey Date: Thu, 11 Feb 2021 22:29:29 -0800 Subject: [PATCH] feat(mysql): add MySqlRawValue - renamed from MySqlValue (from master) --- sqlx-mysql/src/value.rs | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 sqlx-mysql/src/value.rs diff --git a/sqlx-mysql/src/value.rs b/sqlx-mysql/src/value.rs new file mode 100644 index 00000000..d7e5951e --- /dev/null +++ b/sqlx-mysql/src/value.rs @@ -0,0 +1,49 @@ +use std::str::from_utf8; + +use bytes::Bytes; +use sqlx_core::decode::{Error as DecodeError, Result as DecodeResult}; +use sqlx_core::{Decode, Runtime}; + +use crate::MySql; + +/// The format of a raw SQL value for MySQL. +/// +/// MySQL returns values in [`Text`] format for unprepared queries and in [`Binary`] +/// format for prepared queries. There is no facility to request a different format. +/// +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum MySqlRawValueFormat { + Binary, + Text, +} + +/// The raw representation of a SQL value for MySQL. +#[derive(Debug, Clone)] +pub struct MySqlRawValue<'r> { + value: Option<&'r Bytes>, + format: MySqlRawValueFormat, +} + +// 'r: row +impl<'r> MySqlRawValue<'r> { + /// Returns the format of this value. + pub const fn format(&self) -> MySqlRawValueFormat { + self.format + } + + /// Returns the underlying byte view of this value as a byte slice. + pub fn as_bytes(&self) -> DecodeResult<&'r [u8]> { + self.value.map(|bytes| &**bytes).ok_or(DecodeError::UnexpectedNull) + } + + /// Returns a `&str` slice from the underlying byte view of this value, + /// if it contains valid UTF-8. + pub fn as_str(&self) -> DecodeResult<&'r str> { + self.as_bytes().and_then(|bytes| from_utf8(bytes).map_err(DecodeError::NotUtf8)) + } + + /// Decode this value into the target type. + pub fn decode, Rt: Runtime>(self) -> DecodeResult { + >::decode(self) + } +}