1use std::fmt;
11
12use super::column::{Column, expression};
13use super::enums::{ColumnType, Engine, ForeignKeyAction, IndexType, PartitionType};
14use super::index::{CheckConstraint, Index, RenameColumn};
15use super::{ClickHouse, MongoDb, PostgreSql, Schema, names};
16use crate::builder::Statement;
17use crate::error::{Error, Result};
18use crate::value::Value;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ForeignKey {
26 pub column: String,
28 pub ref_table: String,
30 pub ref_column: String,
32 pub on_delete: Option<ForeignKeyAction>,
34 pub on_update: Option<ForeignKeyAction>,
36}
37
38impl ForeignKey {
39 pub fn new(column: impl Into<String>) -> Self {
43 ForeignKey {
44 column: column.into(),
45 ref_table: String::new(),
46 ref_column: String::new(),
47 on_delete: None,
48 on_update: None,
49 }
50 }
51
52 pub fn references(&mut self, column: impl Into<String>) -> &mut Self {
56 self.ref_column = column.into();
57 self
58 }
59
60 pub fn on(&mut self, table: impl Into<String>) -> &mut Self {
64 self.ref_table = table.into();
65 self
66 }
67
68 pub fn on_delete(&mut self, action: ForeignKeyAction) -> &mut Self {
72 self.on_delete = Some(action);
73 self
74 }
75
76 pub fn on_update(&mut self, action: ForeignKeyAction) -> &mut Self {
80 self.on_update = Some(action);
81 self
82 }
83}
84
85pub struct TableDefinition<S> {
90 pub name: String,
92 pub columns: Vec<Column<S>>,
94 pub indexes: Vec<Index>,
96 pub foreign_keys: Vec<ForeignKey>,
98 pub drop_columns: Vec<String>,
100 pub rename_columns: Vec<RenameColumn>,
102 pub drop_indexes: Vec<String>,
104 pub drop_foreign_keys: Vec<String>,
106 pub raw_column_defs: Vec<String>,
108 pub raw_index_defs: Vec<String>,
110 pub checks: Vec<CheckConstraint>,
112 pub composite_primary_key: Vec<String>,
114 pub order_by: Vec<String>,
116 pub partition_type: Option<PartitionType>,
118 pub partition_expression: String,
120 pub partition_count: Option<i64>,
122 pub engine: Option<Engine>,
124 pub engine_args: Vec<String>,
126 pub ttl: Option<String>,
128 pub settings: Vec<(String, String)>,
130 pub sample_by: Option<String>,
132 pub order_by_raw: Option<String>,
134}
135
136impl<S> Clone for TableDefinition<S> {
137 fn clone(&self) -> Self {
138 TableDefinition {
139 name: self.name.clone(),
140 columns: self.columns.clone(),
141 indexes: self.indexes.clone(),
142 foreign_keys: self.foreign_keys.clone(),
143 drop_columns: self.drop_columns.clone(),
144 rename_columns: self.rename_columns.clone(),
145 drop_indexes: self.drop_indexes.clone(),
146 drop_foreign_keys: self.drop_foreign_keys.clone(),
147 raw_column_defs: self.raw_column_defs.clone(),
148 raw_index_defs: self.raw_index_defs.clone(),
149 checks: self.checks.clone(),
150 composite_primary_key: self.composite_primary_key.clone(),
151 order_by: self.order_by.clone(),
152 partition_type: self.partition_type,
153 partition_expression: self.partition_expression.clone(),
154 partition_count: self.partition_count,
155 engine: self.engine,
156 engine_args: self.engine_args.clone(),
157 ttl: self.ttl.clone(),
158 settings: self.settings.clone(),
159 sample_by: self.sample_by.clone(),
160 order_by_raw: self.order_by_raw.clone(),
161 }
162 }
163}
164
165impl<S> fmt::Debug for TableDefinition<S> {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_struct("TableDefinition")
168 .field("name", &self.name)
169 .field("columns", &self.columns)
170 .field("indexes", &self.indexes)
171 .field("foreign_keys", &self.foreign_keys)
172 .finish_non_exhaustive()
173 }
174}
175
176pub struct Table<S> {
207 schema: Option<S>,
208 def: TableDefinition<S>,
209}
210
211impl<S: Clone> Clone for Table<S> {
212 fn clone(&self) -> Self {
213 Table { schema: self.schema.clone(), def: self.def.clone() }
214 }
215}
216
217impl<S> fmt::Debug for Table<S> {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 self.def.fmt(f)
220 }
221}
222
223pub trait Serial: Schema {}
227pub trait Checks: Schema {}
231pub trait ColumnAlterations: Schema {}
235pub trait CompositePrimary: Schema {}
239pub trait InlineForeignKey: Schema {}
243pub trait ForeignKeys: InlineForeignKey {}
247pub trait FulltextSpatialIndex: Schema {}
251pub trait StandardPartitioning: Schema {}
255
256impl<S> Table<S> {
257 pub fn new(name: impl Into<String>) -> Self {
262 Table {
263 schema: None,
264 def: TableDefinition {
265 name: name.into(),
266 columns: Vec::new(),
267 indexes: Vec::new(),
268 foreign_keys: Vec::new(),
269 drop_columns: Vec::new(),
270 rename_columns: Vec::new(),
271 drop_indexes: Vec::new(),
272 drop_foreign_keys: Vec::new(),
273 raw_column_defs: Vec::new(),
274 raw_index_defs: Vec::new(),
275 checks: Vec::new(),
276 composite_primary_key: Vec::new(),
277 order_by: Vec::new(),
278 partition_type: None,
279 partition_expression: String::new(),
280 partition_count: None,
281 engine: None,
282 engine_args: Vec::new(),
283 ttl: None,
284 settings: Vec::new(),
285 sample_by: None,
286 order_by_raw: None,
287 },
288 }
289 }
290
291 pub fn with_schema(schema: S, name: impl Into<String>) -> Self {
296 let mut table = Table::new(name);
297 table.schema = Some(schema);
298 table
299 }
300
301 pub fn definition(&self) -> &TableDefinition<S> {
305 &self.def
306 }
307
308 pub fn definition_mut(&mut self) -> &mut TableDefinition<S> {
311 &mut self.def
312 }
313
314 pub fn name(&self) -> &str {
318 &self.def.name
319 }
320
321 pub fn columns(&self) -> &[Column<S>] {
325 &self.def.columns
326 }
327
328 pub fn column_mut(&mut self, index: usize) -> Option<&mut Column<S>> {
330 self.def.columns.get_mut(index)
331 }
332
333 pub fn foreign_keys(&self) -> &[ForeignKey] {
337 &self.def.foreign_keys
338 }
339
340 pub fn foreign_key_mut(&mut self, index: usize) -> Option<&mut ForeignKey> {
342 self.def.foreign_keys.get_mut(index)
343 }
344
345 fn push(&mut self, column: Column<S>) -> &mut Column<S> {
346 self.def.columns.push(column);
347 self.def.columns.last_mut().expect("just pushed")
348 }
349
350 fn add(&mut self, name: impl Into<String>, kind: ColumnType) -> &mut Column<S> {
351 self.push(Column::new(name, kind))
352 }
353
354 pub fn id(&mut self, name: impl Into<String>) -> &mut Column<S> {
359 let column = Column::new(name, ColumnType::BigInteger).with_auto_increment(true);
360 self.push(column).unsigned().primary()
361 }
362
363 pub fn string(&mut self, name: impl Into<String>, length: i64) -> &mut Column<S> {
367 self.push(Column::new(name, ColumnType::String).with_length(Some(length)))
368 }
369
370 pub fn text(&mut self, name: impl Into<String>) -> &mut Column<S> {
374 self.add(name, ColumnType::Text)
375 }
376
377 pub fn medium_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
381 self.add(name, ColumnType::MediumText)
382 }
383
384 pub fn long_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
388 self.add(name, ColumnType::LongText)
389 }
390
391 pub fn tiny_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
395 self.add(name, ColumnType::TinyInteger)
396 }
397
398 pub fn small_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
402 self.add(name, ColumnType::SmallInteger)
403 }
404
405 pub fn integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
409 self.add(name, ColumnType::Integer)
410 }
411
412 pub fn big_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
416 self.add(name, ColumnType::BigInteger)
417 }
418
419 pub fn decimal(&mut self, name: impl Into<String>, precision: i64, scale: i64) -> Result<&mut Column<S>> {
425 if precision < 1 {
426 return Err(Error::Validation("DECIMAL precision must be at least 1.".into()));
427 }
428 if scale < 0 {
429 return Err(Error::Validation("DECIMAL scale must not be negative.".into()));
430 }
431 if scale > precision {
432 return Err(Error::Validation("DECIMAL scale must not exceed precision.".into()));
433 }
434 Ok(self.push(Column::new(name, ColumnType::Decimal).with_precision(Some(precision)).with_scale(Some(scale))))
435 }
436
437 pub fn uuid(&mut self, name: impl Into<String>) -> &mut Column<S> {
441 self.add(name, ColumnType::Uuid)
442 }
443
444 pub fn float(&mut self, name: impl Into<String>) -> &mut Column<S> {
448 self.add(name, ColumnType::Float)
449 }
450
451 pub fn boolean(&mut self, name: impl Into<String>) -> &mut Column<S> {
455 self.add(name, ColumnType::Boolean)
456 }
457
458 pub fn datetime(&mut self, name: impl Into<String>, precision: i64) -> &mut Column<S> {
463 self.push(Column::new(name, ColumnType::Datetime).with_precision(Some(precision)))
464 }
465
466 pub fn timestamp(&mut self, name: impl Into<String>, precision: i64) -> &mut Column<S> {
471 self.push(Column::new(name, ColumnType::Timestamp).with_precision(Some(precision)))
472 }
473
474 pub fn json(&mut self, name: impl Into<String>) -> &mut Column<S> {
478 self.add(name, ColumnType::Json)
479 }
480
481 pub fn binary(&mut self, name: impl Into<String>) -> &mut Column<S> {
485 self.add(name, ColumnType::Binary)
486 }
487
488 pub fn enumeration<V: Into<String>>(
492 &mut self,
493 name: impl Into<String>,
494 values: impl IntoIterator<Item = V>,
495 ) -> Result<&mut Column<S>> {
496 let values: Vec<String> = values.into_iter().map(Into::into).collect();
497 if values.is_empty() {
498 return Err(Error::Validation("enum() requires at least one allowed value.".into()));
499 }
500 let mut column = Column::new(name, ColumnType::Enum);
501 column.def.enum_values = values;
502 Ok(self.push(column))
503 }
504
505 pub fn point(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
509 self.push(Column::new(name, ColumnType::Point).with_srid(Some(srid)))
510 }
511
512 pub fn linestring(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
516 self.push(Column::new(name, ColumnType::Linestring).with_srid(Some(srid)))
517 }
518
519 pub fn polygon(&mut self, name: impl Into<String>, srid: i64) -> &mut Column<S> {
523 self.push(Column::new(name, ColumnType::Polygon).with_srid(Some(srid)))
524 }
525
526 pub fn timestamps(&mut self, precision: i64) -> &mut Self {
531 self.datetime("created_at", precision);
532 self.datetime("updated_at", precision);
533 self
534 }
535
536 fn sized(name: impl Into<String>, kind: ColumnType, length_or_precision: Option<i64>) -> Column<S> {
537 let string = kind == ColumnType::String;
538 Column::new(name, kind).with_length(if string { length_or_precision } else { None }).with_precision(if string {
539 None
540 } else {
541 length_or_precision
542 })
543 }
544
545 pub fn add_column(
550 &mut self,
551 name: impl Into<String>,
552 kind: ColumnType,
553 length_or_precision: Option<i64>,
554 ) -> &mut Column<S> {
555 self.push(Self::sized(name, kind, length_or_precision))
556 }
557
558 pub fn modify_column(
562 &mut self,
563 name: impl Into<String>,
564 kind: ColumnType,
565 length_or_precision: Option<i64>,
566 ) -> &mut Column<S> {
567 self.push(Self::sized(name, kind, length_or_precision)).modify()
568 }
569
570 pub fn index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
574 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
575 let name = Index::auto_name("idx_", &columns);
576 self.add_index(Index::new(name, columns, IndexType::Index))
577 }
578
579 pub fn unique_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
583 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
584 let name = Index::auto_name("uniq_", &columns);
585 self.add_index(Index::new(name, columns, IndexType::Unique))
586 }
587
588 pub fn add_index(&mut self, index: Index) -> Result<&mut Self> {
592 self.def.indexes.push(index.validated()?);
593 Ok(self)
594 }
595
596 pub fn drop_index(&mut self, name: impl Into<String>) -> &mut Self {
600 self.def.drop_indexes.push(name.into());
601 self
602 }
603
604 pub fn raw_column(&mut self, definition: impl Into<String>) -> &mut Self {
608 self.def.raw_column_defs.push(definition.into());
609 self
610 }
611
612 pub fn raw_index(&mut self, definition: impl Into<String>) -> &mut Self {
616 self.def.raw_index_defs.push(definition.into());
617 self
618 }
619}
620
621impl<S: Schema> Table<S> {
622 fn schema(&self) -> Result<&S> {
623 self.schema.as_ref().ok_or_else(|| {
624 Error::Validation(
625 "Cannot compile a Table without a Schema. Use Schema::table($name) to obtain a builder.".into(),
626 )
627 })
628 }
629
630 pub fn create(&self) -> Result<Statement> {
634 self.schema()?.compile_create(self, false)
635 }
636
637 pub fn create_if_not_exists(&self) -> Result<Statement> {
641 self.schema()?.compile_create(self, true)
642 }
643
644 pub fn alter(&self) -> Result<Statement> {
649 self.schema()?.compile_alter(self)
650 }
651
652 pub fn drop(&self) -> Result<Statement> {
656 self.schema()?.compile_drop(&self.def.name, false)
657 }
658
659 pub fn drop_if_exists(&self) -> Result<Statement> {
663 self.schema()?.compile_drop(&self.def.name, true)
664 }
665
666 pub fn truncate(&self) -> Result<Statement> {
670 self.schema()?.compile_truncate(&self.def.name)
671 }
672
673 pub fn rename(&self, to: &str) -> Result<Statement> {
677 self.schema()?.compile_rename(&self.def.name, to)
678 }
679}
680
681impl<S: Serial> Table<S> {
682 pub fn serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
686 self.push(Column::new(name, ColumnType::Serial).with_auto_increment(true))
687 }
688
689 pub fn big_serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
693 self.push(Column::new(name, ColumnType::BigSerial).with_auto_increment(true))
694 }
695
696 pub fn small_serial(&mut self, name: impl Into<String>) -> &mut Column<S> {
700 self.push(Column::new(name, ColumnType::SmallSerial).with_auto_increment(true))
701 }
702}
703
704impl<S: Checks> Table<S> {
705 pub fn check(&mut self, name: impl Into<String>, expression: impl Into<String>) -> Result<&mut Self> {
709 self.def.checks.push(CheckConstraint::new(name, expression)?);
710 Ok(self)
711 }
712}
713
714impl<S: ColumnAlterations> Table<S> {
715 pub fn rename_column(&mut self, from: impl Into<String>, to: impl Into<String>) -> &mut Self {
719 self.def.rename_columns.push(RenameColumn::new(from, to));
720 self
721 }
722
723 pub fn drop_column(&mut self, name: impl Into<String>) -> &mut Self {
727 self.def.drop_columns.push(name.into());
728 self
729 }
730}
731
732impl<S: CompositePrimary> Table<S> {
733 pub fn primary<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
738 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
739 if columns.len() < 2 {
740 return Err(Error::Validation(
741 "Table::primary(array) requires at least two columns; use Column::primary() for single-column keys."
742 .into(),
743 ));
744 }
745 if let Some(bad) = columns.iter().find(|c| !names::is_identifier(c)) {
746 return Err(Error::Validation(format!("Invalid column name in composite primary key: {bad}")));
747 }
748 self.def.composite_primary_key = columns;
749 Ok(self)
750 }
751}
752
753impl<S: InlineForeignKey> Table<S> {
754 pub fn foreign_key(&mut self, column: impl Into<String>) -> &mut ForeignKey {
758 self.def.foreign_keys.push(ForeignKey::new(column));
759 self.def.foreign_keys.last_mut().expect("just pushed")
760 }
761}
762
763impl<S: ForeignKeys> Table<S> {
764 pub fn add_foreign_key(&mut self, column: impl Into<String>) -> &mut ForeignKey {
769 self.foreign_key(column)
770 }
771
772 pub fn drop_foreign_key(&mut self, name: impl Into<String>) -> &mut Self {
776 self.def.drop_foreign_keys.push(name.into());
777 self
778 }
779}
780
781impl<S: FulltextSpatialIndex> Table<S> {
782 pub fn fulltext_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
786 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
787 let name = Index::auto_name("ft_", &columns);
788 self.add_index(Index::new(name, columns, IndexType::Fulltext))
789 }
790
791 pub fn spatial_index<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
795 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
796 let name = Index::auto_name("sp_", &columns);
797 self.add_index(Index::new(name, columns, IndexType::Spatial))
798 }
799}
800
801impl<S: StandardPartitioning> Table<S> {
802 pub fn partition_by_range(&mut self, expression: impl Into<String>) -> &mut Self {
806 self.partition(PartitionType::Range, expression.into(), None)
807 }
808
809 pub fn partition_by_list(&mut self, expression: impl Into<String>) -> &mut Self {
813 self.partition(PartitionType::List, expression.into(), None)
814 }
815
816 pub fn partition_by_hash(&mut self, expression: impl Into<String>, partitions: Option<i64>) -> Result<&mut Self> {
820 if let Some(count) = partitions
821 && count < 1
822 {
823 return Err(Error::Validation("Partition count must be at least 1.".into()));
824 }
825 Ok(self.partition(PartitionType::Hash, expression.into(), partitions))
826 }
827
828 fn partition(&mut self, kind: PartitionType, expression: String, count: Option<i64>) -> &mut Self {
829 self.def.partition_type = Some(kind);
830 self.def.partition_expression = expression;
831 self.def.partition_count = count;
832 self
833 }
834}
835
836impl Table<PostgreSql> {
837 pub fn vector(&mut self, name: impl Into<String>, dimensions: i64) -> &mut Column<PostgreSql> {
841 self.push(Column::new(name, ColumnType::Vector).with_dimensions(Some(dimensions)))
842 }
843}
844
845impl Table<MongoDb> {
846 pub fn vector(&mut self, name: impl Into<String>) -> &mut Column<MongoDb> {
850 self.add(name, ColumnType::Vector)
851 }
852}
853
854impl Table<ClickHouse> {
855 pub fn vector(&mut self, name: impl Into<String>) -> &mut Column<ClickHouse> {
859 self.add(name, ColumnType::Vector)
860 }
861
862 pub fn array(&mut self, name: impl Into<String>, element: ColumnType) -> &mut Column<ClickHouse> {
866 self.add(name, ColumnType::Array).as_array(element)
867 }
868
869 pub fn tuple(&mut self, name: impl Into<String>, elements: Vec<ColumnType>) -> Result<&mut Column<ClickHouse>> {
873 let mut column = Column::new(name, ColumnType::Tuple);
874 column.as_tuple(elements)?;
875 Ok(self.push(column))
876 }
877
878 pub fn fixed_string(&mut self, name: impl Into<String>, length: i64) -> Result<&mut Column<ClickHouse>> {
882 let mut column = Column::new(name, ColumnType::String).with_length(Some(length));
883 column.as_fixed_string(length)?;
884 Ok(self.push(column))
885 }
886
887 pub fn engine(&mut self, engine: Engine, args: &[&str]) -> Result<&mut Self> {
892 let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
893 if engine == Engine::CollapsingMergeTree && args.is_empty() {
894 return Err(Error::Validation("CollapsingMergeTree requires a sign column.".into()));
895 }
896 if engine == Engine::ReplicatedMergeTree && args.len() < 2 {
897 return Err(Error::Validation("ReplicatedMergeTree requires zookeeper_path and replica_name.".into()));
898 }
899 self.def.engine = Some(engine);
900 self.def.engine_args = args;
901 Ok(self)
902 }
903
904 pub fn order_by<C: Into<String>>(&mut self, columns: impl IntoIterator<Item = C>) -> Result<&mut Self> {
909 let columns: Vec<String> = columns.into_iter().map(Into::into).collect();
910 if let Some(bad) = columns.iter().find(|c| !names::is_identifier(c)) {
911 return Err(Error::Validation(format!("Invalid column name in ORDER BY: {bad}")));
912 }
913 self.def.order_by = columns;
914 Ok(self)
915 }
916
917 pub fn order_by_raw(&mut self, expression: &str) -> Result<&mut Self> {
922 self.def.order_by_raw = Some(self::expression(
923 expression,
924 "Raw ORDER BY expression must not be empty.",
925 "Raw ORDER BY expression must not contain \";\".",
926 )?);
927 Ok(self)
928 }
929
930 pub fn ttl(&mut self, expression: &str) -> Result<&mut Self> {
934 self.def.ttl = Some(self::expression(
935 expression,
936 "TTL expression must not be empty.",
937 "TTL expression must not contain \";\".",
938 )?);
939 Ok(self)
940 }
941
942 pub fn settings<K: Into<String>>(&mut self, settings: impl IntoIterator<Item = (K, Value)>) -> Result<&mut Self> {
948 let mut sanitized: Vec<(String, String)> = Vec::new();
949 for (key, value) in settings {
950 let key = key.into();
951 if !names::is_identifier(&key) {
952 return Err(Error::Validation(format!("Invalid setting name: {key}")));
953 }
954 let rendered = match &value {
955 Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
956 Value::Int(i) => i.to_string(),
957 Value::Float(f) => names::fixed(*f),
958 Value::Str(s) => {
959 let s = String::from_utf8_lossy(s.as_bytes()).into_owned();
960 if !names::is_setting_value(&s) {
961 return Err(Error::Validation(format!(
962 "Invalid setting value for {key}: must match [A-Za-z0-9_.\\-+/]+"
963 )));
964 }
965 s
966 }
967 _ => {
968 return Err(Error::Validation(format!(
969 "Setting value for {key} must be string, int, float, or bool."
970 )));
971 }
972 };
973 match sanitized.iter_mut().find(|(k, _)| *k == key) {
974 Some(entry) => entry.1 = rendered,
975 None => sanitized.push((key, rendered)),
976 }
977 }
978 self.def.settings = sanitized;
979 Ok(self)
980 }
981
982 pub fn partition_by(&mut self, expression: impl Into<String>) -> &mut Self {
986 self.def.partition_expression = expression.into();
987 self
988 }
989
990 pub fn sample_by(&mut self, expression: &str) -> Result<&mut Self> {
994 self.def.sample_by = Some(self::expression(
995 expression,
996 "SAMPLE BY expression must not be empty.",
997 "SAMPLE BY expression must not contain \";\".",
998 )?);
999 Ok(self)
1000 }
1001}