Skip to main content

utopia_query/schema/
column.rs

1//! [`Column`]: a column of a table blueprint, with the modifiers its
2//! dialect supports.
3//!
4//! Modifiers every dialect has are inherent methods. The others are gated
5//! by marker traits the dialects implement ([`Unique`], [`Collation`],
6//! [`Generated`], ...), so a modifier a dialect cannot express does not
7//! exist on its columns, as in PHP where each dialect's column class only
8//! uses the traits it supports.
9
10use std::fmt;
11use std::marker::PhantomData;
12
13use super::enums::ColumnType;
14use super::{ClickHouse, PostgreSql, Schema, names};
15use crate::error::{Error, Result};
16use crate::value::{IntoValue, Value};
17
18/// What a column is: its name, type, sizes and every modifier set on it.
19///
20/// PHP: the public properties of `Utopia\Query\Schema\Column` (and
21/// `Column\ClickHouse`).
22#[derive(Debug, Clone, PartialEq)]
23pub struct ColumnDefinition {
24    /// The name.
25    pub name: String,
26    /// The portable type.
27    pub kind: ColumnType,
28    /// The length (strings).
29    pub length: Option<i64>,
30    /// The precision (decimals, date-times).
31    pub precision: Option<i64>,
32    /// The scale (decimals).
33    pub scale: Option<i64>,
34    /// Whether the column accepts `NULL`.
35    pub nullable: bool,
36    /// The default value, rendered as a literal (`Some(Value::Null)` is
37    /// `DEFAULT NULL`; `None` is no default).
38    pub default: Option<Value>,
39    /// A raw default expression, emitted verbatim.
40    pub default_raw: Option<String>,
41    /// Whether the column is unsigned.
42    pub unsigned: bool,
43    /// Whether the column is unique.
44    pub unique: bool,
45    /// Whether the column is (part of) the primary key.
46    pub primary: bool,
47    /// Whether the server increments the column.
48    pub auto_increment: bool,
49    /// The column this one is placed after (MySQL `ALTER`).
50    pub after: Option<String>,
51    /// The comment.
52    pub comment: Option<String>,
53    /// The allowed values of an enum column.
54    pub enum_values: Vec<String>,
55    /// The spatial reference system of a geometry column.
56    pub srid: Option<i64>,
57    /// The width of a vector column.
58    pub dimensions: Option<i64>,
59    /// Whether an `ALTER` modifies the column instead of adding it.
60    pub modify: bool,
61    /// The collation.
62    pub collation: Option<String>,
63    /// A column-level `CHECK` expression.
64    pub check: Option<String>,
65    /// The expression of a generated column.
66    pub generated_expression: Option<String>,
67    /// Whether a generated column is stored (`Some(true)`) or virtual
68    /// (`Some(false)`); `None` when not set.
69    pub generated_stored: Option<bool>,
70    /// A column-level TTL expression (ClickHouse).
71    pub ttl: Option<String>,
72    /// A user-defined type name (PostgreSQL).
73    pub user_type: Option<String>,
74    /// Whether the type is wrapped in `LowCardinality(...)` (ClickHouse).
75    pub low_cardinality: bool,
76    /// The width of a `FixedString(N)` column (ClickHouse).
77    pub fixed_string_length: Option<i64>,
78    /// The `CODEC(...)` clauses (ClickHouse).
79    pub codecs: Vec<String>,
80    /// The element type of an `Array(T)` column (ClickHouse).
81    pub array_element_type: Option<ColumnType>,
82    /// The element types of a `Tuple(...)` column (ClickHouse).
83    pub tuple_element_types: Vec<ColumnType>,
84}
85
86/// A column of a table blueprint for the dialect `S`.
87///
88/// Built by the table's factories ([`Table::string`](super::Table::string),
89/// [`Table::integer`](super::Table::integer), ...), which return it to
90/// chain modifiers: `table.string("email", 255).unique().nullable()`.
91///
92/// PHP: `Utopia\Query\Schema\Column` and its dialect classes
93/// (`Column\MySQL`, `Column\PostgreSQL`, `Column\SQLite`,
94/// `Column\ClickHouse`, `Column\MongoDB`).
95pub struct Column<S> {
96    pub(crate) def: ColumnDefinition,
97    dialect: PhantomData<fn() -> S>,
98}
99
100impl<S> Clone for Column<S> {
101    fn clone(&self) -> Self {
102        Column { def: self.def.clone(), dialect: PhantomData }
103    }
104}
105
106impl<S> fmt::Debug for Column<S> {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        self.def.fmt(f)
109    }
110}
111
112impl<S> PartialEq for Column<S> {
113    fn eq(&self, other: &Self) -> bool {
114        self.def == other.def
115    }
116}
117
118/// Dialects whose columns can be server-incremented.
119///
120/// PHP: `Column\Trait\AutoIncrement`.
121pub trait AutoIncrement: Schema {}
122/// Dialects with column-level collations.
123///
124/// PHP: `Column\Trait\Collation`.
125pub trait Collation: Schema {}
126/// Dialects with inline column comments.
127///
128/// PHP: `Column\Trait\Comment`.
129pub trait Comment: Schema {}
130/// Dialects whose vector columns have a declared width.
131///
132/// PHP: `Column\Trait\Dimensions`.
133pub trait Dimensions: Schema {}
134/// Dialects with stored generated columns.
135///
136/// PHP: `Column\Trait\Generated`.
137pub trait Generated: Schema {}
138/// Dialects that place columns with `AFTER`.
139///
140/// PHP: `Column\Trait\Positioning`.
141pub trait Positioning: Schema {}
142/// Dialects whose geometry columns carry an SRID.
143///
144/// PHP: `Column\Trait\Srid`.
145pub trait Srid: Schema {}
146/// Dialects with column-level `UNIQUE`.
147///
148/// PHP: `Column\Trait\Unique`.
149pub trait Unique: Schema {}
150/// Dialects with virtual generated columns.
151///
152/// PHP: `Column\Trait\VirtualGenerated`.
153pub trait VirtualGenerated: Schema {}
154
155/// A trimmed expression that is not empty and has no `;`.
156pub(crate) fn expression(value: &str, empty: &str, semicolon: &str) -> Result<String> {
157    let trimmed = php_std::string::trim(value.as_bytes(), php_std::string::TRIM_CHARACTERS);
158    let trimmed = String::from_utf8_lossy(trimmed).into_owned();
159    if trimmed.is_empty() {
160        return Err(Error::Validation(empty.into()));
161    }
162    if trimmed.contains(';') {
163        return Err(Error::Validation(semicolon.into()));
164    }
165    Ok(trimmed)
166}
167
168impl<S> Column<S> {
169    /// A column `name` of type `kind`, with no size and no modifier (PHP's
170    /// table factories make columns; this one belongs to no table).
171    ///
172    /// PHP: `new Column($table, $name, $type)`.
173    pub fn new(name: impl Into<String>, kind: ColumnType) -> Self {
174        Column {
175            def: ColumnDefinition {
176                name: name.into(),
177                kind,
178                length: None,
179                precision: None,
180                scale: None,
181                nullable: false,
182                default: None,
183                default_raw: None,
184                unsigned: false,
185                unique: false,
186                primary: false,
187                auto_increment: false,
188                after: None,
189                comment: None,
190                enum_values: Vec::new(),
191                srid: None,
192                dimensions: None,
193                modify: false,
194                collation: None,
195                check: None,
196                generated_expression: None,
197                generated_stored: None,
198                ttl: None,
199                user_type: None,
200                low_cardinality: false,
201                fixed_string_length: None,
202                codecs: Vec::new(),
203                array_element_type: None,
204                tuple_element_types: Vec::new(),
205            },
206            dialect: PhantomData,
207        }
208    }
209
210    /// The column with a length (strings).
211    ///
212    /// PHP: the `$length` constructor parameter.
213    pub fn with_length(mut self, length: Option<i64>) -> Self {
214        self.def.length = length;
215        self
216    }
217
218    /// The column with a precision.
219    ///
220    /// PHP: the `$precision` constructor parameter.
221    pub fn with_precision(mut self, precision: Option<i64>) -> Self {
222        self.def.precision = precision;
223        self
224    }
225
226    /// The column with a scale.
227    ///
228    /// PHP: the `$scale` constructor parameter.
229    pub fn with_scale(mut self, scale: Option<i64>) -> Self {
230        self.def.scale = scale;
231        self
232    }
233
234    /// The column with a spatial reference system.
235    ///
236    /// PHP: the `$srid` constructor parameter.
237    pub fn with_srid(mut self, srid: Option<i64>) -> Self {
238        self.def.srid = srid;
239        self
240    }
241
242    /// The column with a vector width.
243    ///
244    /// PHP: the `$dimensions` constructor parameter.
245    pub fn with_dimensions(mut self, dimensions: Option<i64>) -> Self {
246        self.def.dimensions = dimensions;
247        self
248    }
249
250    /// The column, server-incremented or not.
251    ///
252    /// PHP: the `$autoIncrement` constructor parameter.
253    pub fn with_auto_increment(mut self, auto_increment: bool) -> Self {
254        self.def.auto_increment = auto_increment;
255        self
256    }
257
258    /// What the column is.
259    ///
260    /// PHP: the column's public properties.
261    pub fn definition(&self) -> &ColumnDefinition {
262        &self.def
263    }
264
265    /// What the column is, to set directly: nothing here is validated, as
266    /// nothing is when PHP sets a column's properties.
267    pub fn definition_mut(&mut self) -> &mut ColumnDefinition {
268        &mut self.def
269    }
270
271    /// The name.
272    ///
273    /// PHP: `$column->name`.
274    pub fn name(&self) -> &str {
275        &self.def.name
276    }
277
278    /// Accepts `NULL`.
279    ///
280    /// PHP: `nullable()`.
281    pub fn nullable(&mut self) -> &mut Self {
282        self.def.nullable = true;
283        self
284    }
285
286    /// Sets the default value, rendered as a literal (`None` for
287    /// `DEFAULT NULL`).
288    ///
289    /// PHP: `default()`.
290    pub fn default(&mut self, value: impl IntoValue) -> &mut Self {
291        self.def.default = Some(value.into_value());
292        self
293    }
294
295    /// Sets a raw default expression (`now()`, `gen_random_uuid()`),
296    /// trimmed; it must not be empty nor contain `;`.
297    ///
298    /// PHP: `defaultRaw()`.
299    pub fn default_raw(&mut self, expression: &str) -> Result<&mut Self> {
300        self.def.default_raw = Some(self::expression(
301            expression,
302            "Raw default expression must not be empty.",
303            "Raw default expression must not contain \";\".",
304        )?);
305        Ok(self)
306    }
307
308    /// Marks the column unsigned.
309    ///
310    /// PHP: `unsigned()`.
311    pub fn unsigned(&mut self) -> &mut Self {
312        self.def.unsigned = true;
313        self
314    }
315
316    /// Marks the column as the primary key (a composite key is
317    /// [`Table::primary`](super::Table::primary)).
318    ///
319    /// PHP: `primary()` without arguments.
320    pub fn primary(&mut self) -> &mut Self {
321        self.def.primary = true;
322        self
323    }
324
325    /// Sets the allowed values of an enum column; there must be one at least.
326    ///
327    /// PHP: `enum()` with one array argument.
328    pub fn enum_values<V: Into<String>>(&mut self, values: impl IntoIterator<Item = V>) -> Result<&mut Self> {
329        let values: Vec<String> = values.into_iter().map(Into::into).collect();
330        if values.is_empty() {
331            return Err(Error::Validation("enum() requires at least one allowed value.".into()));
332        }
333        self.def.enum_values = values;
334        Ok(self)
335    }
336
337    /// Makes an `ALTER` modify the column instead of adding it.
338    ///
339    /// PHP: `modify()`.
340    pub fn modify(&mut self) -> &mut Self {
341        self.def.modify = true;
342        self
343    }
344}
345
346impl<S: AutoIncrement> Column<S> {
347    /// Marks the column server-incremented.
348    ///
349    /// PHP: `autoIncrement()`.
350    pub fn auto_increment(&mut self) -> &mut Self {
351        self.def.auto_increment = true;
352        self
353    }
354}
355
356impl<S: Collation> Column<S> {
357    /// Sets the collation.
358    ///
359    /// PHP: `collation()`.
360    pub fn collation(&mut self, collation: impl Into<String>) -> &mut Self {
361        self.def.collation = Some(collation.into());
362        self
363    }
364}
365
366impl<S: Comment> Column<S> {
367    /// Sets the comment.
368    ///
369    /// PHP: `comment()`.
370    pub fn comment(&mut self, comment: impl Into<String>) -> &mut Self {
371        self.def.comment = Some(comment.into());
372        self
373    }
374}
375
376impl<S: Dimensions> Column<S> {
377    /// Sets the width of a vector column.
378    ///
379    /// PHP: `dimensions()`.
380    pub fn dimensions(&mut self, dimensions: i64) -> &mut Self {
381        self.def.dimensions = Some(dimensions);
382        self
383    }
384}
385
386impl<S: Generated> Column<S> {
387    /// Makes the column generated from `expression`.
388    ///
389    /// PHP: `generatedAs()`.
390    pub fn generated_as(&mut self, expression: impl Into<String>) -> &mut Self {
391        self.def.generated_expression = Some(expression.into());
392        self
393    }
394
395    /// Stores the generated column.
396    ///
397    /// PHP: `stored()`.
398    pub fn stored(&mut self) -> &mut Self {
399        self.def.generated_stored = Some(true);
400        self
401    }
402}
403
404impl<S: VirtualGenerated> Column<S> {
405    /// Computes the generated column on read.
406    ///
407    /// PHP: `virtual()`.
408    pub fn virtual_(&mut self) -> &mut Self {
409        self.def.generated_stored = Some(false);
410        self
411    }
412}
413
414impl<S: Positioning> Column<S> {
415    /// Places the column after `column` (in an `ALTER`).
416    ///
417    /// PHP: `after()`.
418    pub fn after(&mut self, column: impl Into<String>) -> &mut Self {
419        self.def.after = Some(column.into());
420        self
421    }
422}
423
424impl<S: Srid> Column<S> {
425    /// Sets the spatial reference system.
426    ///
427    /// PHP: `srid()`.
428    pub fn srid(&mut self, srid: i64) -> &mut Self {
429        self.def.srid = Some(srid);
430        self
431    }
432}
433
434impl<S: Unique> Column<S> {
435    /// Marks the column unique.
436    ///
437    /// PHP: `unique()`.
438    pub fn unique(&mut self) -> &mut Self {
439        self.def.unique = true;
440        self
441    }
442}
443
444impl<S: super::table::Checks> Column<S> {
445    /// Sets a column-level `CHECK` expression (a named table-level check is
446    /// [`Table::check`](super::Table::check)).
447    ///
448    /// PHP: `check()` with one argument.
449    pub fn check(&mut self, expression: impl Into<String>) -> &mut Self {
450        self.def.check = Some(expression.into());
451        self
452    }
453}
454
455impl Column<PostgreSql> {
456    /// Uses the user-defined type `name` (a `CREATE TYPE` enum), which must
457    /// be an identifier.
458    ///
459    /// PHP: `Column\PostgreSQL::userType()`.
460    pub fn user_type(&mut self, name: &str) -> Result<&mut Self> {
461        if !names::is_identifier(name) {
462            return Err(Error::Validation(format!("Invalid user-defined type name: {name}")));
463        }
464        self.def.user_type = Some(name.to_owned());
465        Ok(self)
466    }
467}
468
469impl Column<ClickHouse> {
470    /// Makes the column `FixedString(length)`; the length is at least 1.
471    ///
472    /// PHP: `Column\ClickHouse::asFixedString()`.
473    pub fn as_fixed_string(&mut self, length: i64) -> Result<&mut Self> {
474        if length < 1 {
475            return Err(Error::Validation("FixedString length must be at least 1.".into()));
476        }
477        self.def.fixed_string_length = Some(length);
478        Ok(self)
479    }
480
481    /// Whether the column is `FixedString(N)`.
482    ///
483    /// PHP: `isFixedString()`.
484    pub fn is_fixed_string(&self) -> bool {
485        self.def.fixed_string_length.is_some()
486    }
487
488    /// Makes the column `Array(element)`.
489    ///
490    /// PHP: `asArray()`.
491    pub fn as_array(&mut self, element: ColumnType) -> &mut Self {
492        self.def.array_element_type = Some(element);
493        self
494    }
495
496    /// Whether the column is `Array(T)`.
497    ///
498    /// PHP: `isArray()`.
499    pub fn is_array(&self) -> bool {
500        self.def.array_element_type.is_some()
501    }
502
503    /// Makes the column `Tuple(elements...)`; there must be one at least.
504    ///
505    /// PHP: `asTuple()`.
506    pub fn as_tuple(&mut self, elements: Vec<ColumnType>) -> Result<&mut Self> {
507        if elements.is_empty() {
508            return Err(Error::Validation("Tuple() requires at least one element type.".into()));
509        }
510        self.def.tuple_element_types = elements;
511        Ok(self)
512    }
513
514    /// Whether the column is `Tuple(...)`.
515    ///
516    /// PHP: `isTuple()`.
517    pub fn is_tuple(&self) -> bool {
518        !self.def.tuple_element_types.is_empty()
519    }
520
521    /// Wraps the type in `LowCardinality(...)`.
522    ///
523    /// PHP: `lowCardinality()`.
524    pub fn low_cardinality(&mut self) -> &mut Self {
525        self.def.low_cardinality = true;
526        self
527    }
528
529    /// Adds a `CODEC(...)` clause (`LZ4`, `Delta(4)`), trimmed; it must not
530    /// be empty nor contain `;`.
531    ///
532    /// PHP: `codec()`.
533    pub fn codec(&mut self, codec: &str) -> Result<&mut Self> {
534        let codec =
535            expression(codec, "CODEC expression must not be empty.", "CODEC expression must not contain \";\".")?;
536        self.def.codecs.push(codec);
537        Ok(self)
538    }
539
540    /// Sets a column-level TTL expression, trimmed; it must not be empty nor
541    /// contain `;`.
542    ///
543    /// PHP: `Column\ClickHouse::ttl()`.
544    pub fn ttl(&mut self, expression: &str) -> Result<&mut Self> {
545        self.def.ttl = Some(self::expression(
546            expression,
547            "TTL expression must not be empty.",
548            "TTL expression must not contain \";\".",
549        )?);
550        Ok(self)
551    }
552}