use openehr_store::schema::Table;
use openehr_store::{ColTy, Dialect, Placeholder};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PostgresqlDialect;
impl Dialect for PostgresqlDialect {
fn name(&self) -> &'static str {
"PostgreSQL"
}
#[allow(clippy::match_same_arms)]
fn col_sql(&self, ty: ColTy) -> String {
match ty {
ColTy::Id(_) | ColTy::Text(_) | ColTy::LongText | ColTy::Instant => "text",
ColTy::Json => "text",
ColTy::InstantUtc => "timestamptz",
ColTy::Int => "bigint",
ColTy::Bool => "boolean",
ColTy::Digest => "bytea",
}
.to_owned()
}
fn quote(&self, identifier: &str) -> String {
format!("\"{}\"", identifier.replace('"', "\"\""))
}
fn placeholder(&self) -> Placeholder {
Placeholder::Dollar
}
fn append_only_sql(&self, table: &Table) -> Vec<String> {
let name = self.quote(table.name);
let function = format!("openehr_refuse_mutation_{}", table.name);
vec![
format!(
"CREATE OR REPLACE FUNCTION {}() RETURNS trigger AS $$\n\
BEGIN\n \
RAISE EXCEPTION '{} is append-only (openEHR V8.10)';\n\
END;\n$$ LANGUAGE plpgsql",
self.quote(&function),
table.name
),
format!(
"CREATE OR REPLACE TRIGGER {} BEFORE UPDATE OR DELETE ON {} \
FOR EACH ROW EXECUTE FUNCTION {}()",
self.quote(&format!("trg_append_only_{}", table.name)),
name,
self.quote(&function)
),
]
}
}