Skip to main content

utopia_query/schema/
mod.rs

1//! Schema builders: DDL for tables, columns, indexes, views, procedures and
2//! triggers, per dialect.
3//!
4//! A schema ([`MySql`], [`PostgreSql`], [`Sqlite`], [`ClickHouse`],
5//! [`MongoDb`]) compiles statements; [`Schema::table`] starts a fluent
6//! [`Table`] blueprint whose terminal methods ([`Table::create`],
7//! [`Table::alter`], [`Table::drop`], ...) compile it. Each dialect only has
8//! the column and table methods it can express (marker traits in
9//! [`column`](mod@column) and [`table`]), and the statements beyond tables are
10//! capability traits in [`feature`].
11//!
12//! ```
13//! use utopia_query::schema::{ForeignKeyAction, PostgreSql, Schema};
14//!
15//! let mut posts = PostgreSql::new().table("posts");
16//! posts.id("id");
17//! posts.string("title", 120);
18//! posts.integer("author_id");
19//! posts.foreign_key("author_id").references("id").on("users").on_delete(ForeignKeyAction::Cascade);
20//! assert_eq!(
21//!     posts.create()?.query,
22//!     "CREATE TABLE \"posts\" (\"id\" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, \
23//!      \"title\" VARCHAR(120) NOT NULL, \"author_id\" INTEGER NOT NULL, PRIMARY KEY (\"id\"), \
24//!      FOREIGN KEY (\"author_id\") REFERENCES \"users\" (\"id\") ON DELETE CASCADE)"
25//! );
26//! # Ok::<(), utopia_query::Error>(())
27//! ```
28//!
29//! ```php
30//! use Utopia\Query\Schema\ForeignKeyAction;
31//! use Utopia\Query\Schema\PostgreSQL;
32//!
33//! $posts = (new PostgreSQL())->table('posts');
34//! $posts->id();
35//! $posts->string('title', 120);
36//! $posts->integer('author_id');
37//! $posts->foreignKey('author_id')->references('id')->on('users')->onDelete(ForeignKeyAction::Cascade);
38//! echo $posts->create()->query, "\n";
39//! ```
40//!
41//! PHP: `Utopia\Query\Schema`, `Utopia\Query\Schema\*`.
42//!
43//! | PHP | Rust |
44//! |---|---|
45//! | `Schema` (abstract), `Schema\SQL` | [`Schema`] (trait) |
46//! | `Schema\MySQL`, `PostgreSQL`, `SQLite`, `ClickHouse`, `MongoDB` | [`MySql`], [`PostgreSql`], [`Sqlite`], [`ClickHouse`], [`MongoDb`] |
47//! | `Schema\Table`, `Table\*` | [`Table`] (`Table<MySql>`, ...), [`TableDefinition`] (its properties) |
48//! | `Table\Trait\*` | marker traits in [`table`] ([`table::Serial`], [`table::Checks`], ...) |
49//! | `Schema\Column`, `Column\*` | [`Column`] (`Column<MySql>`, ...), [`ColumnDefinition`] (its properties) |
50//! | `Column\Trait\*` | marker traits in [`column`](mod@column) ([`column::Unique`], [`column::Collation`], ...) |
51//! | `Schema\ForeignKey`, `ForeignKey\*` | [`ForeignKey`] |
52//! | `Schema\Forwarder\*` | none: a column or key handle borrows its table, so table methods are called on the table |
53//! | `Schema\Index`, `CheckConstraint`, `RenameColumn` | [`Index`], [`CheckConstraint`], [`RenameColumn`] |
54//! | `createIndex()` options | [`IndexOptions`] |
55//! | `Schema\Feature\*` | traits in [`feature`] |
56//! | `Schema\Trait\*` | the dialects' implementations of those traits |
57//! | `ColumnType`, `IndexType`, `ForeignKeyAction`, `Order`, `ParameterDirection`, `PartitionType`, `TriggerEvent`, `TriggerTiming` | [`ColumnType`], [`IndexType`], [`ForeignKeyAction`], [`Order`], [`ParameterDirection`], [`PartitionType`], [`TriggerEvent`], [`TriggerTiming`] |
58//! | `Schema\ClickHouse\Engine`, `ClickHouse\IndexAlgorithm` | [`Engine`], [`IndexAlgorithm`] |
59
60mod base;
61mod clickhouse;
62pub mod column;
63mod enums;
64pub mod feature;
65mod index;
66mod mongodb;
67mod mysql;
68mod names;
69mod postgresql;
70mod sqlite;
71pub mod table;
72
73pub use clickhouse::ClickHouse;
74pub use column::{Column, ColumnDefinition};
75pub use enums::{
76    ColumnType, Engine, ForeignKeyAction, IndexAlgorithm, IndexType, Order, ParameterDirection, PartitionType,
77    TriggerEvent, TriggerTiming,
78};
79pub use feature::ViewBody;
80pub use index::{CheckConstraint, Index, IndexOptions, RenameColumn};
81pub use mongodb::MongoDb;
82pub use mysql::MySql;
83pub use postgresql::PostgreSql;
84pub use sqlite::Sqlite;
85pub use table::{ForeignKey, Table, TableDefinition};
86
87use crate::builder::{Executor, Statement};
88use crate::error::Result;
89
90/// A dialect's DDL compiler: quoting, column types, and the table, index
91/// and drop statements. Dialects override the steps they write
92/// differently; the provided methods are the shared (MySQL-flavoured)
93/// compilation.
94///
95/// Implement it (and the [`feature`] traits) to add a dialect.
96///
97/// PHP: the abstract `Utopia\Query\Schema`.
98pub trait Schema: Clone + Send + Sync + Sized + 'static {
99    /// The executor statements carry, if any.
100    fn executor(&self) -> Option<&Executor>;
101
102    /// Sets the executor every statement compiled from now on carries
103    /// ([`Statement::execute`] runs it).
104    ///
105    /// PHP: `setExecutor()`.
106    fn set_executor(&mut self, executor: Executor) -> &mut Self;
107
108    /// Quotes a possibly qualified identifier.
109    ///
110    /// PHP: `quote()`.
111    fn quote(&self, identifier: &str) -> Result<String>;
112
113    /// Quotes one identifier, dots included.
114    ///
115    /// PHP: `quoteLiteral()`.
116    fn quote_literal(&self, identifier: &str) -> Result<String>;
117
118    /// The SQL type of `column`.
119    ///
120    /// PHP: `compileColumnType()`.
121    fn compile_column_type(&self, column: &Column<Self>) -> Result<String>;
122
123    /// The auto-increment keyword.
124    ///
125    /// PHP: `compileAutoIncrement()`.
126    fn compile_auto_increment(&self) -> &'static str;
127
128    /// A blueprint of table `name` compiled by this schema.
129    ///
130    /// PHP: `table()`.
131    fn table(&self, name: impl Into<String>) -> Table<Self> {
132        Table::with_schema(self.clone(), name)
133    }
134
135    /// `CREATE TABLE [IF NOT EXISTS]` for `table`.
136    ///
137    /// PHP: `compileCreate()`.
138    fn compile_create(&self, table: &Table<Self>, if_not_exists: bool) -> Result<Statement> {
139        base::create(self, table, if_not_exists)
140    }
141
142    /// `ALTER TABLE` for `table`.
143    ///
144    /// PHP: `compileAlter()`.
145    fn compile_alter(&self, table: &Table<Self>) -> Result<Statement> {
146        base::alter(self, table)
147    }
148
149    /// `DROP TABLE [IF EXISTS] name`.
150    ///
151    /// PHP: `compileDrop()`.
152    fn compile_drop(&self, name: &str, if_exists: bool) -> Result<Statement> {
153        base::plain(self, format!("DROP TABLE {}{}", if if_exists { "IF EXISTS " } else { "" }, self.quote(name)?))
154    }
155
156    /// Renames table `from` to `to`.
157    ///
158    /// PHP: `compileRename()`.
159    fn compile_rename(&self, from: &str, to: &str) -> Result<Statement> {
160        base::plain(self, format!("RENAME TABLE {} TO {}", self.quote(from)?, self.quote(to)?))
161    }
162
163    /// Empties table `name`.
164    ///
165    /// PHP: `compileTruncate()`.
166    fn compile_truncate(&self, name: &str) -> Result<Statement> {
167        base::plain(self, format!("TRUNCATE TABLE {}", self.quote(name)?))
168    }
169
170    /// `CREATE INDEX name ON table (columns)` with `options`.
171    ///
172    /// PHP: `createIndex()`.
173    fn create_index(&self, table: &str, name: &str, columns: &[&str], options: &IndexOptions) -> Result<Statement> {
174        base::create_index(self, table, name, columns, options)
175    }
176
177    /// Drops index `name` of `table`.
178    ///
179    /// PHP: `dropIndex()`.
180    fn drop_index(&self, table: &str, name: &str) -> Result<Statement> {
181        base::plain(self, format!("DROP INDEX {} ON {}", self.quote(name)?, self.quote(table)?))
182    }
183
184    /// The definition of `column` in `CREATE` / `ALTER TABLE`.
185    ///
186    /// PHP: `compileColumnDefinition()`.
187    fn compile_column_definition(&self, column: &Column<Self>) -> Result<String> {
188        base::column_definition(self, column)
189    }
190
191    /// `GENERATED ALWAYS AS (...) STORED|VIRTUAL`.
192    ///
193    /// PHP: `compileGeneratedClause()`.
194    fn compile_generated_clause(&self, column: &Column<Self>) -> String {
195        base::generated_clause(column)
196    }
197
198    /// Clauses after the column list of `CREATE TABLE` (partitioning).
199    ///
200    /// PHP: `compileCreateSuffix()`.
201    fn compile_create_suffix(&self, _table: &Table<Self>) -> String {
202        String::new()
203    }
204
205    /// A collation name as `COLLATE` takes it.
206    ///
207    /// PHP: `quoteCollation()`.
208    fn quote_collation(&self, collation: &str) -> Result<String> {
209        Ok(collation.to_owned())
210    }
211
212    /// How the dialect writes a string literal: comments, defaults and enum
213    /// values are inlined, since DDL takes no bound parameters.
214    ///
215    /// PHP: `$literal`.
216    fn literal(&self) -> crate::StringLiteral {
217        crate::StringLiteral::Backslash
218    }
219
220    /// The unsigned keyword, or empty where there is none.
221    ///
222    /// PHP: `compileUnsigned()`.
223    fn compile_unsigned(&self) -> &'static str {
224        "UNSIGNED"
225    }
226
227    /// The column list of an index: lengths, collations, operator class,
228    /// orders and raw expressions.
229    ///
230    /// PHP: `compileIndexColumns()`.
231    fn compile_index_columns(&self, index: &Index) -> Result<String> {
232        base::index_columns(self, index)
233    }
234}