use std::fmt;
use std::marker::PhantomData;
use super::enums::ColumnType;
use super::{ClickHouse, PostgreSql, Schema, names};
use crate::error::{Error, Result};
use crate::value::{IntoValue, Value};
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDefinition {
pub name: String,
pub kind: ColumnType,
pub length: Option<i64>,
pub precision: Option<i64>,
pub scale: Option<i64>,
pub nullable: bool,
pub default: Option<Value>,
pub default_raw: Option<String>,
pub unsigned: bool,
pub unique: bool,
pub primary: bool,
pub auto_increment: bool,
pub after: Option<String>,
pub comment: Option<String>,
pub enum_values: Vec<String>,
pub srid: Option<i64>,
pub dimensions: Option<i64>,
pub modify: bool,
pub collation: Option<String>,
pub check: Option<String>,
pub generated_expression: Option<String>,
pub generated_stored: Option<bool>,
pub ttl: Option<String>,
pub user_type: Option<String>,
pub low_cardinality: bool,
pub fixed_string_length: Option<i64>,
pub codecs: Vec<String>,
pub array_element_type: Option<ColumnType>,
pub tuple_element_types: Vec<ColumnType>,
}
pub struct Column<S> {
pub(crate) def: ColumnDefinition,
dialect: PhantomData<fn() -> S>,
}
impl<S> Clone for Column<S> {
fn clone(&self) -> Self {
Column { def: self.def.clone(), dialect: PhantomData }
}
}
impl<S> fmt::Debug for Column<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.def.fmt(f)
}
}
impl<S> PartialEq for Column<S> {
fn eq(&self, other: &Self) -> bool {
self.def == other.def
}
}
pub trait AutoIncrement: Schema {}
pub trait Collation: Schema {}
pub trait Comment: Schema {}
pub trait Dimensions: Schema {}
pub trait Generated: Schema {}
pub trait Positioning: Schema {}
pub trait Srid: Schema {}
pub trait Unique: Schema {}
pub trait VirtualGenerated: Schema {}
pub(crate) fn expression(value: &str, empty: &str, semicolon: &str) -> Result<String> {
let trimmed = php_std::string::trim(value.as_bytes(), php_std::string::TRIM_CHARACTERS);
let trimmed = String::from_utf8_lossy(trimmed).into_owned();
if trimmed.is_empty() {
return Err(Error::Validation(empty.into()));
}
if trimmed.contains(';') {
return Err(Error::Validation(semicolon.into()));
}
Ok(trimmed)
}
impl<S> Column<S> {
pub fn new(name: impl Into<String>, kind: ColumnType) -> Self {
Column {
def: ColumnDefinition {
name: name.into(),
kind,
length: None,
precision: None,
scale: None,
nullable: false,
default: None,
default_raw: None,
unsigned: false,
unique: false,
primary: false,
auto_increment: false,
after: None,
comment: None,
enum_values: Vec::new(),
srid: None,
dimensions: None,
modify: false,
collation: None,
check: None,
generated_expression: None,
generated_stored: None,
ttl: None,
user_type: None,
low_cardinality: false,
fixed_string_length: None,
codecs: Vec::new(),
array_element_type: None,
tuple_element_types: Vec::new(),
},
dialect: PhantomData,
}
}
pub fn with_length(mut self, length: Option<i64>) -> Self {
self.def.length = length;
self
}
pub fn with_precision(mut self, precision: Option<i64>) -> Self {
self.def.precision = precision;
self
}
pub fn with_scale(mut self, scale: Option<i64>) -> Self {
self.def.scale = scale;
self
}
pub fn with_srid(mut self, srid: Option<i64>) -> Self {
self.def.srid = srid;
self
}
pub fn with_dimensions(mut self, dimensions: Option<i64>) -> Self {
self.def.dimensions = dimensions;
self
}
pub fn with_auto_increment(mut self, auto_increment: bool) -> Self {
self.def.auto_increment = auto_increment;
self
}
pub fn definition(&self) -> &ColumnDefinition {
&self.def
}
pub fn definition_mut(&mut self) -> &mut ColumnDefinition {
&mut self.def
}
pub fn name(&self) -> &str {
&self.def.name
}
pub fn nullable(&mut self) -> &mut Self {
self.def.nullable = true;
self
}
pub fn default(&mut self, value: impl IntoValue) -> &mut Self {
self.def.default = Some(value.into_value());
self
}
pub fn default_raw(&mut self, expression: &str) -> Result<&mut Self> {
self.def.default_raw = Some(self::expression(
expression,
"Raw default expression must not be empty.",
"Raw default expression must not contain \";\".",
)?);
Ok(self)
}
pub fn unsigned(&mut self) -> &mut Self {
self.def.unsigned = true;
self
}
pub fn primary(&mut self) -> &mut Self {
self.def.primary = true;
self
}
pub fn enum_values<V: Into<String>>(&mut self, values: impl IntoIterator<Item = V>) -> Result<&mut Self> {
let values: Vec<String> = values.into_iter().map(Into::into).collect();
if values.is_empty() {
return Err(Error::Validation("enum() requires at least one allowed value.".into()));
}
self.def.enum_values = values;
Ok(self)
}
pub fn modify(&mut self) -> &mut Self {
self.def.modify = true;
self
}
}
impl<S: AutoIncrement> Column<S> {
pub fn auto_increment(&mut self) -> &mut Self {
self.def.auto_increment = true;
self
}
}
impl<S: Collation> Column<S> {
pub fn collation(&mut self, collation: impl Into<String>) -> &mut Self {
self.def.collation = Some(collation.into());
self
}
}
impl<S: Comment> Column<S> {
pub fn comment(&mut self, comment: impl Into<String>) -> &mut Self {
self.def.comment = Some(comment.into());
self
}
}
impl<S: Dimensions> Column<S> {
pub fn dimensions(&mut self, dimensions: i64) -> &mut Self {
self.def.dimensions = Some(dimensions);
self
}
}
impl<S: Generated> Column<S> {
pub fn generated_as(&mut self, expression: impl Into<String>) -> &mut Self {
self.def.generated_expression = Some(expression.into());
self
}
pub fn stored(&mut self) -> &mut Self {
self.def.generated_stored = Some(true);
self
}
}
impl<S: VirtualGenerated> Column<S> {
pub fn virtual_(&mut self) -> &mut Self {
self.def.generated_stored = Some(false);
self
}
}
impl<S: Positioning> Column<S> {
pub fn after(&mut self, column: impl Into<String>) -> &mut Self {
self.def.after = Some(column.into());
self
}
}
impl<S: Srid> Column<S> {
pub fn srid(&mut self, srid: i64) -> &mut Self {
self.def.srid = Some(srid);
self
}
}
impl<S: Unique> Column<S> {
pub fn unique(&mut self) -> &mut Self {
self.def.unique = true;
self
}
}
impl<S: super::table::Checks> Column<S> {
pub fn check(&mut self, expression: impl Into<String>) -> &mut Self {
self.def.check = Some(expression.into());
self
}
}
impl Column<PostgreSql> {
pub fn user_type(&mut self, name: &str) -> Result<&mut Self> {
if !names::is_identifier(name) {
return Err(Error::Validation(format!("Invalid user-defined type name: {name}")));
}
self.def.user_type = Some(name.to_owned());
Ok(self)
}
}
impl Column<ClickHouse> {
pub fn as_fixed_string(&mut self, length: i64) -> Result<&mut Self> {
if length < 1 {
return Err(Error::Validation("FixedString length must be at least 1.".into()));
}
self.def.fixed_string_length = Some(length);
Ok(self)
}
pub fn is_fixed_string(&self) -> bool {
self.def.fixed_string_length.is_some()
}
pub fn as_array(&mut self, element: ColumnType) -> &mut Self {
self.def.array_element_type = Some(element);
self
}
pub fn is_array(&self) -> bool {
self.def.array_element_type.is_some()
}
pub fn as_tuple(&mut self, elements: Vec<ColumnType>) -> Result<&mut Self> {
if elements.is_empty() {
return Err(Error::Validation("Tuple() requires at least one element type.".into()));
}
self.def.tuple_element_types = elements;
Ok(self)
}
pub fn is_tuple(&self) -> bool {
!self.def.tuple_element_types.is_empty()
}
pub fn low_cardinality(&mut self) -> &mut Self {
self.def.low_cardinality = true;
self
}
pub fn codec(&mut self, codec: &str) -> Result<&mut Self> {
let codec =
expression(codec, "CODEC expression must not be empty.", "CODEC expression must not contain \";\".")?;
self.def.codecs.push(codec);
Ok(self)
}
pub fn ttl(&mut self, expression: &str) -> Result<&mut Self> {
self.def.ttl = Some(self::expression(
expression,
"TTL expression must not be empty.",
"TTL expression must not contain \";\".",
)?);
Ok(self)
}
}