use super::PostgresValue;
use super::insert::ValueWrapper;
use drizzle_core::{
param::Param, placeholder::Placeholder, sql::SQL, sql::SQLChunk, traits::SQLParam,
};
use std::borrow::Cow;
#[cfg(feature = "uuid")]
use uuid::Uuid;
#[derive(Debug, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum PostgresUpdateValue<'a, V: SQLParam, T> {
#[default]
Skip,
Null,
Value(ValueWrapper<'a, V, T>),
}
impl<'a, V: SQLParam, T> PostgresUpdateValue<'a, V, T> {
pub fn is_skip(&self) -> bool {
matches!(self, Self::Skip)
}
}
impl<'a, T> From<T> for PostgresUpdateValue<'a, PostgresValue<'a>, T>
where
T: TryInto<PostgresValue<'a>>,
{
fn from(value: T) -> Self {
let sql = value
.try_into()
.map(|v: PostgresValue<'a>| SQL::from(v))
.unwrap_or_else(|_| SQL::from(PostgresValue::Null));
PostgresUpdateValue::Value(ValueWrapper::<PostgresValue<'a>, T>::new(sql))
}
}
impl<'a> From<&str> for PostgresUpdateValue<'a, PostgresValue<'a>, String> {
fn from(value: &str) -> Self {
let postgres_value = SQL::param(Cow::Owned(PostgresValue::from(value.to_string())));
PostgresUpdateValue::Value(ValueWrapper::<PostgresValue<'a>, String>::new(
postgres_value,
))
}
}
impl<'a, T> From<Placeholder> for PostgresUpdateValue<'a, PostgresValue<'a>, T> {
fn from(placeholder: Placeholder) -> Self {
let chunk = SQLChunk::Param(Param {
placeholder,
value: None,
});
PostgresUpdateValue::Value(ValueWrapper::<PostgresValue<'a>, T>::new(
std::iter::once(chunk).collect(),
))
}
}
#[cfg(feature = "uuid")]
impl<'a> From<Uuid> for PostgresUpdateValue<'a, PostgresValue<'a>, String> {
fn from(value: Uuid) -> Self {
let postgres_value = PostgresValue::Uuid(value);
let sql = SQL::param(postgres_value);
PostgresUpdateValue::Value(ValueWrapper::<PostgresValue<'a>, String>::new(sql))
}
}
#[cfg(feature = "uuid")]
impl<'a> From<&'a Uuid> for PostgresUpdateValue<'a, PostgresValue<'a>, String> {
fn from(value: &'a Uuid) -> Self {
let postgres_value = PostgresValue::Uuid(*value);
let sql = SQL::param(postgres_value);
PostgresUpdateValue::Value(ValueWrapper::<PostgresValue<'a>, String>::new(sql))
}
}