Rust

schema

Module

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 and table), and the statements beyond tables are capability traits in feature.

Rust
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)"
);

Contents

10 submodules, and what the module defines itself.

Defined here
use utopia_query::schema::Schema;
Rust
pub trait Schema: Clone + Send + Sync + Sized + 'static

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.

schema::clickhouse

Own page

[ClickHouse]: the ClickHouse schema.

use utopia_query::schema::clickhouse::ClickHouse;
Rust
pub struct ClickHouse

The ClickHouse schema: backtick quoting, Nullable(...) / LowCardinality(...) wrapping, engines with ORDER BY, PARTITION BY, SAMPLE BY, TTL and SETTINGS, data-skipping indexes, codecs and materialized views.

Rust
use utopia_query::schema::{ClickHouse, Engine, Schema};

let mut table = ClickHouse::new().table("events");
table.big_integer("id").unsigned().primary();
table.string("country", 255).low_cardinality();
table.datetime("at", 3);
table.engine(Engine::MergeTree, &[])?.partition_by("toYYYYMM(at)");
assert_eq!(
    table.create()?.query,
    "CREATE TABLE `events` (`id` UInt64, `country` LowCardinality(String), `at` DateTime64(3)) \
     ENGINE = MergeTree() PARTITION BY toYYYYMM(at) ORDER BY (`id`)"
);
Also implements Debug.

schema::column

Own page

[Column]: a column of a table blueprint, with the modifiers its dialect supports.

use utopia_query::schema::column::Column;
Rust
pub struct Column<S>

A column of a table blueprint for the dialect S.

Built by the table's factories (Table::string, Table::integer, ...), which return it to chain modifiers: table.string("email", 255).unique().nullable().

Also implements Clone, Debug, PartialEq.
use utopia_query::schema::column::ColumnDefinition;
Rust
pub struct ColumnDefinition

What a column is: its name, type, sizes and every modifier set on it.

use utopia_query::schema::column::AutoIncrement;
Rust
pub trait AutoIncrement: Schema

Dialects whose columns can be server-incremented.

use utopia_query::schema::column::Collation;
Rust
pub trait Collation: Schema

Dialects with column-level collations.

use utopia_query::schema::column::Comment;
Rust
pub trait Comment: Schema

Dialects with inline column comments.

use utopia_query::schema::column::Dimensions;
Rust
pub trait Dimensions: Schema

Dialects whose vector columns have a declared width.

use utopia_query::schema::column::Generated;
Rust
pub trait Generated: Schema

Dialects with stored generated columns.

use utopia_query::schema::column::Positioning;
Rust
pub trait Positioning: Schema

Dialects that place columns with AFTER.

use utopia_query::schema::column::Srid;
Rust
pub trait Srid: Schema

Dialects whose geometry columns carry an SRID.

use utopia_query::schema::column::Unique;
Rust
pub trait Unique: Schema

Dialects with column-level UNIQUE.

use utopia_query::schema::column::VirtualGenerated;
Rust
pub trait VirtualGenerated: Schema

Dialects with virtual generated columns.

schema::enums

Own page

The schema enumerations: column and index types, foreign-key actions, partitioning, triggers, procedure parameters and ClickHouse engines.

schema::feature

Own page

What a schema can do beyond tables and indexes: each trait is one capability a dialect may implement (foreign keys, procedures, triggers, views, partitions, ...), so callers can require it in a bound.

use utopia_query::schema::feature::ViewBody;
Rust
pub enum ViewBody<'a>

The body of a materialized view: a builder (its SQL inlined, its bindings carried) or raw SQL, emitted verbatim (trusted input only).

use utopia_query::schema::feature::AnalyzeTable;
Rust
pub trait AnalyzeTable: Schema

Refreshing table statistics.

use utopia_query::schema::feature::ColumnComments;
Rust
pub trait ColumnComments: Schema

Column comments as separate statements.

Implemented byClickHousePostgreSql
use utopia_query::schema::feature::CreatePartition;
Rust
pub trait CreatePartition: Schema

