use std::fmt::Write;
use super::sql::{Dialect, quote_ident};
use super::value::{ToValue, Value};
use super::{Repo, Sql};
use crate::error::{Error, Result};
pub(crate) const MIGRATIONS_TABLE: &str = "schema_migrations";
pub(crate) const BESIDE_RAILS_TABLE: &str = "glacier_schema_migrations";
pub struct Schema {
dialect: Dialect,
statements: Vec<String>,
}
impl Schema {
pub fn new(dialect: Dialect) -> Self {
Self {
dialect,
statements: Vec::new(),
}
}
pub fn dialect(&self) -> Dialect {
self.dialect
}
pub fn statements(&self) -> &[String] {
&self.statements
}
pub fn create_table(&mut self, name: &str, define: impl FnOnce(&mut Table)) {
let mut table = Table {
dialect: self.dialect,
columns: Vec::new(),
};
define(&mut table);
let id = match self.dialect {
Dialect::Postgres => "\"id\" BIGSERIAL PRIMARY KEY",
Dialect::Sqlite => "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT",
};
let mut definitions = vec![id.to_owned()];
definitions.extend(table.columns.iter().map(Column::definition));
definitions.extend(table.columns.iter().filter_map(Column::foreign_key));
self.statements.push(format!(
"CREATE TABLE {} (\n {}\n)",
quote_ident(name),
definitions.join(",\n ")
));
}
pub fn drop_table(&mut self, name: &str) {
self.statements
.push(format!("DROP TABLE {}", quote_ident(name)));
}
pub fn rename_table(&mut self, from: &str, to: &str) {
self.statements.push(format!(
"ALTER TABLE {} RENAME TO {}",
quote_ident(from),
quote_ident(to)
));
}
pub fn alter_table(&mut self, name: &str, change: impl FnOnce(&mut Alter)) {
let mut alter = Alter {
dialect: self.dialect,
table: name.to_owned(),
columns: Vec::new(),
statements: Vec::new(),
};
change(&mut alter);
for column in &alter.columns {
let mut definition = column.definition();
if let Some(reference) = column.reference_clause() {
definition.push_str(&reference);
}
alter.statements.push(format!(
"ALTER TABLE {} ADD COLUMN {definition}",
quote_ident(name)
));
}
self.statements.extend(alter.statements);
}
pub fn add_index(&mut self, table: &str, columns: &[&str]) {
self.index(table, columns, false);
}
pub fn add_unique_index(&mut self, table: &str, columns: &[&str]) {
self.index(table, columns, true);
}
pub fn drop_index(&mut self, table: &str, columns: &[&str]) {
self.statements.push(format!(
"DROP INDEX {}",
quote_ident(&index_name(table, columns))
));
}
fn index(&mut self, table: &str, columns: &[&str], unique: bool) {
let list: Vec<String> = columns.iter().map(|c| quote_ident(c)).collect();
self.statements.push(format!(
"CREATE {}INDEX {} ON {} ({})",
if unique { "UNIQUE " } else { "" },
quote_ident(&index_name(table, columns)),
quote_ident(table),
list.join(", ")
));
}
pub fn execute(&mut self, sql: &str) {
self.statements.push(sql.to_owned());
}
}
fn index_name(table: &str, columns: &[&str]) -> String {
format!("{table}_{}_index", columns.join("_"))
}
pub struct Table {
dialect: Dialect,
columns: Vec<Column>,
}
macro_rules! column_types {
($($(#[$doc:meta])* $method:ident => $pg:literal, $sqlite:literal;)*) => {
$(
$(#[$doc])*
pub fn $method(&mut self, name: &str) -> &mut Column {
let sql_type = match self.dialect {
Dialect::Postgres => $pg,
Dialect::Sqlite => $sqlite,
};
self.add(name, sql_type)
}
)*
};
}
impl Table {
column_types! {
string => "VARCHAR", "TEXT";
text => "TEXT", "TEXT";
integer => "INTEGER", "INTEGER";
bigint => "BIGINT", "BIGINT";
float => "DOUBLE PRECISION", "REAL";
boolean => "BOOLEAN", "BOOLEAN";
timestamp => "TIMESTAMPTZ", "TEXT";
binary => "BYTEA", "BLOB";
json => "JSONB", "TEXT";
}
pub fn references(&mut self, name: &str) -> &mut Column {
let table = glacier_inflect::pluralize(name);
self.references_table(name, &table)
}
pub fn references_table(&mut self, name: &str, table: &str) -> &mut Column {
let column = self.bigint(&format!("{name}_id"));
column.references = Some(table.to_owned());
column
}
pub fn timestamps(&mut self) {
self.timestamp("inserted_at").not_null();
self.timestamp("updated_at").not_null();
}
fn add(&mut self, name: &str, sql_type: &'static str) -> &mut Column {
self.columns.push(Column {
name: name.to_owned(),
sql_type,
not_null: false,
unique: false,
default: None,
references: None,
on_delete: None,
dialect: self.dialect,
});
self.columns.last_mut().expect("just pushed")
}
}
pub struct Alter {
dialect: Dialect,
table: String,
columns: Vec<Column>,
statements: Vec<String>,
}
macro_rules! alter_column_types {
($($method:ident),*) => {
$(
#[doc = concat!("Adds a column; see [`Table::", stringify!($method), "`].")]
pub fn $method(&mut self, name: &str) -> &mut Column {
let mut table = Table { dialect: self.dialect, columns: Vec::new() };
table.$method(name);
self.columns.extend(table.columns);
self.columns.last_mut().expect("just added")
}
)*
};
}
impl Alter {
alter_column_types!(
string, text, integer, bigint, float, boolean, timestamp, binary, json
);
pub fn references(&mut self, name: &str) -> &mut Column {
let mut table = Table {
dialect: self.dialect,
columns: Vec::new(),
};
table.references(name);
self.columns.extend(table.columns);
self.columns.last_mut().expect("just added")
}
pub fn drop_column(&mut self, name: &str) {
self.statements.push(format!(
"ALTER TABLE {} DROP COLUMN {}",
quote_ident(&self.table),
quote_ident(name)
));
}
pub fn rename_column(&mut self, from: &str, to: &str) {
self.statements.push(format!(
"ALTER TABLE {} RENAME COLUMN {} TO {}",
quote_ident(&self.table),
quote_ident(from),
quote_ident(to)
));
}
}
pub struct Column {
name: String,
sql_type: &'static str,
not_null: bool,
unique: bool,
default: Option<String>,
references: Option<String>,
on_delete: Option<&'static str>,
dialect: Dialect,
}
impl Column {
pub fn not_null(&mut self) -> &mut Self {
self.not_null = true;
self
}
pub fn unique(&mut self) -> &mut Self {
self.unique = true;
self
}
pub fn default(&mut self, value: impl ToValue) -> &mut Self {
self.default = Some(literal(&value.to_value(), self.dialect));
self
}
pub fn on_delete_cascade(&mut self) -> &mut Self {
self.on_delete = Some("CASCADE");
self
}
pub fn on_delete_nullify(&mut self) -> &mut Self {
self.on_delete = Some("SET NULL");
self
}
fn definition(&self) -> String {
let mut sql = format!("{} {}", quote_ident(&self.name), self.sql_type);
if self.not_null {
sql.push_str(" NOT NULL");
}
if self.unique {
sql.push_str(" UNIQUE");
}
if let Some(default) = &self.default {
let _ = write!(sql, " DEFAULT {default}");
}
sql
}
fn reference_clause(&self) -> Option<String> {
let table = self.references.as_ref()?;
let mut sql = format!(" REFERENCES {}(\"id\")", quote_ident(table));
if let Some(action) = self.on_delete {
let _ = write!(sql, " ON DELETE {action}");
}
Some(sql)
}
fn foreign_key(&self) -> Option<String> {
let clause = self.reference_clause()?;
Some(format!("FOREIGN KEY ({}){clause}", quote_ident(&self.name)))
}
}
fn literal(value: &Value, dialect: Dialect) -> String {
match value {
Value::Null => "NULL".into(),
Value::Bool(true) => "TRUE".into(),
Value::Bool(false) => "FALSE".into(),
Value::Int(v) => v.to_string(),
Value::Float(v) => v.to_string(),
Value::Text(v) => format!("'{}'", v.replace('\'', "''")),
Value::Timestamp(v) => match dialect {
Dialect::Postgres => format!("'{}'", v.to_rfc3339()),
Dialect::Sqlite => format!("'{}'", super::sqlite_timestamp(v)),
},
Value::Json(v) => format!("'{}'", v.to_string().replace('\'', "''")),
Value::Decimal(v) => v.to_string(),
Value::Uuid(v) => format!("'{v}'"),
Value::List(items) => items
.iter()
.map(|item| literal(item, dialect))
.collect::<Vec<_>>()
.join(", "),
Value::Date(v) => format!("'{v}'"),
Value::Bytes(v) => {
let hex: String = v.iter().map(|b| format!("{b:02x}")).collect();
match dialect {
Dialect::Postgres => format!("'\\x{hex}'"),
Dialect::Sqlite => format!("X'{hex}'"),
}
}
}
}
#[derive(Clone)]
pub struct Migration {
version: String,
name: String,
up: fn(&mut Schema),
down: fn(&mut Schema),
}
impl Migration {
pub fn new(name: &str, up: fn(&mut Schema), down: fn(&mut Schema)) -> Self {
let trimmed = name.trim_start_matches('m');
let version: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
Self {
version,
name: name.to_owned(),
up,
down,
}
}
pub fn version(&self) -> &str {
&self.version
}
pub fn name(&self) -> &str {
&self.name
}
pub fn up_sql(&self, dialect: Dialect) -> Vec<String> {
let mut schema = Schema::new(dialect);
(self.up)(&mut schema);
schema.statements
}
pub fn down_sql(&self, dialect: Dialect) -> Vec<String> {
let mut schema = Schema::new(dialect);
(self.down)(&mut schema);
schema.statements
}
}
pub struct Migrator {
repo: Repo,
migrations: Vec<Migration>,
table: tokio::sync::OnceCell<&'static str>,
}
pub struct Status {
pub migration: Migration,
pub applied: bool,
}
impl Migrator {
pub fn new(repo: &Repo, mut migrations: Vec<Migration>) -> Result<Self> {
migrations.sort_by(|a, b| a.version.cmp(&b.version));
for migration in &migrations {
if migration.version.is_empty() {
return Err(Error::internal(format!(
"migration `{}` needs a name like m20261003120000_create_posts",
migration.name
)));
}
}
if let Some(pair) = migrations
.windows(2)
.find(|pair| pair[0].version == pair[1].version)
{
return Err(Error::internal(format!(
"migrations `{}` and `{}` share version {}",
pair[0].name, pair[1].name, pair[0].version
)));
}
Ok(Self {
repo: repo.clone(),
migrations,
table: tokio::sync::OnceCell::new(),
})
}
async fn table(&self) -> Result<&'static str> {
self.table
.get_or_try_init(|| async {
let columns = match self.repo.dialect() {
Dialect::Postgres => {
super::sql(
"SELECT column_name AS name FROM information_schema.columns \
WHERE table_schema = current_schema() AND table_name = ?",
)
.bind(MIGRATIONS_TABLE)
.on(&self.repo)
.fetch_all()
.await?
}
Dialect::Sqlite => {
super::sql(&format!("PRAGMA table_info({MIGRATIONS_TABLE})"))
.on(&self.repo)
.fetch_all()
.await?
}
};
let names: Vec<String> = columns
.iter()
.filter_map(|row| row.get::<String>("name").ok())
.collect();
let rails = !names.is_empty() && !names.iter().any(|n| n == "inserted_at");
Ok::<_, Error>(if rails {
BESIDE_RAILS_TABLE
} else {
MIGRATIONS_TABLE
})
})
.await
.copied()
}
async fn ensure_table(&self) -> Result<()> {
let table = self.table().await?;
let sql = format!(
"CREATE TABLE IF NOT EXISTS {table} (version VARCHAR(255) PRIMARY KEY, inserted_at {})",
match self.repo.dialect() {
Dialect::Postgres => "TIMESTAMPTZ",
Dialect::Sqlite => "TEXT",
}
);
if let Err(err) = super::sql(&sql).on(&self.repo).execute().await {
let exists = super::sql(&format!("SELECT 1 FROM {table} WHERE 1 = 0"))
.on(&self.repo)
.fetch_all()
.await
.is_ok();
if !exists {
return Err(err);
}
}
Ok(())
}
async fn applied(&self) -> Result<Vec<String>> {
self.ensure_table().await?;
let table = self.table().await?;
let rows = super::sql(&format!("SELECT version FROM {table} ORDER BY version"))
.on(&self.repo)
.fetch_all()
.await?;
rows.iter().map(|row| row.get("version")).collect()
}
pub async fn status(&self) -> Result<Vec<Status>> {
let applied = self.applied().await?;
Ok(self
.migrations
.iter()
.map(|m| Status {
migration: m.clone(),
applied: applied.contains(&m.version),
})
.collect())
}
pub async fn pending(&self) -> Result<Vec<Migration>> {
Ok(self
.status()
.await?
.into_iter()
.filter(|s| !s.applied)
.map(|s| s.migration)
.collect())
}
pub async fn migrate(&self) -> Result<Vec<String>> {
let mut done = Vec::new();
let table = self.table().await?;
for migration in self.pending().await? {
let tx = self.repo.begin().await?;
for statement in migration.up_sql(self.repo.dialect()) {
super::sql(&statement)
.on(&tx)
.execute()
.await
.map_err(|e| {
Error::internal(format!("{}: {}\n{statement}", migration.name, e.message()))
})?;
}
let mut record = Sql::new();
record
.push(&format!(
"INSERT INTO {table} (version, inserted_at) VALUES ("
))
.push_value(Value::Text(migration.version.clone()))
.push(", ")
.push_value(Value::Timestamp(chrono::Utc::now()))
.push(")");
super::Connection::from(&tx).execute(&record).await?;
tx.commit().await?;
done.push(migration.name);
}
Ok(done)
}
pub async fn rollback(&self, steps: usize) -> Result<Vec<String>> {
let applied = self.applied().await?;
let table = self.table().await?;
let mut done = Vec::new();
for version in applied.iter().rev().take(steps) {
let migration = self
.migrations
.iter()
.find(|m| &m.version == version)
.ok_or_else(|| {
Error::internal(format!(
"migration {version} is applied but missing from the code"
))
})?;
let tx = self.repo.begin().await?;
for statement in migration.down_sql(self.repo.dialect()) {
super::sql(&statement)
.on(&tx)
.execute()
.await
.map_err(|e| {
Error::internal(format!("{}: {}\n{statement}", migration.name, e.message()))
})?;
}
super::sql(&format!("DELETE FROM {table} WHERE version = ?"))
.bind(version.as_str())
.on(&tx)
.execute()
.await?;
tx.commit().await?;
done.push(migration.name.clone());
}
Ok(done)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn up(s: &mut Schema) {
s.create_table("posts", |t| {
t.string("title").not_null();
t.integer("views").not_null().default(0);
t.boolean("published").not_null().default(false);
t.references("author").on_delete_cascade();
t.timestamps();
});
s.add_unique_index("posts", &["title"]);
}
#[test]
fn renders_create_table_per_dialect() {
let m = Migration::new("m20261003120000_create_posts", up, |_| {});
assert_eq!(m.version(), "20261003120000");
let pg = m.up_sql(Dialect::Postgres);
assert_eq!(
pg[0],
"CREATE TABLE \"posts\" (\n \"id\" BIGSERIAL PRIMARY KEY,\n \"title\" VARCHAR NOT NULL,\n \"views\" INTEGER NOT NULL DEFAULT 0,\n \"published\" BOOLEAN NOT NULL DEFAULT FALSE,\n \"author_id\" BIGINT,\n \"inserted_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n FOREIGN KEY (\"author_id\") REFERENCES \"authors\"(\"id\") ON DELETE CASCADE\n)"
);
assert_eq!(
pg[1],
"CREATE UNIQUE INDEX \"posts_title_index\" ON \"posts\" (\"title\")"
);
let sqlite = m.up_sql(Dialect::Sqlite);
assert!(sqlite[0].contains("\"id\" INTEGER PRIMARY KEY AUTOINCREMENT"));
assert!(sqlite[0].contains("\"inserted_at\" TEXT NOT NULL"));
}
#[test]
fn renders_literals() {
assert_eq!(
literal(&Value::Text("it's".into()), Dialect::Sqlite),
"'it''s'"
);
assert_eq!(
literal(&Value::Bytes(vec![1, 255]), Dialect::Sqlite),
"X'01ff'"
);
assert_eq!(
literal(&Value::Bytes(vec![1, 255]), Dialect::Postgres),
"'\\x01ff'"
);
}
}