use crate::{Error, Result, Row, StringColumn};
use base64::{engine::general_purpose::STANDARD, Engine as _};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Base64Bytes(pub Vec<u8>);
impl Base64Bytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for Base64Bytes {
fn from(v: Vec<u8>) -> Self {
Base64Bytes(v)
}
}
impl From<Base64Bytes> for Vec<u8> {
fn from(b: Base64Bytes) -> Self {
b.0
}
}
impl StringColumn for Base64Bytes {
fn to_column_str(&self) -> String {
STANDARD.encode(&self.0)
}
fn from_column_str(s: &str) -> Result<Self> {
STANDARD
.decode(s)
.map(Base64Bytes)
.map_err(|e| Error::msg(format!("invalid base64 in column: {e}")))
}
}
impl crate::SqlType for Base64Bytes {
const COLUMN_TYPE: crate::ColumnType = crate::ColumnType::Text;
}
impl crate::ToColumn for Base64Bytes {
fn to_value(&self) -> sea_query::Value {
sea_query::Value::String(Some(Box::new(self.to_column_str())))
}
}
impl crate::FromColumn for Base64Bytes {
fn from_column(row: &dyn Row, col: &str) -> Result<Self> {
let s =
row.get_string(col)?.ok_or_else(|| Error::msg(format!("column `{col}` was NULL")))?;
<Base64Bytes as StringColumn>::from_column_str(&s)
}
}