utopia-query 0.1.1

Queries as data, compiled to SQL (MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse) and MongoDB commands; schema builders; a SQL tokenizer, parser, serializer and statement classifier.
Documentation
//! Schema builders: DDL for tables, columns, indexes, views, procedures and
//! triggers, per dialect.
//!
//! A schema ([`MySql`], [`PostgreSql`], [`Sqlite`], [`ClickHouse`],
//! [`MongoDb`]) compiles statements; [`Schema::table`] starts a fluent
//! [`Table`] blueprint whose terminal methods ([`Table::create`],
//! [`Table::alter`], [`Table::drop`], ...) compile it. Each dialect only has
//! the column and table methods it can express (marker traits in
//! [`column`](mod@column) and [`table`]), and the statements beyond tables are
//! capability traits in [`feature`].
//!
//! ```
//! use utopia_query::schema::{ForeignKeyAction, PostgreSql, Schema};
//!
//! let mut posts = PostgreSql::new().table("posts");
//! posts.id("id");
//! posts.string("title", 120);
//! posts.integer("author_id");
//! posts.foreign_key("author_id").references("id").on("users").on_delete(ForeignKeyAction::Cascade);
//! assert_eq!(
//!     posts.create()?.query,
//!     "CREATE TABLE \"posts\" (\"id\" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, \
//!      \"title\" VARCHAR(120) NOT NULL, \"author_id\" INTEGER NOT NULL, PRIMARY KEY (\"id\"), \
//!      FOREIGN KEY (\"author_id\") REFERENCES \"users\" (\"id\") ON DELETE CASCADE)"
//! );
//! # Ok::<(), utopia_query::Error>(())
//! ```
//!
//! ```php
//! use Utopia\Query\Schema\ForeignKeyAction;
//! use Utopia\Query\Schema\PostgreSQL;
//!
//! $posts = (new PostgreSQL())->table('posts');
//! $posts->id();
//! $posts->string('title', 120);
//! $posts->integer('author_id');
//! $posts->foreignKey('author_id')->references('id')->on('users')->onDelete(ForeignKeyAction::Cascade);
//! echo $posts->create()->query, "\n";
//! ```
//!
//! PHP: `Utopia\Query\Schema`, `Utopia\Query\Schema\*`.
//!
//! | PHP | Rust |
//! |---|---|
//! | `Schema` (abstract), `Schema\SQL` | [`Schema`] (trait) |
//! | `Schema\MySQL`, `PostgreSQL`, `SQLite`, `ClickHouse`, `MongoDB` | [`MySql`], [`PostgreSql`], [`Sqlite`], [`ClickHouse`], [`MongoDb`] |
//! | `Schema\Table`, `Table\*` | [`Table`] (`Table<MySql>`, ...), [`TableDefinition`] (its properties) |
//! | `Table\Trait\*` | marker traits in [`table`] ([`table::Serial`], [`table::Checks`], ...) |
//! | `Schema\Column`, `Column\*` | [`Column`] (`Column<MySql>`, ...), [`ColumnDefinition`] (its properties) |
//! | `Column\Trait\*` | marker traits in [`column`](mod@column) ([`column::Unique`], [`column::Collation`], ...) |
//! | `Schema\ForeignKey`, `ForeignKey\*` | [`ForeignKey`] |
//! | `Schema\Forwarder\*` | none: a column or key handle borrows its table, so table methods are called on the table |
//! | `Schema\Index`, `CheckConstraint`, `RenameColumn` | [`Index`], [`CheckConstraint`], [`RenameColumn`] |
//! | `createIndex()` options | [`IndexOptions`] |
//! | `Schema\Feature\*` | traits in [`feature`] |
//! | `Schema\Trait\*` | the dialects' implementations of those traits |
//! | `ColumnType`, `IndexType`, `ForeignKeyAction`, `Order`, `ParameterDirection`, `PartitionType`, `TriggerEvent`, `TriggerTiming` | [`ColumnType`], [`IndexType`], [`ForeignKeyAction`], [`Order`], [`ParameterDirection`], [`PartitionType`], [`TriggerEvent`], [`TriggerTiming`] |
//! | `Schema\ClickHouse\Engine`, `ClickHouse\IndexAlgorithm` | [`Engine`], [`IndexAlgorithm`] |

mod base;
mod clickhouse;
pub mod column;
mod enums;
pub mod feature;
mod index;
mod mongodb;
mod mysql;
mod names;
mod postgresql;
mod sqlite;
pub mod table;

pub use clickhouse::ClickHouse;
pub use column::{Column, ColumnDefinition};
pub use enums::{
    ColumnType, Engine, ForeignKeyAction, IndexAlgorithm, IndexType, Order, ParameterDirection, PartitionType,
    TriggerEvent, TriggerTiming,
};
pub use feature::ViewBody;
pub use index::{CheckConstraint, Index, IndexOptions, RenameColumn};
pub use mongodb::MongoDb;
pub use mysql::MySql;
pub use postgresql::PostgreSql;
pub use sqlite::Sqlite;
pub use table::{ForeignKey, Table, TableDefinition};

use crate::builder::{Executor, Statement};
use crate::error::Result;

