Skip to main content

utopia_query/schema/
table.rs

1//! [`Table`]: a fluent table blueprint, compiled by its schema into
2//! `CREATE TABLE`, `ALTER TABLE` and the other table statements; and
3//! [`ForeignKey`], a foreign key declared on it.
4//!
5//! Factories and alterations every dialect has are inherent methods; the
6//! others are gated by marker traits the dialects implement ([`Serial`],
7//! [`Checks`], [`InlineForeignKey`], ...), as PHP's dialect table classes
8//! each use only the traits they support.
9
10use 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/// A foreign key: `FOREIGN KEY (column) REFERENCES table (column)` with
21/// optional `ON DELETE` / `ON UPDATE` actions.
22///
23/// PHP: `Utopia\Query\Schema\ForeignKey` and its dialect classes.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ForeignKey {
26    /// The local column.
27    pub column: String,
28    /// The referenced table.
29    pub ref_table: String,
30    /// The referenced column.
31    pub ref_column: String,
32    /// The action on delete.
33    pub on_delete: Option<ForeignKeyAction>,
34    /// The action on update.
35    pub on_update: Option<ForeignKeyAction>,
36}
37
38impl ForeignKey {
39    /// A foreign key on `column`, referencing nothing yet.
40    ///
41    /// PHP: `new ForeignKey($table, $column)`.
42    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    /// Sets the referenced column.
53    ///
54    /// PHP: `references()`.
55    pub fn references(&mut self, column: impl Into<String>) -> &mut Self {
56        self.ref_column = column.into();
57        self
58    }
59
60    /// Sets the referenced table.
61    ///
62    /// PHP: `on()`.
63    pub fn on(&mut self, table: impl Into<String>) -> &mut Self {
64        self.ref_table = table.into();
65        self
66    }
67
68    /// Sets the action on delete.
69    ///
70    /// PHP: `onDelete()`.
71    pub fn on_delete(&mut self, action: ForeignKeyAction) -> &mut Self {
72        self.on_delete = Some(action);
73        self
74    }
75
76    /// Sets the action on update.
77    ///
78    /// PHP: `onUpdate()`.
79    pub fn on_update(&mut self, action: ForeignKeyAction) -> &mut Self {
80        self.on_update = Some(action);
81        self
82    }
83}
84
85/// Everything a table blueprint holds: added columns, indexes, keys, and
86/// the alterations, partitioning and engine options set on it.
87///
88/// PHP: the public properties of `Utopia\Query\Schema\Table`.
89pub struct TableDefinition<S> {
90    /// The table name.
91    pub name: String,
92    /// The columns to add (or modify).
93    pub columns: Vec<Column<S>>,
94    /// The indexes to add.
95    pub indexes: Vec<Index>,
96    /// The foreign keys to add.
97    pub foreign_keys: Vec<ForeignKey>,
98    /// The columns to drop.
99    pub drop_columns: Vec<String>,
100    /// The columns to rename.
101    pub rename_columns: Vec<RenameColumn>,
102    /// The indexes to drop.
103    pub drop_indexes: Vec<String>,
104    /// The foreign keys to drop.
105    pub drop_foreign_keys: Vec<String>,
106    /// Raw column definitions.
107    pub raw_column_defs: Vec<String>,
108    /// Raw index definitions.
109    pub raw_index_defs: Vec<String>,
110    /// Named `CHECK` constraints.
111    pub checks: Vec<CheckConstraint>,
112    /// The columns of a composite primary key.
113    pub composite_primary_key: Vec<String>,
114    /// The ClickHouse `ORDER BY` columns.
115    pub order_by: Vec<String>,
116    /// How the table is partitioned.
117    pub partition_type: Option<PartitionType>,
118    /// The partition expression.
119    pub partition_expression: String,
120    /// The number of partitions (`PARTITIONS n`).
121    pub partition_count: Option<i64>,
122    /// The ClickHouse engine.
123    pub engine: Option<Engine>,
124    /// The engine's arguments.
125    pub engine_args: Vec<String>,
126    /// The ClickHouse table TTL.
127    pub ttl: Option<String>,
128    /// The ClickHouse `SETTINGS`, rendered.
129    pub settings: Vec<(String, String)>,
130    /// The ClickHouse `SAMPLE BY` expression.
131    pub sample_by: Option<String>,
132    /// A raw ClickHouse `ORDER BY` expression.
133    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
176/// A table blueprint for the dialect `S`: columns, indexes, keys and
177/// alterations, compiled by the schema it came from.
178///
179/// ```
180/// use utopia_query::schema::{MySql, Schema};
181///
182/// let mut users = MySql::new().table("users");
183/// users.id("id");
184/// users.string("email", 255).unique();
185/// users.foreign_key("team_id").references("id").on("teams");
186/// assert_eq!(
187///     users.create()?.query,
188///     "CREATE TABLE `users` (`id` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, `email` VARCHAR(255) NOT NULL, \
189///      PRIMARY KEY (`id`), UNIQUE (`email`), FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`))"
190/// );
191/// # Ok::<(), utopia_query::Error>(())
192/// ```
193///
194/// ```php
195/// use Utopia\Query\Schema\MySQL;
196///
197/// $users = (new MySQL())->table('users');
198/// $users->id();
199/// $users->string('email')->unique();
200/// $users->foreignKey('team_id')->references('id')->on('teams');
201/// echo $users->create()->query, "\n";
202/// ```
203///
204/// PHP: `Utopia\Query\Schema\Table` and its dialect classes (`Table\MySQL`,
205/// `Table\PostgreSQL`, `Table\SQLite`, `Table\ClickHouse`, `Table\MongoDB`).
206pub 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
223/// Dialects with `SERIAL` column factories.
224///
225/// PHP: `Table\Trait\Serial`.
226pub trait Serial: Schema {}
227/// Dialects with named table-level `CHECK` constraints (and column-level ones).
228///
229/// PHP: `Table\Trait\Checks`.
230pub trait Checks: Schema {}
231/// Dialects that drop and rename columns in `ALTER TABLE`.
232///
233/// PHP: `Table\Trait\ColumnAlterations`.
234pub trait ColumnAlterations: Schema {}
235/// Dialects with composite primary keys.
236///
237/// PHP: `Table\Trait\CompositePrimary`.
238pub trait CompositePrimary: Schema {}
239/// Dialects with inline foreign keys in `CREATE TABLE`.
240///
241/// PHP: `Table\Trait\InlineForeignKey`.
242pub trait InlineForeignKey: Schema {}
243/// Dialects that also add and drop foreign keys in `ALTER TABLE`.
244///
245/// PHP: `Table\Trait\ForeignKeys`.
246pub trait ForeignKeys: InlineForeignKey {}
247/// Dialects with full-text and spatial indexes.
248///
249/// PHP: `Table\Trait\FulltextSpatialIndex`.
250pub trait FulltextSpatialIndex: Schema {}
251/// Dialects with `PARTITION BY RANGE / LIST / HASH`.
252///
253/// PHP: `Table\Trait\StandardPartitioning`.
254pub trait StandardPartitioning: Schema {}
255
256impl<S> Table<S> {
257    /// A blueprint of table `name` without a schema: it collects columns and
258    /// alterations but cannot compile (its terminal methods fail).
259    ///
260    /// PHP: `new Table(null, $name)`.
261    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    /// A blueprint of table `name` compiled by `schema` (what
292    /// [`Schema::table`] returns).
293    ///
294    /// PHP: `new Table($schema, $name)`.
295    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    /// Everything the blueprint holds.
302    ///
303    /// PHP: the table's public properties.
304    pub fn definition(&self) -> &TableDefinition<S> {
305        &self.def
306    }
307
308    /// Everything the blueprint holds, to set directly: nothing here is
309    /// validated, as nothing is when PHP sets a table's properties.
310    pub fn definition_mut(&mut self) -> &mut TableDefinition<S> {
311        &mut self.def
312    }
313
314    /// The table name.
315    ///
316    /// PHP: `$table->name`.
317    pub fn name(&self) -> &str {
318        &self.def.name
319    }
320
321    /// The columns added so far.
322    ///
323    /// PHP: `$table->columns`.
324    pub fn columns(&self) -> &[Column<S>] {
325        &self.def.columns
326    }
327
328    /// The column at `index` (in the order they were added), to modify it later.
329    pub fn column_mut(&mut self, index: usize) -> Option<&mut Column<S>> {
330        self.def.columns.get_mut(index)
331    }
332
333    /// The foreign keys declared so far.
334    ///
335    /// PHP: `$table->foreignKeys`.
336    pub fn foreign_keys(&self) -> &[ForeignKey] {
337        &self.def.foreign_keys
338    }
339
340    /// The foreign key at `index` (in the order they were declared), to modify it later.
341    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    /// Adds an unsigned auto-incrementing `BIGINT` primary key `name`
355    /// (PHP's default name is `id`).
356    ///
357    /// PHP: `id()`.
358    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    /// Adds a string column of `length` characters (PHP's default is 255).
364    ///
365    /// PHP: `string()`.
366    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    /// Adds a text column.
371    ///
372    /// PHP: `text()`.
373    pub fn text(&mut self, name: impl Into<String>) -> &mut Column<S> {
374        self.add(name, ColumnType::Text)
375    }
376
377    /// Adds a medium text column.
378    ///
379    /// PHP: `mediumText()`.
380    pub fn medium_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
381        self.add(name, ColumnType::MediumText)
382    }
383
384    /// Adds a long text column.
385    ///
386    /// PHP: `longText()`.
387    pub fn long_text(&mut self, name: impl Into<String>) -> &mut Column<S> {
388        self.add(name, ColumnType::LongText)
389    }
390
391    /// Adds an 8-bit integer column.
392    ///
393    /// PHP: `tinyInteger()`.
394    pub fn tiny_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
395        self.add(name, ColumnType::TinyInteger)
396    }
397
398    /// Adds a 16-bit integer column.
399    ///
400    /// PHP: `smallInteger()`.
401    pub fn small_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
402        self.add(name, ColumnType::SmallInteger)
403    }
404
405    /// Adds a 32-bit integer column.
406    ///
407    /// PHP: `integer()`.
408    pub fn integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
409        self.add(name, ColumnType::Integer)
410    }
411
412    /// Adds a 64-bit integer column.
413    ///
414    /// PHP: `bigInteger()`.
415    pub fn big_integer(&mut self, name: impl Into<String>) -> &mut Column<S> {
416        self.add(name, ColumnType::BigInteger)
417    }
418
419    /// Adds a `DECIMAL(precision, scale)` column (PHP's defaults are 10 and
420    /// 0); the precision is at least 1 and the scale between 0 and the
421    /// precision.
422    ///
423    /// PHP: `decimal()`.
424    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    /// Adds a UUID column (native where the dialect has one).
438    ///
439    /// PHP: `uuid()`.
440    pub fn uuid(&mut self, name: impl Into<String>) -> &mut Column<S> {
441        self.add(name, ColumnType::Uuid)
442    }
443
444    /// Adds a double-precision float column.
445    ///
446    /// PHP: `float()`.
447    pub fn float(&mut self, name: impl Into<String>) -> &mut Column<S> {
448        self.add(name, ColumnType::Float)
449    }
450
451    /// Adds a boolean column.
452    ///
453    /// PHP: `boolean()`.
454    pub fn boolean(&mut self, name: impl Into<String>) -> &mut Column<S> {
455        self.add(name, ColumnType::Boolean)
456    }
457
458    /// Adds a date-time column with fractional-second `precision` (PHP's
459    /// default is 0).
460    ///
461    /// PHP: `datetime()`.
462    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    /// Adds a timestamp column with fractional-second `precision` (PHP's
467    /// default is 0).
468    ///
469    /// PHP: `timestamp()`.
470    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    /// Adds a JSON column.
475    ///
476    /// PHP: `json()`.
477    pub fn json(&mut self, name: impl Into<String>) -> &mut Column<S> {
478        self.add(name, ColumnType::Json)
479    }
480
481    /// Adds a binary column.
482    ///
483    /// PHP: `binary()`.
484    pub fn binary(&mut self, name: impl Into<String>) -> &mut Column<S> {
485        self.add(name, ColumnType::Binary)
486    }
487
488    /// Adds an enum column of `values` (one at least).
489    ///
490    /// PHP: `enum()`.
491    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    /// Adds a point column with `srid` (PHP's default is 4326).
506    ///
507    /// PHP: `point()`.
508    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    /// Adds a line string column with `srid` (PHP's default is 4326).
513    ///
514    /// PHP: `linestring()`.
515    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    /// Adds a polygon column with `srid` (PHP's default is 4326).
520    ///
521    /// PHP: `polygon()`.
522    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    /// Adds `created_at` and `updated_at` date-times with `precision` (PHP's
527    /// default is 3).
528    ///
529    /// PHP: `timestamps()`.
530    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    /// Adds a column of any type; `length_or_precision` is the length of a
546    /// string and the precision of anything else.
547    ///
548    /// PHP: `addColumn()`.
549    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    /// Modifies a column (an `ALTER` emits `MODIFY` / `ALTER COLUMN`).
559    ///
560    /// PHP: `modifyColumn()`.
561    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    /// Adds an index over `columns`, named `idx_<columns>`.
571    ///
572    /// PHP: `index()` (the other options: [`Table::add_index`]).
573    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    /// Adds a unique index over `columns`, named `uniq_<columns>`.
580    ///
581    /// PHP: `uniqueIndex()`.
582    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    /// Adds `index`, after [`Index::validated`].
589    ///
590    /// PHP: `addIndex()` (and the options of `index()` / `uniqueIndex()`).
591    pub fn add_index(&mut self, index: Index) -> Result<&mut Self> {
592        self.def.indexes.push(index.validated()?);
593        Ok(self)
594    }
595
596    /// Drops the index `name` (in an `ALTER`).
597    ///
598    /// PHP: `dropIndex()`.
599    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    /// Adds a raw column definition, emitted verbatim.
605    ///
606    /// PHP: `rawColumn()`.
607    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    /// Adds a raw index definition, emitted verbatim.
613    ///
614    /// PHP: `rawIndex()`.
615    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    /// `CREATE TABLE`.
631    ///
632    /// PHP: `create()`.
633    pub fn create(&self) -> Result<Statement> {
634        self.schema()?.compile_create(self, false)
635    }
636
637    /// `CREATE TABLE IF NOT EXISTS`.
638    ///
639    /// PHP: `createIfNotExists()` / `create(true)`.
640    pub fn create_if_not_exists(&self) -> Result<Statement> {
641        self.schema()?.compile_create(self, true)
642    }
643
644    /// `ALTER TABLE` with the columns, renames, drops, indexes and keys
645    /// collected.
646    ///
647    /// PHP: `alter()`.
648    pub fn alter(&self) -> Result<Statement> {
649        self.schema()?.compile_alter(self)
650    }
651
652    /// `DROP TABLE`.
653    ///
654    /// PHP: `drop()`.
655    pub fn drop(&self) -> Result<Statement> {
656        self.schema()?.compile_drop(&self.def.name, false)
657    }
658
659    /// `DROP TABLE IF EXISTS`.
660    ///
661    /// PHP: `dropIfExists()`.
662    pub fn drop_if_exists(&self) -> Result<Statement> {
663        self.schema()?.compile_drop(&self.def.name, true)
664    }
665
666    /// Empties the table.
667    ///
668    /// PHP: `truncate()`.
669    pub fn truncate(&self) -> Result<Statement> {
670        self.schema()?.compile_truncate(&self.def.name)
671    }
672
673    /// Renames the table to `to`.
674    ///
675    /// PHP: `rename()`.
676    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    /// Adds an auto-incrementing integer column.
683    ///
684    /// PHP: `serial()`.
685    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    /// Adds an auto-incrementing big integer column.
690    ///
691    /// PHP: `bigSerial()`.
692    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    /// Adds an auto-incrementing small integer column.
697    ///
698    /// PHP: `smallSerial()`.
699    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    /// Adds a named `CHECK` constraint (`name` is an identifier).
706    ///
707    /// PHP: `check()` with two arguments.
708    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    /// Renames the column `from` to `to` (in an `ALTER`).
716    ///
717    /// PHP: `renameColumn()`.
718    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    /// Drops the column `name` (in an `ALTER`).
724    ///
725    /// PHP: `dropColumn()`.
726    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    /// Declares a primary key over two `columns` or more, each an identifier
734    /// (a single-column key is [`Column::primary`]).
735    ///
736    /// PHP: `primary()` with an array.
737    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    /// Declares a foreign key on `column`.
755    ///
756    /// PHP: `foreignKey()`.
757    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    /// Declares a foreign key to add in an `ALTER` (the same as
765    /// [`Table::foreign_key`]).
766    ///
767    /// PHP: `addForeignKey()`.
768    pub fn add_foreign_key(&mut self, column: impl Into<String>) -> &mut ForeignKey {
769        self.foreign_key(column)
770    }
771
772    /// Drops the foreign key `name` (in an `ALTER`).
773    ///
774    /// PHP: `dropForeignKey()`.
775    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    /// Adds a full-text index over `columns`, named `ft_<columns>`.
783    ///
784    /// PHP: `fulltextIndex()`.
785    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    /// Adds a spatial index over `columns`, named `sp_<columns>`.
792    ///
793    /// PHP: `spatialIndex()`.
794    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    /// Partitions by range of `expression`.
803    ///
804    /// PHP: `partitionByRange()`.
805    pub fn partition_by_range(&mut self, expression: impl Into<String>) -> &mut Self {
806        self.partition(PartitionType::Range, expression.into(), None)
807    }
808
809    /// Partitions by list of `expression`.
810    ///
811    /// PHP: `partitionByList()`.
812    pub fn partition_by_list(&mut self, expression: impl Into<String>) -> &mut Self {
813        self.partition(PartitionType::List, expression.into(), None)
814    }
815
816    /// Partitions by hash of `expression`, into `partitions` (at least 1) when given.
817    ///
818    /// PHP: `partitionByHash()`.
819    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    /// Adds a `VECTOR(dimensions)` column (pgvector).
838    ///
839    /// PHP: `Table\PostgreSQL::vector()`.
840    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    /// Adds a vector (array) field.
847    ///
848    /// PHP: `Table\MongoDB::vector()`.
849    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    /// Adds an `Array(Float64)` vector column.
856    ///
857    /// PHP: `Table\ClickHouse::vector()`.
858    pub fn vector(&mut self, name: impl Into<String>) -> &mut Column<ClickHouse> {
859        self.add(name, ColumnType::Vector)
860    }
861
862    /// Adds an `Array(element)` column.
863    ///
864    /// PHP: `array()`.
865    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    /// Adds a `Tuple(elements...)` column (one element at least).
870    ///
871    /// PHP: `tuple()`.
872    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    /// Adds a `FixedString(length)` column (length at least 1).
879    ///
880    /// PHP: `fixedString()`.
881    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    /// Selects the engine; `CollapsingMergeTree` needs a sign column and
888    /// `ReplicatedMergeTree` a ZooKeeper path and a replica name.
889    ///
890    /// PHP: `engine()`.
891    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    /// Sets the `ORDER BY` columns (identifiers); without one, the primary
905    /// key orders the table.
906    ///
907    /// PHP: `orderBy()`.
908    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    /// Sets a raw `ORDER BY` expression (trimmed, not empty, no `;`), which
918    /// takes precedence over [`Table::order_by`].
919    ///
920    /// PHP: `orderByRaw()`.
921    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    /// Sets the table TTL (trimmed, not empty, no `;`).
931    ///
932    /// PHP: `Table\ClickHouse::ttl()`.
933    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    /// Replaces the engine `SETTINGS`: names are identifiers; booleans
943    /// become `1` / `0`, numbers are printed, strings must match
944    /// `[A-Za-z0-9_.\-+/]+`.
945    ///
946    /// PHP: `settings()`.
947    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    /// Sets the `PARTITION BY` expression.
983    ///
984    /// PHP: `partitionBy()`.
985    pub fn partition_by(&mut self, expression: impl Into<String>) -> &mut Self {
986        self.def.partition_expression = expression.into();
987        self
988    }
989
990    /// Sets the `SAMPLE BY` expression (trimmed, not empty, no `;`).
991    ///
992    /// PHP: `sampleBy()`.
993    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}