schema
ModuleSchema 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.
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 (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 |
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)"
);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";Contents
3 submodules, and what the module defines itself.
use utopia_query::schema::CheckConstraint;pub struct CheckConstraint {
pub name: String,
pub expression: String,
}A named table-level CHECK constraint.
PHP: Utopia\Query\Schema\CheckConstraint.
use utopia_query::schema::ClickHouse;pub struct ClickHouse {
// private fields
}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.
PHP: Utopia\Query\Schema\ClickHouse.
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`)"
);use Utopia\Query\Schema\ClickHouse;
use Utopia\Query\Schema\ClickHouse\Engine;
$table = (new ClickHouse())->table('events');
$table->bigInteger('id')->unsigned()->primary();
$table->string('country')->lowCardinality();
$table->datetime('at', 3);
$table->engine(Engine::MergeTree)->partitionBy('toYYYYMM(at)');
echo $table->create()->query, "\n";Debug.use utopia_query::schema::Index;pub struct Index {
pub name: String,
pub columns: Vec<String>,
pub kind: IndexType,
pub lengths: Vec<(String, i64)>,
pub orders: Vec<(String, String)>,
pub method: String,
pub operator_class: String,
pub collations: Vec<(String, String)>,
pub raw_columns: Vec<String>,
pub algorithm: Option<IndexAlgorithm>,
pub algorithm_args: Vec<Value>,
pub granularity: Option<i64>,
}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.
Index::new makes one with defaults; Index::validated runs the
checks PHP's constructor makes.
PHP: Utopia\Query\Schema\Index.
use utopia_query::schema::IndexOptions;pub struct IndexOptions {
pub unique: bool,
pub kind: Option<IndexType>,
pub method: String,
pub operator_class: String,
pub lengths: Vec<(String, i64)>,
pub orders: Vec<(String, String)>,
pub collations: Vec<(String, String)>,
pub raw_columns: Vec<String>,
pub concurrently: bool,
}The options of a standalone CREATE INDEX statement.
PHP: the optional parameters of Schema::createIndex().
use utopia_query::schema::MongoDb;pub struct MongoDb {
// private fields
}The MongoDB schema: collections with $jsonSchema validators, indexes,
views and databases as JSON commands ({"command": "createCollection", ...}).
PHP: Utopia\Query\Schema\MongoDB.
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"]}}}"#
);use Utopia\Query\Schema\MongoDB;
$users = (new MongoDB())->table('users');
$users->string('email');
$users->integer('age')->nullable();
echo $users->create()->query, "\n";Debug.use utopia_query::schema::MySql;pub struct MySql {
// private fields
}The MySQL schema: backtick quoting, AUTO_INCREMENT, inline indexes,
PARTITION BY ... PARTITIONS n.
PHP: Utopia\Query\Schema\MySQL.
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"
);use Utopia\Query\Schema\MySQL;
$table = (new MySQL())->table('events');
$table->id();
$table->json('payload')->nullable();
$table->partitionByHash('id', 4);
echo $table->create()->query, "\n";Debug.use utopia_query::schema::PostgreSql;pub struct PostgreSql {
// private fields
}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.
PHP: Utopia\Query\Schema\PostgreSQL.
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\")"
);use Utopia\Query\Schema\ColumnType;
use Utopia\Query\Schema\PostgreSQL;
$table = (new PostgreSQL())->table('users');
$table->addColumn('bio', ColumnType::Text)->nullable();
$table->dropColumn('legacy');
$table->index(['email']);
echo $table->alter()->query, "\n";Debug.use utopia_query::schema::RenameColumn;pub struct RenameColumn {
pub from: String,
pub to: String,
}A column rename of an ALTER TABLE.
PHP: Utopia\Query\Schema\RenameColumn.
use utopia_query::schema::Sqlite;pub struct Sqlite {
// private fields
}The SQLite schema: backtick quoting, INTEGER PRIMARY KEY AUTOINCREMENT
inline, TEXT for most types, DELETE FROM for truncation.
PHP: Utopia\Query\Schema\SQLite.
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)"
);use Utopia\Query\Schema\SQLite;
$table = (new SQLite())->table('notes');
$table->id();
$table->text('body');
echo $table->create()->query, "\n";Debug.use utopia_query::schema::ColumnType;pub enum ColumnType {
String,
Varchar,
Text,
MediumText,
LongText,
TinyInteger,
SmallInteger,
Integer,
BigInteger,
Float,
Double,
Decimal,
Boolean,
Datetime,
Timestamp,
Json,
Binary,
Enum,
Point,
Linestring,
Polygon,
Vector,
Id,
Uuid,
Uuid7,
Object,
Relationship,
Serial,
BigSerial,
SmallSerial,
Array,
Tuple,
}The portable type of a column; each dialect compiles it to its own SQL type (or BSON type).
PHP: Utopia\Query\Schema\ColumnType.
Display.use utopia_query::schema::Engine;pub enum Engine {
MergeTree,
ReplacingMergeTree,
SummingMergeTree,
AggregatingMergeTree,
CollapsingMergeTree,
ReplicatedMergeTree,
Memory,
Log,
TinyLog,
StripeLog,
}A ClickHouse table engine.
PHP: Utopia\Query\Schema\ClickHouse\Engine.
Display.use utopia_query::schema::ForeignKeyAction;pub enum ForeignKeyAction {
Cascade,
SetNull,
SetDefault,
Restrict,
NoAction,
}What a foreign key does when the referenced row is deleted or updated.
PHP: Utopia\Query\Schema\ForeignKeyAction.
Display.use utopia_query::schema::IndexAlgorithm;pub enum IndexAlgorithm {
MinMax,
Set,
BloomFilter,
NgramBloomFilter,
TokenBloomFilter,
Inverted,
}The algorithm of a ClickHouse data-skipping index.
PHP: Utopia\Query\Schema\ClickHouse\IndexAlgorithm.
Display.use utopia_query::schema::IndexType;pub enum IndexType {
Key,
Index,
Unique,
Fulltext,
Spatial,
Object,
HnswEuclidean,
HnswCosine,
HnswDot,
Trigram,
Ttl,
}The kind of an index.
PHP: Utopia\Query\Schema\IndexType.
Display.use utopia_query::schema::Order;pub enum Order {
Asc,
Desc,
}The order of an index column.
PHP: Utopia\Query\Schema\Order.
Display.use utopia_query::schema::ParameterDirection;pub enum ParameterDirection {
In,
Out,
InOut,
}The direction of a stored procedure parameter.
PHP: Utopia\Query\Schema\ParameterDirection.
Display.use utopia_query::schema::PartitionType;pub enum PartitionType {
Range,
List,
Hash,
}How a table is partitioned.
PHP: Utopia\Query\Schema\PartitionType.
Display.use utopia_query::schema::TriggerEvent;pub enum TriggerEvent {
Insert,
Update,
Delete,
}The statement a trigger fires on.
PHP: Utopia\Query\Schema\TriggerEvent.
Display.use utopia_query::schema::TriggerTiming;pub enum TriggerTiming {
Before,
After,
InsteadOf,
}When a trigger fires.
PHP: Utopia\Query\Schema\TriggerTiming.
Display.use utopia_query::schema::Schema;pub trait Schema: Clone + Send + Sync + Sized + 'staticA 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.
schema::column
Own page[Column]: a column of a table blueprint, with the modifiers its
dialect supports.
Modifiers every dialect has are inherent methods. The others are gated
by marker traits the dialects implement (Unique, Collation,
Generated, ...), so a modifier a dialect cannot express does not
exist on its columns, as in PHP where each dialect's column class only
uses the traits it supports.
use utopia_query::schema::column::Column;pub struct Column<S> {
// private fields
}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().
PHP: Utopia\Query\Schema\Column and its dialect classes
(Column\MySQL, Column\PostgreSQL, Column\SQLite,
Column\ClickHouse, Column\MongoDB).
Clone, Debug, PartialEq.use utopia_query::schema::column::ColumnDefinition;pub struct ColumnDefinition {
pub name: String,
pub kind: ColumnType,
pub length: Option<i64>,
pub precision: Option<i64>,
pub scale: Option<i64>,
pub nullable: bool,
pub default: Option<Value>,
pub default_raw: Option<String>,
pub unsigned: bool,
pub unique: bool,
pub primary: bool,
pub auto_increment: bool,
pub after: Option<String>,
pub comment: Option<String>,
pub enum_values: Vec<String>,
pub srid: Option<i64>,
pub dimensions: Option<i64>,
pub modify: bool,
pub collation: Option<String>,
pub check: Option<String>,
pub generated_expression: Option<String>,
pub generated_stored: Option<bool>,
pub ttl: Option<String>,
pub user_type: Option<String>,
pub low_cardinality: bool,
pub fixed_string_length: Option<i64>,
pub codecs: Vec<String>,
pub array_element_type: Option<ColumnType>,
pub tuple_element_types: Vec<ColumnType>,
}What a column is: its name, type, sizes and every modifier set on it.
PHP: the public properties of Utopia\Query\Schema\Column (and
Column\ClickHouse).
use utopia_query::schema::column::AutoIncrement;pub trait AutoIncrement: SchemaDialects whose columns can be server-incremented.
PHP: Column\Trait\AutoIncrement.
use utopia_query::schema::column::Collation;pub trait Collation: SchemaDialects with column-level collations.
PHP: Column\Trait\Collation.
use utopia_query::schema::column::Comment;pub trait Comment: SchemaDialects with inline column comments.
PHP: Column\Trait\Comment.
use utopia_query::schema::column::Dimensions;pub trait Dimensions: SchemaDialects whose vector columns have a declared width.
PHP: Column\Trait\Dimensions.
use utopia_query::schema::column::Generated;pub trait Generated: SchemaDialects with stored generated columns.
PHP: Column\Trait\Generated.
use utopia_query::schema::column::Positioning;pub trait Positioning: SchemaDialects that place columns with AFTER.
PHP: Column\Trait\Positioning.
use utopia_query::schema::column::Srid;pub trait Srid: SchemaDialects whose geometry columns carry an SRID.
PHP: Column\Trait\Srid.
use utopia_query::schema::column::Unique;pub trait Unique: SchemaDialects with column-level UNIQUE.
PHP: Column\Trait\Unique.
use utopia_query::schema::column::VirtualGenerated;pub trait VirtualGenerated: SchemaDialects with virtual generated columns.
PHP: Column\Trait\VirtualGenerated.
schema::feature
Own pageWhat 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.
PHP: the Utopia\Query\Schema\Feature\* interfaces.
use utopia_query::schema::feature::ViewBody;pub enum ViewBody<'a> {
Builder(&'a mut dyn AnyBuilder),
Sql(&'a str),
}The body of a materialized view: a builder (its SQL inlined, its bindings carried) or raw SQL, emitted verbatim (trusted input only).
PHP: Builder|string $body.
use utopia_query::schema::feature::AnalyzeTable;pub trait AnalyzeTable: SchemaRefreshing table statistics.
PHP: Schema\Feature\AnalyzeTable.
use utopia_query::schema::feature::ColumnComments;pub trait ColumnComments: SchemaColumn comments as separate statements.
PHP: Schema\Feature\ColumnComments.
use utopia_query::schema::feature::CreatePartition;pub trait CreatePartition: SchemaAdding partitions.
PHP: Schema\Feature\CreatePartition.
use utopia_query::schema::feature::Databases;pub trait Databases: SchemaDatabases (schemas on PostgreSQL).
PHP: Schema\Feature\Databases.
use utopia_query::schema::feature::DropPartition;pub trait DropPartition: SchemaDropping partitions.
PHP: Schema\Feature\DropPartition.
use utopia_query::schema::feature::ForeignKeys;pub trait ForeignKeys: SchemaAdding and dropping foreign-key constraints on existing tables.
PHP: Schema\Feature\ForeignKeys.
use utopia_query::schema::feature::MaterializedViews;pub trait MaterializedViews: SchemaMaterialized views.
PHP: Schema\Feature\MaterializedViews.
use utopia_query::schema::feature::Partitioning;pub trait Partitioning: SchemaPARTITION BY in CREATE TABLE.
PHP: Schema\Feature\Partitioning.
use utopia_query::schema::feature::Procedures;pub trait Procedures: SchemaStored procedures.
PHP: Schema\Feature\Procedures.
use utopia_query::schema::feature::RenameIndex;pub trait RenameIndex: SchemaRenaming indexes.
PHP: Schema\Feature\RenameIndex.
use utopia_query::schema::feature::ReplaceView;pub trait ReplaceView: SchemaCREATE OR REPLACE VIEW.
PHP: Schema\Feature\ReplaceView.
use utopia_query::schema::feature::Sequences;pub trait Sequences: SchemaSequences.
PHP: Schema\Feature\Sequences.
use utopia_query::schema::feature::TableComments;pub trait TableComments: SchemaTable comments.
PHP: Schema\Feature\TableComments.
use utopia_query::schema::feature::Triggers;pub trait Triggers: SchemaRow triggers.
PHP: Schema\Feature\Triggers.
use utopia_query::schema::feature::Types;pub trait Types: SchemaUser-defined enum types.
PHP: Schema\Feature\Types.
use utopia_query::schema::feature::Views;pub trait Views: SchemaViews.
PHP: Schema\Feature\Views.
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.
Factories and alterations every dialect has are inherent methods; the
others are gated by marker traits the dialects implement (Serial,
Checks, InlineForeignKey, ...), as PHP's dialect table classes
each use only the traits they support.
use utopia_query::schema::table::ForeignKey;pub struct ForeignKey {
pub column: String,
pub ref_table: String,
pub ref_column: String,
pub on_delete: Option<ForeignKeyAction>,
pub on_update: Option<ForeignKeyAction>,
}A foreign key: FOREIGN KEY (column) REFERENCES table (column) with
optional ON DELETE / ON UPDATE actions.
PHP: Utopia\Query\Schema\ForeignKey and its dialect classes.
use utopia_query::schema::table::Table;pub struct Table<S> {
// private fields
}A table blueprint for the dialect S: columns, indexes, keys and
alterations, compiled by the schema it came from.
PHP: Utopia\Query\Schema\Table and its dialect classes (Table\MySQL,
Table\PostgreSQL, Table\SQLite, Table\ClickHouse, Table\MongoDB).
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`))"
);use Utopia\Query\Schema\MySQL;
$users = (new MySQL())->table('users');
$users->id();
$users->string('email')->unique();
$users->foreignKey('team_id')->references('id')->on('teams');
echo $users->create()->query, "\n";Clone, Debug.use utopia_query::schema::table::TableDefinition;pub struct TableDefinition<S> {
pub name: String,
pub columns: Vec<Column<S>>,
pub indexes: Vec<Index>,
pub foreign_keys: Vec<ForeignKey>,
pub drop_columns: Vec<String>,
pub rename_columns: Vec<RenameColumn>,
pub drop_indexes: Vec<String>,
pub drop_foreign_keys: Vec<String>,
pub raw_column_defs: Vec<String>,
pub raw_index_defs: Vec<String>,
pub checks: Vec<CheckConstraint>,
pub composite_primary_key: Vec<String>,
pub order_by: Vec<String>,
pub partition_type: Option<PartitionType>,
pub partition_expression: String,
pub partition_count: Option<i64>,
pub engine: Option<Engine>,
pub engine_args: Vec<String>,
pub ttl: Option<String>,
pub settings: Vec<(String, String)>,
pub sample_by: Option<String>,
pub order_by_raw: Option<String>,
}Everything a table blueprint holds: added columns, indexes, keys, and the alterations, partitioning and engine options set on it.
PHP: the public properties of Utopia\Query\Schema\Table.
Clone, Debug.use utopia_query::schema::table::Checks;pub trait Checks: SchemaDialects with named table-level CHECK constraints (and column-level ones).
PHP: Table\Trait\Checks.
use utopia_query::schema::table::ColumnAlterations;pub trait ColumnAlterations: SchemaDialects that drop and rename columns in ALTER TABLE.
PHP: Table\Trait\ColumnAlterations.
use utopia_query::schema::table::CompositePrimary;pub trait CompositePrimary: SchemaDialects with composite primary keys.
PHP: Table\Trait\CompositePrimary.
use utopia_query::schema::table::ForeignKeys;pub trait ForeignKeys: InlineForeignKeyDialects that also add and drop foreign keys in ALTER TABLE.
PHP: Table\Trait\ForeignKeys.
use utopia_query::schema::table::FulltextSpatialIndex;pub trait FulltextSpatialIndex: SchemaDialects with full-text and spatial indexes.
PHP: Table\Trait\FulltextSpatialIndex.
use utopia_query::schema::table::InlineForeignKey;pub trait InlineForeignKey: SchemaDialects with inline foreign keys in CREATE TABLE.
PHP: Table\Trait\InlineForeignKey.
use utopia_query::schema::table::Serial;pub trait Serial: SchemaDialects with SERIAL column factories.
PHP: Table\Trait\Serial.
use utopia_query::schema::table::StandardPartitioning;pub trait StandardPartitioning: SchemaDialects with PARTITION BY RANGE / LIST / HASH.
PHP: Table\Trait\StandardPartitioning.