Skip to main content

utopia_query/schema/
index.rs

1//! The value parts of a table blueprint: indexes, check constraints and
2//! column renames, and the options of a standalone `CREATE INDEX`.
3
4use super::enums::{IndexAlgorithm, IndexType};
5use super::names;
6use crate::error::{Error, Result};
7use crate::value::Value;
8
9/// An index of a table: its columns (with per-column lengths, orders and
10/// collations), raw expressions, method and operator class, and for
11/// ClickHouse data-skipping indexes the algorithm, its arguments and the
12/// granularity.
13///
14/// [`Index::new`] makes one with defaults; [`Index::validated`] runs the
15/// checks PHP's constructor makes.
16///
17/// PHP: `Utopia\Query\Schema\Index`.
18#[derive(Debug, Clone, PartialEq)]
19pub struct Index {
20    /// The name.
21    pub name: String,
22    /// The columns.
23    pub columns: Vec<String>,
24    /// The kind.
25    pub kind: IndexType,
26    /// Prefix lengths, by column.
27    pub lengths: Vec<(String, i64)>,
28    /// Orders (`ASC` / `DESC`, any case), by column.
29    pub orders: Vec<(String, String)>,
30    /// The method (`USING btree`), or empty.
31    pub method: String,
32    /// The operator class applied to every column, or empty.
33    pub operator_class: String,
34    /// Collations, by column.
35    pub collations: Vec<(String, String)>,
36    /// Raw SQL expressions appended to the column list, unquoted.
37    pub raw_columns: Vec<String>,
38    /// The ClickHouse skip-index algorithm, if any.
39    pub algorithm: Option<IndexAlgorithm>,
40    /// The algorithm's arguments: strings, integers or floats.
41    pub algorithm_args: Vec<Value>,
42    /// The ClickHouse granularity, if set.
43    pub granularity: Option<i64>,
44}
45
46fn lookup<'a, T>(pairs: &'a [(String, T)], column: &str) -> Option<&'a T> {
47    pairs.iter().rev().find(|(c, _)| c == column).map(|(_, v)| v)
48}
49
50impl Index {
51    /// An index of `kind` named `name` over `columns`, with no other option
52    /// (not validated: see [`Index::validated`]).
53    pub fn new(name: impl Into<String>, columns: Vec<String>, kind: IndexType) -> Self {
54        Index {
55            name: name.into(),
56            columns,
57            kind,
58            lengths: Vec::new(),
59            orders: Vec::new(),
60            method: String::new(),
61            operator_class: String::new(),
62            collations: Vec::new(),
63            raw_columns: Vec::new(),
64            algorithm: None,
65            algorithm_args: Vec::new(),
66            granularity: None,
67        }
68    }
69
70    /// The index, after PHP's constructor checks: a ClickHouse index name
71    /// is an identifier, there is at least one column or raw expression, the
72    /// method, operator class and collations are plain words, the
73    /// granularity is at least 1, and `minmax` / `inverted` take no
74    /// arguments.
75    ///
76    /// PHP: `new Index(...)`, which throws `ValidationException`.
77    pub fn validated(self) -> Result<Self> {
78        if self.algorithm.is_some() && !names::is_identifier(&self.name) {
79            return Err(Error::Validation(format!("Invalid index name: {}", self.name)));
80        }
81        if self.columns.is_empty() && self.raw_columns.is_empty() {
82            return Err(Error::Validation("Index requires at least one column.".into()));
83        }
84        if !self.method.is_empty() && !names::is_word(&self.method) {
85            return Err(Error::Validation(format!("Invalid index method: {}", self.method)));
86        }
87        if !self.operator_class.is_empty() && !names::is_dotted_word(&self.operator_class) {
88            return Err(Error::Validation(format!("Invalid operator class: {}", self.operator_class)));
89        }
90        for (_, collation) in &self.collations {
91            if !names::is_word(collation) {
92                return Err(Error::Validation(format!("Invalid collation: {collation}")));
93            }
94        }
95        if let Some(granularity) = self.granularity
96            && granularity < 1
97        {
98            return Err(Error::Validation("Index granularity must be >= 1.".into()));
99        }
100        if let Some(algorithm) = self.algorithm
101            && !self.algorithm_args.is_empty()
102            && !algorithm.accepts_args()
103        {
104            return Err(Error::Validation(format!("{} does not accept algorithm arguments.", algorithm.as_str())));
105        }
106        Ok(self)
107    }
108
109    /// The name an unnamed index gets: `prefix` and the columns joined by
110    /// `_`, each with runs of characters outside `[A-Za-z0-9_]` replaced by
111    /// one `_` (`idx_email`, `uniq_tenant_id_email`).
112    ///
113    /// PHP: `Table::autoIndexName()`.
114    pub fn auto_name(prefix: &str, columns: &[String]) -> String {
115        let mut name = String::from(prefix);
116        for (i, column) in columns.iter().enumerate() {
117            if i > 0 {
118                name.push('_');
119            }
120            name.push_str(&names::sanitize(column));
121        }
122        name
123    }
124
125    /// The prefix length of `column`, if set.
126    pub fn length(&self, column: &str) -> Option<i64> {
127        lookup(&self.lengths, column).copied()
128    }
129
130    /// The order of `column`, if set.
131    pub fn order(&self, column: &str) -> Option<&str> {
132        lookup(&self.orders, column).map(String::as_str)
133    }
134
135    /// The collation of `column`, if set.
136    pub fn collation(&self, column: &str) -> Option<&str> {
137        lookup(&self.collations, column).map(String::as_str)
138    }
139}
140
141/// The options of a standalone `CREATE INDEX` statement.
142///
143/// PHP: the optional parameters of `Schema::createIndex()`.
144#[derive(Debug, Clone, Default, PartialEq)]
145pub struct IndexOptions {
146    /// `CREATE UNIQUE INDEX`.
147    pub unique: bool,
148    /// The kind (`fulltext`, `spatial`, ...), when not unique; `None` for a
149    /// plain index.
150    pub kind: Option<IndexType>,
151    /// The method (`USING ...`), or empty.
152    pub method: String,
153    /// The operator class, or empty.
154    pub operator_class: String,
155    /// Prefix lengths, by column.
156    pub lengths: Vec<(String, i64)>,
157    /// Orders, by column.
158    pub orders: Vec<(String, String)>,
159    /// Collations, by column.
160    pub collations: Vec<(String, String)>,
161    /// Raw SQL expressions appended to the column list.
162    pub raw_columns: Vec<String>,
163    /// `CREATE INDEX CONCURRENTLY` (PostgreSQL only; ignored elsewhere).
164    pub concurrently: bool,
165}
166
167impl IndexOptions {
168    /// The index these options describe, named `name` over `columns`
169    /// (validated).
170    pub(crate) fn index(&self, name: &str, columns: &[&str]) -> Result<Index> {
171        let kind = if self.unique { IndexType::Unique } else { self.kind.unwrap_or(IndexType::Index) };
172        Index {
173            lengths: self.lengths.clone(),
174            orders: self.orders.clone(),
175            method: self.method.clone(),
176            operator_class: self.operator_class.clone(),
177            collations: self.collations.clone(),
178            raw_columns: self.raw_columns.clone(),
179            ..Index::new(name, columns.iter().map(|c| (*c).to_owned()).collect(), kind)
180        }
181        .validated()
182    }
183}
184
185/// A named table-level `CHECK` constraint.
186///
187/// PHP: `Utopia\Query\Schema\CheckConstraint`.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct CheckConstraint {
190    /// The constraint name.
191    pub name: String,
192    /// The SQL expression, emitted verbatim.
193    pub expression: String,
194}
195
196impl CheckConstraint {
197    /// A check named `name` (an identifier) on `expression`.
198    ///
199    /// PHP: `new CheckConstraint($name, $expression)`, which throws
200    /// `ValidationException` for an invalid name.
201    pub fn new(name: impl Into<String>, expression: impl Into<String>) -> Result<Self> {
202        let name = name.into();
203        if !names::is_identifier(&name) {
204            return Err(Error::Validation(format!("Invalid check constraint name: {name}")));
205        }
206        Ok(CheckConstraint { name, expression: expression.into() })
207    }
208}
209
210/// A column rename of an `ALTER TABLE`.
211///
212/// PHP: `Utopia\Query\Schema\RenameColumn`.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct RenameColumn {
215    /// The current name.
216    pub from: String,
217    /// The new name.
218    pub to: String,
219}
220
221impl RenameColumn {
222    /// A rename of `from` to `to`.
223    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
224        RenameColumn { from: from.into(), to: to.into() }
225    }
226}