use crate::error::{MigratromError, Result};
use crate::types::{Check, ExecuteStep, Operation};
#[derive(Clone, Debug)]
pub struct RawCheck {
pub description: Option<String>,
pub sql: String,
}
impl RawCheck {
pub fn new(sql: impl Into<String>) -> Self {
Self {
description: None,
sql: sql.into(),
}
}
}
#[derive(Clone, Debug)]
pub struct RawStep {
pub description: Option<String>,
pub sql: String,
}
impl RawStep {
pub fn new(sql: impl Into<String>) -> Self {
Self {
description: None,
sql: sql.into(),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct RawSqlInput {
pub label: String,
pub precheck: Vec<RawCheck>,
pub execute: Vec<RawStep>,
pub postcheck: Vec<RawCheck>,
pub id: Option<String>,
}
pub fn raw_sql(input: RawSqlInput) -> Result<Operation> {
if input.execute.is_empty() {
return Err(MigratromError::Config(
"rawSql requires at least one execute step".to_string(),
));
}
if input.postcheck.is_empty() {
return Err(MigratromError::Config(
"rawSql requires at least one postcheck step".to_string(),
));
}
let id = input.id.unwrap_or_else(|| slugify(&input.label));
Ok(Operation {
id,
label: input.label,
precheck: input.precheck.into_iter().map(normalize_check).collect(),
execute: input.execute.into_iter().map(normalize_step).collect(),
postcheck: input.postcheck.into_iter().map(normalize_check).collect(),
outside_transaction: false,
})
}
fn normalize_check(c: RawCheck) -> Check {
Check {
description: c.description.unwrap_or_else(|| c.sql.clone()),
sql: c.sql,
}
}
fn normalize_step(s: RawStep) -> ExecuteStep {
ExecuteStep {
description: s.description.unwrap_or_else(|| s.sql.clone()),
sql: s.sql,
}
}
fn slugify(label: &str) -> String {
let mut out = String::with_capacity(label.len());
let mut prev_dot = false;
for ch in label.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
prev_dot = false;
} else if !prev_dot {
out.push('.');
prev_dot = true;
}
}
out.trim_matches('.').to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugifies_label_into_id() {
let op = raw_sql(RawSqlInput {
label: "Create Sequence raw_seq!".to_string(),
execute: vec![RawStep::new("CREATE SEQUENCE public.raw_seq")],
postcheck: vec![RawCheck::new(
"SELECT to_regclass('\"public\".\"raw_seq\"') IS NOT NULL",
)],
..Default::default()
})
.unwrap();
assert_eq!(op.id, "create.sequence.raw.seq");
assert_eq!(op.execute[0].description, op.execute[0].sql);
}
#[test]
fn requires_execute_and_postcheck() {
assert!(raw_sql(RawSqlInput {
label: "noop".to_string(),
..Default::default()
})
.is_err());
}
}