sqlx-firebirdsql 0.1.0

Firebird SQL driver for SQLx
use std::borrow::Cow;
use std::str::from_utf8;

use bytes::Bytes;
pub(crate) use sqlx_core::value::*;

use crate::error::{BoxDynError, UnexpectedNullError};
use crate::type_info::FirebirdSqlType;
use crate::{Firebird, FirebirdTypeInfo};

#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum FirebirdValueFormat {
    Text,
    Binary,
}

/// Implementation of [`Value`] for Firebird.
#[derive(Clone)]
pub struct FirebirdValue {
    value: Option<Bytes>,
    type_info: FirebirdTypeInfo,
    format: FirebirdValueFormat,
}

/// Implementation of [`ValueRef`] for Firebird.
#[derive(Clone)]
pub struct FirebirdValueRef<'r> {
    pub(crate) value: Option<&'r [u8]>,
    pub(crate) row: Option<&'r Bytes>,
    pub(crate) type_info: FirebirdTypeInfo,
    pub(crate) format: FirebirdValueFormat,
}

impl<'r> FirebirdValueRef<'r> {
    pub(crate) fn format(&self) -> FirebirdValueFormat {
        self.format
    }

    pub(crate) fn as_bytes(&self) -> Result<&'r [u8], BoxDynError> {
        match &self.value {
            Some(v) => Ok(v),
            None => Err(UnexpectedNullError.into()),
        }
    }

    pub(crate) fn as_str(&self) -> Result<&'r str, BoxDynError> {
        Ok(from_utf8(self.as_bytes()?)?)
    }
}

impl Value for FirebirdValue {
    type Database = Firebird;

    fn as_ref(&self) -> FirebirdValueRef<'_> {
        FirebirdValueRef {
            value: self.value.as_deref(),
            row: None,
            type_info: self.type_info.clone(),
            format: self.format,
        }
    }

    fn type_info(&self) -> Cow<'_, FirebirdTypeInfo> {
        Cow::Borrowed(&self.type_info)
    }

    fn is_null(&self) -> bool {
        is_null(self.value.as_deref(), &self.type_info)
    }
}

impl<'r> ValueRef<'r> for FirebirdValueRef<'r> {
    type Database = Firebird;

    fn to_owned(&self) -> FirebirdValue {
        let value = match (self.row, self.value) {
            (Some(row), Some(value)) => Some(row.slice_ref(value)),

            (None, Some(value)) => Some(Bytes::copy_from_slice(value)),

            _ => None,
        };

        FirebirdValue {
            value,
            format: self.format,
            type_info: self.type_info.clone(),
        }
    }

    fn type_info(&self) -> Cow<'_, FirebirdTypeInfo> {
        Cow::Borrowed(&self.type_info)
    }

    #[inline]
    fn is_null(&self) -> bool {
        is_null(self.value, &self.type_info)
    }
}

fn is_null(value: Option<&[u8]>, ty: &FirebirdTypeInfo) -> bool {
    if let Some(value) = value {
        // zero dates and date times should be treated the same as NULL
        if matches!(
            ty.r#type,
            FirebirdSqlType::Date | FirebirdSqlType::Timestamp | FirebirdSqlType::TimestampTz
        ) && value.starts_with(b"\0")
        {
            return true;
        }
    }

    value.is_none()
}