mod postgres;
pub use postgres::PostgresTypeMapper;
use syn::Type;
use crate::entity::parse::ColumnConfig;
#[derive(Debug, Clone)]
pub struct SqlType {
pub name: String,
pub nullable: bool,
pub array_dim: usize
}
impl SqlType {
#[cfg(test)]
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
nullable: false,
array_dim: 0
}
}
#[cfg(test)]
#[must_use]
pub fn nullable(name: impl Into<String>) -> Self {
Self {
name: name.into(),
nullable: true,
array_dim: 0
}
}
#[must_use]
pub fn to_sql_string(&self) -> String {
if self.array_dim > 0 {
format!("{}{}", self.name, "[]".repeat(self.array_dim))
} else {
self.name.clone()
}
}
}
pub trait TypeMapper {
fn map_type(&self, ty: &Type, column: &ColumnConfig) -> SqlType;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sql_type_new() {
let ty = SqlType::new("INTEGER");
assert_eq!(ty.name, "INTEGER");
assert!(!ty.nullable);
assert_eq!(ty.array_dim, 0);
}
#[test]
fn sql_type_nullable() {
let ty = SqlType::nullable("TEXT");
assert!(ty.nullable);
}
#[test]
fn sql_type_to_sql_string_scalar() {
let ty = SqlType::new("UUID");
assert_eq!(ty.to_sql_string(), "UUID");
}
#[test]
fn sql_type_to_sql_string_array() {
let ty = SqlType {
name: "TEXT".to_string(),
nullable: false,
array_dim: 1
};
assert_eq!(ty.to_sql_string(), "TEXT[]");
}
#[test]
fn sql_type_to_sql_string_2d_array() {
let ty = SqlType {
name: "INTEGER".to_string(),
nullable: false,
array_dim: 2
};
assert_eq!(ty.to_sql_string(), "INTEGER[][]");
}
}