/// A dialect's DDL compiler: quoting, column types, and the table, index
/// and drop statements. Dialects override the steps they write
/// differently; the provided methods are the shared (MySQL-flavoured)
/// compilation.
///
/// Implement it (and the [`feature`] traits) to add a dialect.
///
/// PHP: the abstract `Utopia\Query\Schema`.
pub trait Schema: Clone + Send + Sync + Sized + 'static {
    /// The executor statements carry, if any.
    fn executor(&self) -> Option<&Executor>;

    /// Sets the executor every statement compiled from now on carries
    /// ([`Statement::execute`] runs it).
    ///
    /// PHP: `setExecutor()`.
    fn set_executor(&mut self, executor: Executor) -> &mut Self;

    /// Quotes a possibly qualified identifier.
    ///
    /// PHP: `quote()`.
    fn quote(&self, identifier: &str) -> Result<String>;

    /// Quotes one identifier, dots included.
    ///
    /// PHP: `quoteLiteral()`.
    fn quote_literal(&self, identifier: &str) -> Result<String>;

    /// The SQL type of `column`.
    ///
    /// PHP: `compileColumnType()`.
    fn compile_column_type(&self, column: &Column<Self>) -> Result<String>;

    /// The auto-increment keyword.
    ///
    /// PHP: `compileAutoIncrement()`.
    fn compile_auto_increment(&self) -> &'static str;

    /// A blueprint of table `name` compiled by this schema.
    ///
    /// PHP: `table()`.
    fn table(&self, name: impl Into<String>) -> Table<Self> {
        Table::with_schema(self.clone(), name)
    }

    /// `CREATE TABLE [IF NOT EXISTS]` for `table`.
    ///
    /// PHP: `compileCreate()`.
    fn compile_create(&self, table: &Table<Self>, if_not_exists: bool) -> Result<Statement> {
        base::create(self, table, if_not_exists)
    }

    /// `ALTER TABLE` for `table`.
    ///
    /// PHP: `compileAlter()`.
    fn compile_alter(&self, table: &Table<Self>) -> Result<Statement> {
        base::alter(self, table)
    }

    /// `DROP TABLE [IF EXISTS] name`.
    ///
    /// PHP: `compileDrop()`.
    fn compile_drop(&self, name: &str, if_exists: bool) -> Result<Statement> {
        base::plain(self, format!("DROP TABLE {}{}", if if_exists { "IF EXISTS " } else { "" }, self.quote(name)?))
    }

    /// Renames table `from` to `to`.
    ///
    /// PHP: `compileRename()`.
    fn compile_rename(&self, from: &str, to: &str) -> Result<Statement> {
        base::plain(self, format!("RENAME TABLE {} TO {}", self.quote(from)?, self.quote(to)?))
    }

    /// Empties table `name`.
    ///
    /// PHP: `compileTruncate()`.
    fn compile_truncate(&self, name: &str) -> Result<Statement> {
        base::plain(self, format!("TRUNCATE TABLE {}", self.quote(name)?))
    }

    /// `CREATE INDEX name ON table (columns)` with `options`.
    ///
    /// PHP: `createIndex()`.
    fn create_index(&self, table: &str, name: &str, columns: &[&str], options: &IndexOptions) -> Result<Statement> {
        base::create_index(self, table, name, columns, options)
    }

    /// Drops index `name` of `table`.
    ///
    /// PHP: `dropIndex()`.
    fn drop_index(&self, table: &str, name: &str) -> Result<Statement> {
        base::plain(self, format!("DROP INDEX {} ON {}", self.quote(name)?, self.quote(table)?))
    }

    /// The definition of `column` in `CREATE` / `ALTER TABLE`.
    ///
    /// PHP: `compileColumnDefinition()`.
    fn compile_column_definition(&self, column: &Column<Self>) -> Result<String> {
        base::column_definition(self, column)
    }

    /// `GENERATED ALWAYS AS (...) STORED|VIRTUAL`.
    ///
    /// PHP: `compileGeneratedClause()`.
    fn compile_generated_clause(&self, column: &Column<Self>) -> String {
        base::generated_clause(column)
    }

    /// Clauses after the column list of `CREATE TABLE` (partitioning).
    ///
    /// PHP: `compileCreateSuffix()`.
    fn compile_create_suffix(&self, _table: &Table<Self>) -> String {
        String::new()
    }

    /// A collation name as `COLLATE` takes it.
    ///
    /// PHP: `quoteCollation()`.
    fn quote_collation(&self, collation: &str) -> Result<String> {
        Ok(collation.to_owned())
    }

    /// How the dialect writes a string literal: comments, defaults and enum
    /// values are inlined, since DDL takes no bound parameters.
    ///
    /// PHP: `$literal`.
    fn literal(&self) -> crate::StringLiteral {
        crate::StringLiteral::Backslash
    }

    /// The unsigned keyword, or empty where there is none.
    ///
    /// PHP: `compileUnsigned()`.
    fn compile_unsigned(&self) -> &'static str {
        "UNSIGNED"
    }

    /// The column list of an index: lengths, collations, operator class,
    /// orders and raw expressions.
    ///
    /// PHP: `compileIndexColumns()`.
    fn compile_index_columns(&self, index: &Index) -> Result<String> {
        base::index_columns(self, index)
    }
}