Adding partitions.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::Databases;
Rust
pub trait Databases: Schema

Databases (schemas on PostgreSQL).

use utopia_query::schema::feature::DropPartition;
Rust
pub trait DropPartition: Schema

Dropping partitions.

use utopia_query::schema::feature::ForeignKeys;
Rust
pub trait ForeignKeys: Schema

Adding and dropping foreign-key constraints on existing tables.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::MaterializedViews;
Rust
pub trait MaterializedViews: Schema

Materialized views.

Implemented byClickHouse
use utopia_query::schema::feature::Partitioning;
Rust
pub trait Partitioning: Schema

PARTITION BY in CREATE TABLE.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::Procedures;
Rust
pub trait Procedures: Schema

Stored procedures.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::RenameIndex;
Rust
pub trait RenameIndex: Schema

Renaming indexes.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::ReplaceView;
Rust
pub trait ReplaceView: Schema

CREATE OR REPLACE VIEW.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::Sequences;
Rust
pub trait Sequences: Schema

Sequences.

use utopia_query::schema::feature::TableComments;
Rust
pub trait TableComments: Schema

Table comments.

use utopia_query::schema::feature::Triggers;
Rust
pub trait Triggers: Schema

Row triggers.

Implemented byMySqlPostgreSql
use utopia_query::schema::feature::Types;
Rust
pub trait Types: Schema

User-defined enum types.

Implemented byPostgreSql
use utopia_query::schema::feature::Views;
Rust
pub trait Views: Schema

Views.

schema::index

Own page

The value parts of a table blueprint: indexes, check constraints and column renames, and the options of a standalone CREATE INDEX.

use utopia_query::schema::index::CheckConstraint;
Rust
pub struct CheckConstraint

A named table-level CHECK constraint.

use utopia_query::schema::index::Index;
Rust
pub struct Index

An index of a table: its columns (with per-column lengths, orders and collations), raw expressions, method and operator class, and for ClickHouse data-skipping indexes the algorithm, its arguments and the granularity.

use utopia_query::schema::index::IndexOptions;
Rust
pub struct IndexOptions

The options of a standalone CREATE INDEX statement.

use utopia_query::schema::index::RenameColumn;
Rust
pub struct RenameColumn

A column rename of an ALTER TABLE.

schema::mongodb

Own page

[MongoDb]: the MongoDB schema, whose statements are JSON commands.

use utopia_query::schema::mongodb::MongoDb;
Rust
pub struct MongoDb

The MongoDB schema: collections with $jsonSchema validators, indexes, views and databases as JSON commands ({"command": "createCollection", ...}).

Rust
use utopia_query::schema::{MongoDb, Schema};

let mut users = MongoDb::new().table("users");
users.string("email", 255);
users.integer("age").nullable();
assert_eq!(
    users.create()?.query,
    r#"{"command":"createCollection","collection":"users","validator":{"$jsonSchema":{"bsonType":"object","properties":{"email":{"bsonType":"string"},"age":{"bsonType":"int"}},"required":["email"]}}}"#
);
Also implements Debug.

schema::mysql

Own page

[MySql]: the MySQL / MariaDB schema.

use utopia_query::schema::mysql::MySql;
Rust
pub struct MySql

The MySQL schema: backtick quoting, AUTO_INCREMENT, inline indexes, PARTITION BY ... PARTITIONS n.

Rust
use utopia_query::schema::{MySql, Schema};

let schema = MySql::new();
let mut table = schema.table("events");
table.id("id");
table.json("payload").nullable();
table.partition_by_hash("id", Some(4))?;
assert_eq!(
    table.create()?.query,
    "CREATE TABLE `events` (`id` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, `payload` JSON NULL, \
     PRIMARY KEY (`id`)) PARTITION BY HASH(id) PARTITIONS 4"
);
Also implements Debug.

schema::postgresql

Own page

[PostgreSql]: the PostgreSQL schema.

use utopia_query::schema::postgresql::PostgreSql;
Rust
pub struct PostgreSql

