use std::fmt;
use super::column::{Column, expression};
use super::enums::{ColumnType, Engine, ForeignKeyAction, IndexType, PartitionType};
use super::index::{CheckConstraint, Index, RenameColumn};
use super::{ClickHouse, MongoDb, PostgreSql, Schema, names};
use crate::builder::Statement;
use crate::error::{Error, Result};
use crate::value::Value;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForeignKey {
pub column: String,
pub ref_table: String,
pub ref_column: String,
pub on_delete: Option<ForeignKeyAction>,
pub on_update: Option<ForeignKeyAction>,
}
impl ForeignKey {
pub fn new(column: impl Into<String>) -> Self {
ForeignKey {
column: column.into(),
ref_table: String::new(),
ref_column: String::new(),
on_delete: None,
on_update: None,
}
}
pub fn references(&mut self, column: impl Into<String>) -> &mut Self {
self.ref_column = column.into();
self
}
pub fn on(&mut self, table: impl Into<String>) -> &mut Self {
self.ref_table = table.into();
self
}
pub fn on_delete(&mut self, action: ForeignKeyAction) -> &mut Self {
self.on_delete = Some(action);
self
}
pub fn on_update(&mut self, action: ForeignKeyAction) -> &mut Self {
self.on_update = Some(action);
self
}
}
pub struct TableDefinition<S> {
pub name: String,
pub columns: Vec<Column<S>>,
pub indexes: Vec<Index>,
pub foreign_keys: Vec<ForeignKey>,
pub drop_columns: Vec<String>,
pub rename_columns: Vec<RenameColumn>,
pub drop_indexes: Vec<String>,
pub drop_foreign_keys: Vec<String>,
pub raw_column_defs: Vec<String>,
pub raw_index_defs: Vec<String>,
pub checks: Vec<CheckConstraint>,
pub composite_primary_key: Vec<String>,
pub order_by: Vec<String>,
pub partition_type: Option<PartitionType>,
pub partition_expression: String,
pub partition_count: Option<i64>,
pub engine: Option<Engine>,
pub engine_args: Vec<String>,
pub ttl: Option<String>,
pub settings: Vec<(String, String)>,
pub sample_by: Option<String>,
pub order_by_raw: Option<String>,
}
impl<S> Clone for TableDefinition<S> {
fn clone(&self) -> Self {
TableDefinition {
name: self.name.clone(),
columns: self.columns.clone(),
indexes: self.indexes.clone(),
foreign_keys: self.foreign_keys.clone(),
drop_columns: self.drop_columns.clone(),
rename_columns: self.rename_columns.clone(),
drop_indexes: self.drop_indexes.clone(),
drop_foreign_keys: self.drop_foreign_keys.clone(),
raw_column_defs: self.raw_column_defs.clone(),
raw_index_defs: self.raw_index_defs.clone(),
checks: self.checks.clone(),
composite_primary_key: self.composite_primary_key.clone(),
order_by: self.order_by.clone(),
partition_type: self.partition_type,
partition_expression: self.partition_expression.clone(),
partition_count: self.partition_count,
engine: self.engine,
engine_args: self.engine_args.clone(),
ttl: self.ttl.clone(),
settings: self.settings.clone(),
sample_by: self.sample_by.clone(),
order_by_raw: self.order_by_raw.clone(),
}
}
}
impl<S> fmt::Debug for TableDefinition<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TableDefinition")
.field("name", &self.name)
.field("columns", &self.columns)
.field("indexes", &self.indexes)
.field("foreign_keys", &self.foreign_keys)
.finish_non_exhaustive()
}
}
pub struct Table<S> {
schema: Option<S>,
def: TableDefinition<S>,
}
impl<S: Clone> Clone for Table<S> {
fn clone(&self) -> Self {
Table { schema: self.schema.clone(), def: self.def.clone() }
}
}
impl<S> fmt::Debug for Table<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.def.fmt(f)
}
}
pub trait Serial: Schema {}
pub trait Checks: Schema {}
pub trait ColumnAlterations: Schema {}
pub trait CompositePrimary: Schema {}
pub trait InlineForeignKey: Schema {}
pub trait ForeignKeys: InlineForeignKey {}
pub trait FulltextSpatialIndex: Schema {}
pub trait StandardPartitioning: Schema {}
impl<S> Table<S> {
pub fn new(name: impl Into<String>) -> Self {
Table {
schema: None,
def: TableDefinition {
name: name.into(),
columns: Vec::new(),
indexes: Vec::new(),
foreign_keys: Vec::new(),
drop_columns: Vec::new(),
rename_columns: Vec::new(),
drop_indexes: Vec::new(),
drop_foreign_keys: Vec::new(),
raw_column_defs: Vec::new(),
raw_index_defs: Vec::new(),
checks: Vec::new(),
composite_primary_key: Vec::new(),
order_by: Vec::new(),
partition_type: None,
partition_expression: String::new(),
partition_count: None,
engine: None,
engine_args: Vec::new(),
ttl: None,
settings: Vec::new(),
sample_by: None,
order_by_raw: None,
},
}
}
pub fn with_schema(schema: S, name: impl Into<String>) -> Self {
let mut table = Table::new(name);
table.schema = Some(schema);
table
}
pub fn definition(&self) -> &TableDefinition<S> {
&self.def
}
pub fn definition_mut(&mut self) -> &mut TableDefinition<S> {
&mut self.def
}
pub fn name(&self) -> &str {
&self.def.name
}
pub fn columns(&self) -> &[Column<S>] {
&self.def.columns
}
pub fn column_mut(&mut self, index: usize) -> Option<&mut Column<S>> {
self.def.columns.get_mut(index)
}
pub fn foreign_keys(&self) -> &[ForeignKey] {
&self.def.foreign_keys
}
pub fn foreign_key_mut(&mut self, index: usize) -> Option<&mut ForeignKey> {
self.def.foreign_keys.get_mut(index)
}
fn push(&mut self, column: Column<S>) -> &mut Column<S> {
self.def.columns.push(column);
self.def.columns.last_mut().expect("just pushed")
}
fn add(&mut self, name: impl Into<String>, kind: ColumnType) -> &mut Column<S> {
self.push(Column::new(name, kind))
}
pub fn id(&mut self, name: impl Into<String>) -> &mut Column<S> {
let column = Column::new(name, ColumnType::BigInteger).with_auto_increment(true);
self.push(column).unsigned().primary()
}
pub fn string(&mut self, name: impl Into<String>, length: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::String).with_length(Some(length)))
}
pub fn text(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Text)
}
pub fn medium_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::MediumText)
}
pub fn long_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::LongText)
}
pub fn tiny_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::TinyInteger)
}
pub fn small_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::SmallInteger)
}
pub fn integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Integer)
}
pub fn big_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::BigInteger)
}
pub fn decimal(&mut self, name: impl Into<String>, precision: i64, scale: i64) -> Result<&mut Column<S>> {
if precision < 1 {
return Err(Error::Validation("DECIMAL precision must be at least 1.".into()));
}
if scale < 0 {
return Err(Error::Validation("DECIMAL scale must not be negative.".into()));
}
if scale > precision {
return Err(Error::Validation("DECIMAL scale must not exceed precision.".into()));
}
Ok(self.push(Column::new(name, ColumnType::Decimal).with_precision(Some(precision)).with_scale(Some(scale))))
}
pub fn uuid(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Uuid)
}
pub fn float(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Float)
}
pub fn boolean(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Boolean)
}
pub fn datetime(&mut self, name: impl Into<String>, precision: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Datetime).with_precision(Some(precision)))
}
pub fn timestamp(&mut self, name: impl Into<String>, precision: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Timestamp).with_precision(Some(precision)))
}
pub fn json(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Json)
}
pub fn binary(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.add(name, ColumnType::Binary)
}
pub fn enumeration<V: Into<String>>(
&mut self,
name: impl Into<String>,
values: impl IntoIterator<Item = V>,
) -> Result<&mut Column<S>> {
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()));
}
let mut column = Column::new(name, ColumnType::Enum);
column.def.enum_values = values;
Ok(self.push(column))
}
pub fn point(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Point).with_srid(Some(srid)))
}
pub fn linestring(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Linestring).with_srid(Some(srid)))
}
pub fn polygon(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Polygon).with_srid(Some(srid)))
}
pub fn timestamps(&mut self, precision: i64) -> &mut Self {
self.datetime("created_at", precision);
self.datetime("updated_at", precision);
self
}
fn sized(name: impl Into<String>, kind: ColumnType, length_or_precision: Option<i64>) -> Column<S> {
let string = kind == ColumnType::String;
Column::new(name, kind).with_length(if string { length_or_precision } else { None }).with_precision(if string {
None
} else {
length_or_precision
})
}
pub fn add_column(
&mut self,
name: impl Into<String>,
kind: ColumnType,
length_or_precision: Option<i64>,
) -> &mut Column<S> {
self.push(Self::sized(name, kind, length_or_precision))
}
pub fn modify_column(
&mut self,
name: impl Into<String>,
kind: ColumnType,
length_or_precision: Option<i64>,
) -> &mut Column<S> {
self.push(Self::sized(name, kind, length_or_precision)).modify()
}
pub fn index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
let name = Index::auto_name("idx_", &columns);
self.add_index(Index::new(name, columns, IndexType::Index))
}
pub fn unique_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
let name = Index::auto_name("uniq_", &columns);
self.add_index(Index::new(name, columns, IndexType::Unique))
}
pub fn add_index(&mut self, index: Index) -> Result<&mut Self> {
self.def.indexes.push(index.validated()?);
Ok(self)
}
pub fn drop_index(&mut self, name: impl Into<String>) -> &mut Self {
self.def.drop_indexes.push(name.into());
self
}
pub fn raw_column(&mut self, definition: impl Into<String>) -> &mut Self {
self.def.raw_column_defs.push(definition.into());
self
}
pub fn raw_index(&mut self, definition: impl Into<String>) -> &mut Self {
self.def.raw_index_defs.push(definition.into());
self
}
}
impl<S: Schema> Table<S> {
fn schema(&self) -> Result<&S> {
self.schema.as_ref().ok_or_else(|| {
Error::Validation(
"Cannot compile a Table without a Schema. Use Schema::table($name) to obtain a builder.".into(),
)
})
}
pub fn create(&self) -> Result<Statement> {
self.schema()?.compile_create(self, false)
}
pub fn create_if_not_exists(&self) -> Result<Statement> {
self.schema()?.compile_create(self, true)
}
pub fn alter(&self) -> Result<Statement> {
self.schema()?.compile_alter(self)
}
pub fn drop(&self) -> Result<Statement> {
self.schema()?.compile_drop(&self.def.name, false)
}
pub fn drop_if_exists(&self) -> Result<Statement> {
self.schema()?.compile_drop(&self.def.name, true)
}
pub fn truncate(&self) -> Result<Statement> {
self.schema()?.compile_truncate(&self.def.name)
}
pub fn rename(&self, to: &str) -> Result<Statement> {
self.schema()?.compile_rename(&self.def.name, to)
}
}
impl<S: Serial> Table<S> {
pub fn serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::Serial).with_auto_increment(true))
}
pub fn big_serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::BigSerial).with_auto_increment(true))
}
pub fn small_serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
self.push(Column::new(name, ColumnType::SmallSerial).with_auto_increment(true))
}
}
impl<S: Checks> Table<S> {
pub fn check(&mut self, name: impl Into<String>, expression: impl Into<String>) -> Result<&mut Self> {
self.def.checks.push(CheckConstraint::new(name, expression)?);
Ok(self)
}
}
impl<S: ColumnAlterations> Table<S> {
pub fn rename_column(&mut self, from: impl Into<String>, to: impl Into<String>) -> &mut Self {
self.def.rename_columns.push(RenameColumn::new(from, to));
self
}
pub fn drop_column(&mut self, name: impl Into<String>) -> &mut Self {
self.def.drop_columns.push(name.into());
self
}
}
impl<S: CompositePrimary> Table<S> {
pub fn primary<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
if columns.len() < 2 {
return Err(Error::Validation(
"Table::primary(array) requires at least two columns; use Column::primary() for single-column keys."
.into(),
));
}
if let Some(bad) = columns.iter().find(|c| !names::is_identifier(c)) {
return Err(Error::Validation(format!("Invalid column name in composite primary key: {bad}")));
}
self.def.composite_primary_key = columns;
Ok(self)
}
}
impl<S: InlineForeignKey> Table<S> {
pub fn foreign_key(&mut self, column: impl Into<String>) -> &mut ForeignKey {
self.def.foreign_keys.push(ForeignKey::new(column));
self.def.foreign_keys.last_mut().expect("just pushed")
}
}
impl<S: ForeignKeys> Table<S> {
pub fn add_foreign_key(&mut self, column: impl Into<String>) -> &mut ForeignKey {
self.foreign_key(column)
}
pub fn drop_foreign_key(&mut self, name: impl Into<String>) -> &mut Self {
self.def.drop_foreign_keys.push(name.into());
self
}
}
impl<S: FulltextSpatialIndex> Table<S> {
pub fn fulltext_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
let name = Index::auto_name("ft_", &columns);
self.add_index(Index::new(name, columns, IndexType::Fulltext))
}
pub fn spatial_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
let name = Index::auto_name("sp_", &columns);
self.add_index(Index::new(name, columns, IndexType::Spatial))
}
}
impl<S: StandardPartitioning> Table<S> {
pub fn partition_by_range(&mut self, expression: impl Into<String>) -> &mut Self {
self.partition(PartitionType::Range, expression.into(), None)
}
pub fn partition_by_list(&mut self, expression: impl Into<String>) -> &mut Self {
self.partition(PartitionType::List, expression.into(), None)
}
pub fn partition_by_hash(&mut self, expression: impl Into<String>, partitions: Option<i64>) -> Result<&mut Self> {
if let Some(count) = partitions
&& count < 1
{
return Err(Error::Validation("Partition count must be at least 1.".into()));
}
Ok(self.partition(PartitionType::Hash, expression.into(), partitions))
}
fn partition(&mut self, kind: PartitionType, expression: String, count: Option<i64>) -> &mut Self {
self.def.partition_type = Some(kind);
self.def.partition_expression = expression;
self.def.partition_count = count;
self
}
}
impl Table<PostgreSql> {
pub fn vector(&mut self, name: impl Into<String>, dimensions: i64) -> &mut Column<PostgreSql> {
self.push(Column::new(name, ColumnType::Vector).with_dimensions(Some(dimensions)))
}
}
impl Table<MongoDb> {
pub fn vector(&mut self, name: impl Into<String>) -> &mut Column<MongoDb> {
self.add(name, ColumnType::Vector)
}
}
impl Table<ClickHouse> {
pub fn vector(&mut self, name: impl Into<String>) -> &mut Column<ClickHouse> {
self.add(name, ColumnType::Vector)
}
pub fn array(&mut self, name: impl Into<String>, element: ColumnType) -> &mut Column<ClickHouse> {
self.add(name, ColumnType::Array).as_array(element)
}
pub fn tuple(&mut self, name: impl Into<String>, elements: Vec<ColumnType>) -> Result<&mut Column<ClickHouse>> {
let mut column = Column::new(name, ColumnType::Tuple);
column.as_tuple(elements)?;
Ok(self.push(column))
}
pub fn fixed_string(&mut self, name: impl Into<String>, length: i64) -> Result<&mut Column<ClickHouse>> {
let mut column = Column::new(name, ColumnType::String).with_length(Some(length));
column.as_fixed_string(length)?;
Ok(self.push(column))
}
pub fn engine(&mut self, engine: Engine, args: &[&str]) -> Result<&mut Self> {
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
if engine == Engine::CollapsingMergeTree && args.is_empty() {
return Err(Error::Validation("CollapsingMergeTree requires a sign column.".into()));
}
if engine == Engine::ReplicatedMergeTree && args.len() < 2 {
return Err(Error::Validation("ReplicatedMergeTree requires zookeeper_path and replica_name.".into()));
}
self.def.engine = Some(engine);
self.def.engine_args = args;
Ok(self)
}
pub fn order_by<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
if let Some(bad) = columns.iter().find(|c| !names::is_identifier(c)) {
return Err(Error::Validation(format!("Invalid column name in ORDER BY: {bad}")));
}
self.def.order_by = columns;
Ok(self)
}
pub fn order_by_raw(&mut self, expression: &str) -> Result<&mut Self> {
self.def.order_by_raw = Some(self::expression(
expression,
"Raw ORDER BY expression must not be empty.",
"Raw ORDER BY expression must not contain \";\".",
)?);
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)
}
pub fn settings<K: Into<String>>(&mut self, settings: impl IntoIterator<Item = (K, Value)>) -> Result<&mut Self> {
let mut sanitized: Vec<(String, String)> = Vec::new();
for (key, value) in settings {
let key = key.into();
if !names::is_identifier(&key) {
return Err(Error::Validation(format!("Invalid setting name: {key}")));
}
let rendered = match &value {
Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
Value::Int(i) => i.to_string(),
Value::Float(f) => names::fixed(*f),
Value::Str(s) => {
let s = String::from_utf8_lossy(s.as_bytes()).into_owned();
if !names::is_setting_value(&s) {
return Err(Error::Validation(format!(
"Invalid setting value for {key}: must match [A-Za-z0-9_.\\-+/]+"
)));
}
s
}
_ => {
return Err(Error::Validation(format!(
"Setting value for {key} must be string, int, float, or bool."
)));
}
};
match sanitized.iter_mut().find(|(k, _)| *k == key) {
Some(entry) => entry.1 = rendered,
None => sanitized.push((key, rendered)),
}
}
self.def.settings = sanitized;
Ok(self)
}
pub fn partition_by(&mut self, expression: impl Into<String>) -> &mut Self {
self.def.partition_expression = expression.into();
self
}
pub fn sample_by(&mut self, expression: &str) -> Result<&mut Self> {
self.def.sample_by = Some(self::expression(
expression,
"SAMPLE BY expression must not be empty.",
"SAMPLE BY expression must not contain \";\".",
)?);
Ok(self)
}
}