use super::value::SqlValue;
use crate::error::{Error, Result};
use async_trait::async_trait;
use serde_json::Value as JsonValue;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatabaseBackend {
Postgres,
MySQL,
MariaDB,
SQLite,
}
#[async_trait]
pub trait TypeConverter: Send + Sync {
fn backend(&self) -> DatabaseBackend;
fn sql_value_to_param(&self, value: &SqlValue, param_index: usize) -> Result<String>;
fn extract_column_value(
&self,
row: &dyn std::any::Any,
column_index: usize,
column_name: &str,
column_type: &str,
) -> Result<SqlValue>;
fn row_to_json(&self, row: &dyn std::any::Any) -> Result<JsonValue>;
fn is_null(&self, row: &dyn std::any::Any, column_index: usize) -> Result<bool>;
fn null_representation(&self, _target_type: Option<&str>) -> String {
"NULL".to_string()
}
fn boolean_to_sql(&self, value: bool) -> String {
if value { "TRUE" } else { "FALSE" }.to_string()
}
fn parameter_placeholder(&self, index: usize) -> String;
}
#[derive(Debug, Clone)]
pub struct ColumnMetadata {
pub name: String,
pub type_name: String,
pub nullable: bool,
pub position: usize,
}
pub struct ConversionUtils;
impl ConversionUtils {
pub fn parse_bool_string(s: &str) -> Option<bool> {
match s.to_lowercase().as_str() {
"true" | "t" | "yes" | "y" | "1" => Some(true),
"false" | "f" | "no" | "n" | "0" => Some(false),
_ => None,
}
}
pub fn parse_timestamp(s: &str) -> Result<i64> {
use chrono::{DateTime, NaiveDateTime, Utc};
if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
return Ok(dt.timestamp());
}
if let Ok(ndt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Ok(DateTime::<Utc>::from_naive_utc_and_offset(ndt, Utc).timestamp());
}
if let Ok(ndt) =
NaiveDateTime::parse_from_str(&format!("{} 00:00:00", s), "%Y-%m-%d %H:%M:%S")
{
return Ok(DateTime::<Utc>::from_naive_utc_and_offset(ndt, Utc).timestamp());
}
Err(Error::template(format!("Failed to parse timestamp: {}", s)))
}
pub fn format_timestamp(timestamp: i64) -> String {
use chrono::{DateTime, Utc};
DateTime::from_timestamp(timestamp, 0)
.map(|dt: DateTime<Utc>| dt.to_rfc3339())
.unwrap_or_else(|| format!("{}", timestamp))
}
pub fn escape_sql_string(s: &str) -> String {
s.replace('\'', "''")
}
pub fn bytes_to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02X}", b)).collect()
}
pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>> {
let hex = hex.trim_start_matches("0x").trim_start_matches("0X");
if hex.len() % 2 != 0 {
return Err(Error::template(
"Invalid hex string: odd length".to_string(),
));
}
(0..hex.len())
.step_by(2)
.map(|i| {
u8::from_str_radix(&hex[i..i + 2], 16)
.map_err(|e| Error::template(format!("Invalid hex string: {}", e)))
})
.collect()
}
}