The PostgreSQL schema: double-quote quoting, identity columns, SERIAL types, CHECK-emulated enums, standalone index statements, PL/pgSQL procedures and triggers, types, sequences, extensions and collations.

Rust
use utopia_query::schema::{PostgreSql, Schema};

let mut table = PostgreSql::new().table("users");
table.add_column("bio", utopia_query::schema::ColumnType::Text, None).nullable();
table.drop_column("legacy");
table.index(["email"])?;
assert_eq!(
    table.alter()?.query,
    "ALTER TABLE \"users\" ADD COLUMN \"bio\" TEXT NULL, DROP COLUMN \"legacy\"; \
     CREATE INDEX \"idx_email\" ON \"users\" (\"email\")"
);
Also implements Debug.

schema::sqlite

Own page

[Sqlite]: the SQLite schema.

use utopia_query::schema::sqlite::Sqlite;
Rust
pub struct Sqlite

The SQLite schema: backtick quoting, INTEGER PRIMARY KEY AUTOINCREMENT inline, TEXT for most types, DELETE FROM for truncation.

Rust
use utopia_query::schema::{Schema, Sqlite};

let mut table = Sqlite::new().table("notes");
table.id("id");
table.text("body");
assert_eq!(
    table.create()?.query,
    "CREATE TABLE `notes` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `body` TEXT NOT NULL)"
);
Also implements Debug.

schema::table

Own page

[Table]: a fluent table blueprint, compiled by its schema into CREATE TABLE, ALTER TABLE and the other table statements; and ForeignKey, a foreign key declared on it.

use utopia_query::schema::table::ForeignKey;
Rust
pub struct ForeignKey

A foreign key: FOREIGN KEY (column) REFERENCES table (column) with optional ON DELETE / ON UPDATE actions.

use utopia_query::schema::table::Table;
Rust
pub struct Table<S>

A table blueprint for the dialect S: columns, indexes, keys and alterations, compiled by the schema it came from.

Rust
use utopia_query::schema::{MySql, Schema};

let mut users = MySql::new().table("users");
users.id("id");
users.string("email", 255).unique();
users.foreign_key("team_id").references("id").on("teams");
assert_eq!(
    users.create()?.query,
    "CREATE TABLE `users` (`id` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, `email` VARCHAR(255) NOT NULL, \
     PRIMARY KEY (`id`), UNIQUE (`email`), FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`))"
);
Also implements Clone, Debug.
use utopia_query::schema::table::TableDefinition;
Rust
pub struct TableDefinition<S>

Everything a table blueprint holds: added columns, indexes, keys, and the alterations, partitioning and engine options set on it.

Also implements Clone, Debug.
use utopia_query::schema::table::Checks;
Rust
pub trait Checks: Schema

Dialects with named table-level CHECK constraints (and column-level ones).

use utopia_query::schema::table::ColumnAlterations;
Rust
pub trait ColumnAlterations: Schema

Dialects that drop and rename columns in ALTER TABLE.

use utopia_query::schema::table::CompositePrimary;
Rust
pub trait CompositePrimary: Schema

Dialects with composite primary keys.

use utopia_query::schema::table::ForeignKeys;
Rust
pub trait ForeignKeys: InlineForeignKey

Dialects that also add and drop foreign keys in ALTER TABLE.

Implemented byMySqlPostgreSql
use utopia_query::schema::table::FulltextSpatialIndex;
Rust
pub trait FulltextSpatialIndex: Schema

Dialects with full-text and spatial indexes.

use utopia_query::schema::table::InlineForeignKey;
Rust
pub trait InlineForeignKey: Schema

Dialects with inline foreign keys in CREATE TABLE.

use utopia_query::schema::table::Serial;
Rust
pub trait Serial: Schema

Dialects with SERIAL column factories.

use utopia_query::schema::table::StandardPartitioning;
Rust
pub trait StandardPartitioning: Schema

Dialects with PARTITION BY RANGE / LIST / HASH.