use serde::{Deserialize, Serialize};
pub mod composite;
pub mod procedure;
pub mod trigger;
use crate::IgnisObject;
pub use composite::{CompositeField, CompositeType, CompositeTypeRegistry};
pub use procedure::{
FunctionSecurity, FunctionVolatility, ParameterMode, ProcedureLanguage, ProcedureParameter,
ProcedureRegistry, StoredFunction, StoredProcedure,
};
pub use trigger::{Trigger, TriggerEvent, TriggerOrientation, TriggerReferencing, TriggerTiming};
fn escape_sql_identifier(identifier: &str) -> String {
format!("\"{}\"", identifier.replace("\"", "\"\"")).to_lowercase()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Sequence {
pub name: String,
pub schema: Option<String>,
pub data_type: String,
pub start_value: Option<i64>,
pub minimum_value: Option<i64>,
pub maximum_value: Option<i64>,
pub increment: Option<i64>,
pub cycle: Option<bool>,
pub cache: Option<i64>,
pub owner: Option<String>,
pub comment: Option<String>,
}
impl Sequence {
pub fn new(name: impl Into<String>, data_type: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
data_type: data_type.into(),
start_value: None,
minimum_value: None,
maximum_value: None,
increment: None,
cycle: None,
cache: None,
owner: None,
comment: None,
}
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn with_start_value(mut self, start: i64) -> Self {
self.start_value = Some(start);
self
}
pub fn with_minimum_value(mut self, min: i64) -> Self {
self.minimum_value = Some(min);
self
}
pub fn with_maximum_value(mut self, max: i64) -> Self {
self.maximum_value = Some(max);
self
}
pub fn with_increment(mut self, increment: i64) -> Self {
self.increment = Some(increment);
self
}
pub fn with_cycle(mut self, cycle: bool) -> Self {
self.cycle = Some(cycle);
self
}
pub fn with_cache(mut self, cache: i64) -> Self {
self.cache = Some(cache);
self
}
pub fn with_owner(mut self, owner: impl Into<String>) -> Self {
self.owner = Some(owner.into());
self
}
pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn qualified_name(&self) -> String {
if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
}
}
pub fn generate_create_ddl(&self) -> String {
let mut ddl = format!("CREATE SEQUENCE {}", self.qualified_name());
use std::fmt::Write;
write!(ddl, " AS {}", self.data_type).unwrap();
if let Some(start) = self.start_value {
write!(ddl, " START WITH {}", start).unwrap();
}
if let Some(min) = self.minimum_value {
write!(ddl, " MINVALUE {}", min).unwrap();
}
if let Some(max) = self.maximum_value {
write!(ddl, " MAXVALUE {}", max).unwrap();
}
if let Some(increment) = self.increment {
write!(ddl, " INCREMENT BY {}", increment).unwrap();
}
if let Some(cycle) = self.cycle {
if cycle {
ddl.push_str(" CYCLE");
} else {
ddl.push_str(" NO CYCLE");
}
}
if let Some(cache) = self.cache {
ddl.push_str(&format!(" CACHE {}", cache));
}
if let Some(ref owner) = self.owner {
ddl.push_str(&format!(" OWNED BY {}", owner));
}
ddl.push(';');
if let Some(ref comment) = self.comment {
ddl.push_str(&format!(
"\nCOMMENT ON SEQUENCE {} IS '{}';",
self.qualified_name(),
comment
));
}
ddl
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
pub name: String,
pub schema: Option<String>,
pub columns: Vec<Column>,
pub primary_key: Option<String>,
pub constraints: Vec<Constraint>,
pub indexes: Vec<Index>,
pub rls_enabled: bool,
pub policies: Vec<Policy>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct View {
pub name: String,
pub schema: Option<String>,
pub columns: Vec<Column>,
pub ddl: Option<String>,
pub materialized: bool,
pub refresh_strategy: Option<RefreshStrategy>,
pub dependencies: Vec<String>,
pub indexes: Vec<Index>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Event {
pub name: String,
pub schema: Option<String>,
pub schedule: String,
pub command: String,
pub database: Option<String>,
pub username: Option<String>,
pub ddl: String,
pub enabled: bool,
}
impl Event {
pub fn new(
name: impl Into<String>,
schedule: impl Into<String>,
command: impl Into<String>,
) -> Self {
let name = name.into();
let schedule = schedule.into();
let command = command.into();
let ddl = format!(
"SELECT cron.schedule('{}', '{}', $${}$$)",
escape_sql_identifier(&name),
escape_sql_identifier(&schedule),
command
);
Self {
name,
schema: None,
schedule,
command,
database: None,
username: None,
ddl,
enabled: true,
}
}
pub fn with_schema(
schema: impl Into<String>,
name: impl Into<String>,
schedule: impl Into<String>,
command: impl Into<String>,
) -> Self {
let mut event = Self::new(name, schedule, command);
event.schema = Some(schema.into());
event
}
pub fn with_database(mut self, database: impl Into<String>) -> Self {
self.database = Some(database.into());
self
}
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = Some(username.into());
self
}
pub fn with_custom_ddl(mut self, ddl: impl Into<String>) -> Self {
self.ddl = ddl.into();
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn generate_ddl(&self) -> String {
if self.ddl
!= format!(
"SELECT cron.schedule('{}', '{}', $${}$$)",
escape_sql_identifier(&self.name),
escape_sql_identifier(&self.schedule),
self.command
)
{
return self.ddl.clone();
}
let mut ddl = self.ddl.clone();
if let Some(db) = &self.database {
ddl.push_str(&format!(
"\nUPDATE cron.job SET database = '{}' WHERE jobname = '{}'",
db,
escape_sql_identifier(&self.name)
));
}
if let Some(user) = &self.username {
ddl.push_str(&format!(
"\nUPDATE cron.job SET username = '{}' WHERE jobname = '{}'",
user,
escape_sql_identifier(&self.name)
));
}
ddl
}
pub fn generate_drop_ddl(&self) -> String {
format!(
"SELECT cron.unschedule('{}')",
escape_sql_identifier(&self.name)
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum RefreshStrategy {
Concurrent,
Locked,
Auto,
Manual,
}
impl Table {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
columns: Vec::new(),
primary_key: None,
constraints: Vec::new(),
indexes: Vec::new(),
rls_enabled: false,
policies: Vec::new(),
}
}
pub fn with_schema(schema: impl Into<String>, name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: Some(schema.into()),
columns: Vec::new(),
primary_key: None,
constraints: Vec::new(),
indexes: Vec::new(),
rls_enabled: false,
policies: Vec::new(),
}
}
pub fn add_column(mut self, column: Column) -> Self {
self.columns.push(column);
self
}
pub fn set_primary_key(mut self, pk_column: impl Into<String>) -> Self {
self.primary_key = Some(pk_column.into());
self
}
pub fn add_constraint(mut self, constraint: Constraint) -> Self {
self.constraints.push(constraint);
self
}
pub fn add_index(mut self, index: Index) -> Self {
self.indexes.push(index);
self
}
pub fn column(&mut self, name: &str) -> Option<&mut Column> {
self.columns.iter_mut().find(|col| col.name == name)
}
pub fn generate_ddl(&self) -> String {
let mut ddl = String::new();
let full_name = if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
};
use std::fmt::Write;
write!(ddl, "CREATE TABLE {} (\n", full_name).unwrap();
let column_defs: Vec<String> = self.columns.iter().map(|col| col.to_sql()).collect();
ddl.push_str(&column_defs.join(",\n"));
if let Some(ref pk) = self.primary_key {
write!(ddl, ",\n PRIMARY KEY (\"{}\")", pk).unwrap();
}
for constraint in &self.constraints {
ddl.push_str(&format!(",\n {}", constraint.to_sql()));
}
ddl.push_str("\n);");
for index in &self.indexes {
ddl.push_str(&format!("\n{}", index.to_sql()));
}
ddl
}
pub fn enable_rls(mut self) -> Self {
self.rls_enabled = true;
self
}
pub fn disable_rls(mut self) -> Self {
self.rls_enabled = false;
self
}
pub fn add_policy(mut self, policy: Policy) -> Self {
self.policies.push(policy);
self
}
pub fn add_policies(mut self, policies: Vec<Policy>) -> Self {
self.policies.extend(policies);
self
}
pub fn is_rls_enabled(&self) -> bool {
self.rls_enabled
}
pub fn policies(&self) -> &[Policy] {
&self.policies
}
pub fn generate_rls_ddl(&self) -> String {
let mut ddl = String::new();
if self.rls_enabled {
let full_name = if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
};
ddl.push_str(&format!(
"ALTER TABLE {} ENABLE ROW LEVEL SECURITY;\n",
full_name
));
for policy in &self.policies {
ddl.push_str(&format!("{}\n", policy.to_sql()));
}
}
ddl
}
}
impl View {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
columns: Vec::new(),
ddl: None,
materialized: false,
refresh_strategy: None,
dependencies: Vec::new(),
indexes: Vec::new(),
}
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn add_column(mut self, column: Column) -> Self {
self.columns.push(column);
self
}
pub fn with_ddl(mut self, ddl: impl Into<String>) -> Self {
self.ddl = Some(ddl.into());
self
}
pub fn set_schema(&mut self, schema: impl Into<String>) -> &mut Self {
self.schema = Some(schema.into());
self
}
pub fn add_column_mut(&mut self, column: Column) -> &mut Self {
self.columns.push(column);
self
}
pub fn set_ddl(&mut self, ddl: impl Into<String>) -> &mut Self {
self.ddl = Some(ddl.into());
self
}
pub fn set_materialized(&mut self, materialized: bool) -> &mut Self {
self.materialized = materialized;
self
}
pub fn set_refresh_strategy(&mut self, strategy: RefreshStrategy) -> &mut Self {
self.refresh_strategy = Some(strategy);
self
}
pub fn add_dependency(&mut self, dependency: impl Into<String>) -> &mut Self {
self.dependencies.push(dependency.into());
self
}
pub fn set_dependencies(&mut self, dependencies: Vec<String>) -> &mut Self {
self.dependencies = dependencies;
self
}
pub fn add_index(&mut self, name: impl Into<String>, columns: Vec<String>) -> &mut Self {
let index = Index::new(name.into(), columns, false);
self.indexes.push(index);
self
}
pub fn add_unique_index(&mut self, name: impl Into<String>, columns: Vec<String>) -> &mut Self {
let index = Index::new(name.into(), columns, true);
self.indexes.push(index);
self
}
pub fn generate_ddl(&self) -> String {
if let Some(ref ddl) = self.ddl {
ddl.clone()
} else {
let mut sql = String::new();
let full_name = if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
};
if self.materialized {
sql.push_str(&format!("CREATE MATERIALIZED VIEW {}", full_name));
} else {
sql.push_str(&format!("CREATE VIEW {}", full_name));
}
sql.push_str(" AS SELECT ");
let column_names: Vec<String> = self
.columns
.iter()
.map(|col| format!("\"{}\"", col.name))
.collect();
sql.push_str(&column_names.join(", "));
sql.push_str(" FROM /* table_name */;");
if self.materialized && !self.indexes.is_empty() {
sql.push('\n');
for index in &self.indexes {
sql.push_str(&index.to_sql());
sql.push('\n');
}
}
sql
}
}
pub fn generate_refresh_ddl(&self) -> Option<String> {
if !self.materialized {
return None;
}
let full_name = if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
};
let refresh_strategy = match self.refresh_strategy {
Some(RefreshStrategy::Concurrent) => "CONCURRENTLY",
Some(RefreshStrategy::Locked) => "",
Some(RefreshStrategy::Auto) => "CONCURRENTLY", Some(RefreshStrategy::Manual) => "",
None => "", };
Some(format!(
"REFRESH MATERIALIZED VIEW {} {};",
refresh_strategy, full_name
))
}
pub fn generate_all_ddl(&self) -> Vec<String> {
let mut statements = Vec::new();
statements.push(self.generate_ddl());
if self.materialized && !self.indexes.is_empty() {
for index in &self.indexes {
statements.push(index.to_sql());
}
}
if let Some(refresh_ddl) = self.generate_refresh_ddl() {
statements.push(refresh_ddl);
}
statements
}
}
impl IgnisObject for Table {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn schema(&self) -> Option<&str> {
self.schema.as_deref()
}
#[inline]
fn ddl(&self) -> &str {
"CREATE TABLE" }
#[inline]
fn object_type(&self) -> &str {
"table"
}
}
impl IgnisObject for View {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn schema(&self) -> Option<&str> {
self.schema.as_deref()
}
#[inline]
fn ddl(&self) -> &str {
if let Some(ref ddl) = self.ddl {
ddl
} else {
"CREATE VIEW" }
}
#[inline]
fn object_type(&self) -> &str {
"view"
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Column {
pub name: String,
pub column_type: ColumnType,
pub nullable: bool,
pub default: Option<String>,
pub unique: bool,
pub references: Option<ForeignKey>,
pub check: Option<String>,
}
impl Column {
pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
Self {
name: name.into(),
column_type,
nullable: true,
default: None,
unique: false,
references: None,
check: None,
}
}
pub fn not_null(mut self) -> Self {
self.nullable = false;
self
}
pub fn nullable(mut self) -> Self {
self.nullable = true;
self
}
pub fn unique(mut self) -> Self {
self.unique = true;
self
}
pub fn default(mut self, default: impl Into<String>) -> Self {
self.default = Some(default.into());
self
}
pub fn references(mut self, fk: ForeignKey) -> Self {
self.references = Some(fk);
self
}
#[inline]
pub fn set_not_null(&mut self) -> &mut Self {
self.nullable = false;
self
}
#[inline]
pub fn set_nullable(&mut self) -> &mut Self {
self.nullable = true;
self
}
#[inline]
pub fn set_unique(&mut self) -> &mut Self {
self.unique = true;
self
}
pub fn set_default(&mut self, default: impl Into<String>) -> &mut Self {
self.default = Some(default.into());
self
}
pub fn set_references(&mut self, fk: ForeignKey) -> &mut Self {
self.references = Some(fk);
self
}
pub fn check(self, _expression: impl Into<String>) -> Self {
self
}
pub fn to_sql(&self) -> String {
let mut sql = format!(" \"{}\" {}", self.name, self.column_type.to_sql());
if !self.nullable {
sql.push_str(" NOT NULL");
}
if let Some(ref default) = self.default {
if default.contains("nextval(")
&& self.column_type == ColumnType::Int4
&& self.name == "id"
{
sql = format!(" \"{}\" SERIAL", self.name);
if !self.nullable {
sql.push_str(" NOT NULL");
}
} else {
sql.push_str(&format!(" DEFAULT {}", default));
}
}
if self.unique {
sql.push_str(" UNIQUE");
}
if let Some(ref fk) = self.references {
sql.push_str(&format!(" REFERENCES \"{}\"(\"{}\")", fk.table, fk.column));
}
sql
}
pub fn generate_column_definition(&self) -> String {
self.to_sql()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnType {
Int2,
Int4,
Int8,
Varchar(Option<usize>),
Text,
Bool,
Uuid,
Timestamptz,
Date,
Time,
Json,
Jsonb,
Char,
Bytea,
Numeric(Option<usize>, Option<usize>),
Array(Box<ColumnType>),
Custom(String),
Serial, BigSerial, SmallSerial, }
impl Default for ColumnType {
fn default() -> Self {
ColumnType::Text
}
}
impl ColumnType {
#[inline]
pub fn to_sql(&self) -> String {
match self {
ColumnType::Int2 => "SMALLINT".to_string(),
ColumnType::Int4 => "INTEGER".to_string(),
ColumnType::Int8 => "BIGINT".to_string(),
ColumnType::Varchar(None) => "VARCHAR".to_string(),
ColumnType::Varchar(Some(length)) => format!("VARCHAR({})", length),
ColumnType::Text => "TEXT".to_string(),
ColumnType::Bool => "BOOLEAN".to_string(),
ColumnType::Uuid => "UUID".to_string(),
ColumnType::Timestamptz => "TIMESTAMPTZ".to_string(),
ColumnType::Date => "DATE".to_string(),
ColumnType::Time => "TIME".to_string(),
ColumnType::Json => "JSON".to_string(),
ColumnType::Jsonb => "JSONB".to_string(),
ColumnType::Char => "CHAR".to_string(),
ColumnType::Bytea => "BYTEA".to_string(),
ColumnType::Numeric(None, None) => "NUMERIC".to_string(),
ColumnType::Numeric(Some(precision), None) => format!("NUMERIC({})", precision),
ColumnType::Numeric(Some(precision), Some(scale)) => {
format!("NUMERIC({},{})", precision, scale)
}
ColumnType::Numeric(None, Some(scale)) => format!("NUMERIC(38,{})", scale), ColumnType::Array(element_type) => format!("{}[]", element_type.to_sql()),
ColumnType::Custom(custom_type) => custom_type.clone(),
ColumnType::Serial => "SERIAL".to_string(),
ColumnType::BigSerial => "BIGSERIAL".to_string(),
ColumnType::SmallSerial => "SMALLSERIAL".to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ForeignKey {
pub table: String,
pub column: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Constraint {
pub name: String,
pub constraint_type: ConstraintType,
}
impl Constraint {
pub fn to_sql(&self) -> String {
match &self.constraint_type {
ConstraintType::Check(expression) => {
format!("CONSTRAINT \"{}\" CHECK ({})", self.name, expression)
}
ConstraintType::Unique(columns) => {
let cols: Vec<String> = columns.iter().map(|c| format!("\"{}\"", c)).collect();
format!("CONSTRAINT \"{}\" UNIQUE ({})", self.name, cols.join(", "))
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConstraintType {
Check(String),
Unique(Vec<String>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Index {
pub name: String,
pub columns: Vec<String>,
pub unique: bool,
}
impl Index {
pub fn new(name: impl Into<String>, columns: Vec<String>, unique: bool) -> Self {
Self {
name: name.into(),
columns,
unique,
}
}
pub fn to_sql(&self) -> String {
let unique = if self.unique { "UNIQUE " } else { "" };
let cols: Vec<String> = self.columns.iter().map(|c| format!("\"{}\"", c)).collect();
format!(
"CREATE {}INDEX \"{}\" ON \"{}\" ({});",
unique,
self.name,
"table_name",
cols.join(", ")
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct IndexMeta {
pub name: &'static str,
pub table: &'static str,
pub schema: Option<&'static str>,
pub unique: bool,
pub concurrent: bool,
pub index_type: IndexType,
pub columns: &'static [&'static str],
}
impl IndexMeta {
pub fn ddl(&self) -> String {
let mut ddl = String::new();
ddl.push_str("CREATE ");
if self.unique {
ddl.push_str("UNIQUE ");
}
if self.concurrent {
ddl.push_str("CONCURRENTLY ");
}
ddl.push_str("INDEX ");
let index_name = if let Some(schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
};
ddl.push_str(&index_name);
ddl.push_str(" ON ");
let table_name = if let Some(schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.table)
} else {
format!("\"{}\"", self.table)
};
ddl.push_str(&table_name);
match self.index_type {
IndexType::BTree => {} IndexType::GIN => ddl.push_str(" USING GIN"),
IndexType::GIST => ddl.push_str(" USING GIST"),
IndexType::BRIN => ddl.push_str(" USING BRIN"),
IndexType::Hash => ddl.push_str(" USING HASH"),
IndexType::SPGIST => ddl.push_str(" USING SPGIST"),
}
ddl.push_str(" (");
for (i, column) in self.columns.iter().enumerate() {
if i > 0 {
ddl.push_str(", ");
}
ddl.push_str(&format!("\"{}\"", column));
}
ddl.push_str(")");
ddl.push_str(";");
ddl
}
pub fn generate_ddl(&self) -> String {
self.ddl()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum IndexType {
BTree,
GIN,
GIST,
BRIN,
Hash,
SPGIST,
}
impl Default for IndexType {
fn default() -> Self {
IndexType::BTree
}
}
impl std::fmt::Display for IndexType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IndexType::BTree => write!(f, "BTree"),
IndexType::GIN => write!(f, "GIN"),
IndexType::GIST => write!(f, "GIST"),
IndexType::BRIN => write!(f, "BRIN"),
IndexType::Hash => write!(f, "Hash"),
IndexType::SPGIST => write!(f, "SPGIST"),
}
}
}
impl From<&str> for ColumnType {
fn from(type_str: &str) -> Self {
match type_str.to_uppercase().as_str() {
"INT4" | "INTEGER" | "INT" => ColumnType::Int4,
"INT8" | "BIGINT" => ColumnType::Int8,
"TEXT" => ColumnType::Text,
"VARCHAR" => ColumnType::Varchar(None),
"BOOLEAN" | "BOOL" => ColumnType::Bool,
"UUID" => ColumnType::Uuid,
"TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" => ColumnType::Timestamptz,
"NUMERIC" | "DECIMAL" => ColumnType::Numeric(None, None),
"JSONB" => ColumnType::Jsonb,
"SERIAL" => ColumnType::Serial,
"BIGSERIAL" => ColumnType::BigSerial,
"SMALLSERIAL" => ColumnType::SmallSerial,
_ => ColumnType::Text, }
}
}
#[derive(Debug, Clone)]
pub struct TableMeta {
pub name: &'static str,
pub schema: Option<&'static str>,
pub primary_key: &'static str,
pub columns: &'static [(&'static str, ColumnType)],
}
impl TableMeta {
pub const fn new(
name: &'static str,
schema: Option<&'static str>,
primary_key: &'static str,
columns: &'static [(&'static str, ColumnType)],
) -> Self {
Self {
name,
schema,
primary_key,
columns,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Role {
pub name: String,
pub password: Option<String>,
pub superuser: bool,
pub createdb: bool,
pub createrole: bool,
pub inherit: bool,
pub login: bool,
pub replication: bool,
pub connection_limit: Option<i32>,
pub valid_until: Option<String>,
pub member_of: Vec<String>,
pub members: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Grant {
pub privilege: Privilege,
pub target: GrantTarget,
pub grantee: String,
pub grantor: Option<String>,
pub with_grant_option: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Privilege {
Select,
Insert,
Update,
Delete,
References,
Trigger,
Connect,
Create,
Temporary,
Usage,
CreateInSchema,
Execute,
All,
Custom(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum GrantTarget {
Table {
table: String,
schema: Option<String>,
},
Schema(String),
Database(String),
Function {
function: String,
schema: Option<String>,
},
AllTablesInSchema(String),
AllFunctionsInSchema(String),
Role(String),
}
impl Role {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
password: None,
superuser: false,
createdb: false,
createrole: false,
inherit: true,
login: false,
replication: false,
connection_limit: None,
valid_until: None,
member_of: Vec::new(),
members: Vec::new(),
}
}
pub fn with_password(mut self, password: impl Into<String>) -> Self {
self.password = Some(password.into());
self
}
pub fn with_superuser(mut self, superuser: bool) -> Self {
self.superuser = superuser;
self
}
pub fn with_createdb(mut self, createdb: bool) -> Self {
self.createdb = createdb;
self
}
pub fn with_createrole(mut self, createrole: bool) -> Self {
self.createrole = createrole;
self
}
pub fn with_inherit(mut self, inherit: bool) -> Self {
self.inherit = inherit;
self
}
pub fn with_login(mut self, login: bool) -> Self {
self.login = login;
self
}
pub fn with_replication(mut self, replication: bool) -> Self {
self.replication = replication;
self
}
pub fn with_connection_limit(mut self, limit: i32) -> Self {
self.connection_limit = Some(limit);
self
}
pub fn with_valid_until(mut self, until: impl Into<String>) -> Self {
self.valid_until = Some(until.into());
self
}
pub fn with_member_of(mut self, roles: Vec<String>) -> Self {
self.member_of = roles;
self
}
pub fn with_members(mut self, members: Vec<String>) -> Self {
self.members = members;
self
}
pub fn generate_create_ddl(&self) -> String {
let mut ddl = format!("CREATE ROLE \"{}\"", self.name);
if self.login {
ddl.push_str(" LOGIN");
} else {
ddl.push_str(" NOLOGIN");
}
if self.superuser {
ddl.push_str(" SUPERUSER");
} else {
ddl.push_str(" NOSUPERUSER");
}
if self.createdb {
ddl.push_str(" CREATEDB");
} else {
ddl.push_str(" NOCREATEDB");
}
if self.createrole {
ddl.push_str(" CREATEROLE");
} else {
ddl.push_str(" NOCREATEROLE");
}
if self.inherit {
ddl.push_str(" INHERIT");
} else {
ddl.push_str(" NOINHERIT");
}
if self.replication {
ddl.push_str(" REPLICATION");
} else {
ddl.push_str(" NOREPLICATION");
}
if let Some(limit) = self.connection_limit {
ddl.push_str(&format!(" CONNECTION LIMIT {}", limit));
}
if let Some(ref password) = self.password {
ddl.push_str(&format!(" PASSWORD '{}'", password));
}
if let Some(ref until) = self.valid_until {
ddl.push_str(&format!(" VALID UNTIL '{}'", until));
}
ddl.push(';');
for parent in &self.member_of {
ddl.push_str(&format!("\nGRANT \"{}\" TO \"{}\";", parent, self.name));
}
for member in &self.members {
ddl.push_str(&format!("\nGRANT \"{}\" TO \"{}\";", self.name, member));
}
ddl
}
pub fn generate_alter_ddl(&self, old_role: &Role) -> String {
let mut ddl = String::new();
if self.login != old_role.login {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.login { "LOGIN" } else { "NOLOGIN" }
));
}
if self.superuser != old_role.superuser {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.superuser {
"SUPERUSER"
} else {
"NOSUPERUSER"
}
));
}
if self.createdb != old_role.createdb {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.createdb {
"CREATEDB"
} else {
"NOCREATEDB"
}
));
}
if self.createrole != old_role.createrole {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.createrole {
"CREATEROLE"
} else {
"NOCREATEROLE"
}
));
}
if self.inherit != old_role.inherit {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.inherit { "INHERIT" } else { "NOINHERIT" }
));
}
if self.replication != old_role.replication {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" {};\n",
self.name,
if self.replication {
"REPLICATION"
} else {
"NOREPLICATION"
}
));
}
if self.connection_limit != old_role.connection_limit {
if let Some(limit) = self.connection_limit {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
self.name, limit
));
} else {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT -1;\n",
self.name
));
}
}
if self.password != old_role.password {
if let Some(ref password) = self.password {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" PASSWORD '{}';\n",
self.name, password
));
}
}
if self.valid_until != old_role.valid_until {
if let Some(ref until) = self.valid_until {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
self.name, until
));
} else {
ddl.push_str(&format!(
"ALTER ROLE \"{}\" VALID UNTIL 'infinity';\n",
self.name
));
}
}
let old_member_of: std::collections::HashSet<_> = old_role.member_of.iter().collect();
let new_member_of: std::collections::HashSet<_> = self.member_of.iter().collect();
for parent in &self.member_of {
if !old_member_of.contains(parent) {
ddl.push_str(&format!("GRANT \"{}\" TO \"{}\";\n", parent, self.name));
}
}
for parent in &old_role.member_of {
if !new_member_of.contains(parent) {
ddl.push_str(&format!("REVOKE \"{}\" FROM \"{}\";\n", parent, self.name));
}
}
let old_members: std::collections::HashSet<_> = old_role.members.iter().collect();
let new_members: std::collections::HashSet<_> = self.members.iter().collect();
for member in &self.members {
if !old_members.contains(member) {
ddl.push_str(&format!("GRANT \"{}\" TO \"{}\";\n", self.name, member));
}
}
for member in &old_role.members {
if !new_members.contains(member) {
ddl.push_str(&format!("REVOKE \"{}\" FROM \"{}\";\n", self.name, member));
}
}
ddl
}
pub fn generate_drop_ddl(&self) -> String {
format!("DROP ROLE IF EXISTS \"{}\";", self.name)
}
}
impl Grant {
pub fn new(privilege: Privilege, target: GrantTarget, grantee: impl Into<String>) -> Self {
Self {
privilege,
target,
grantee: grantee.into(),
grantor: None,
with_grant_option: false,
}
}
pub fn with_grantor(mut self, grantor: impl Into<String>) -> Self {
self.grantor = Some(grantor.into());
self
}
pub fn with_grant_option(mut self, with_grant_option: bool) -> Self {
self.with_grant_option = with_grant_option;
self
}
pub fn privilege_name(&self) -> String {
match &self.privilege {
Privilege::Select => "SELECT".to_string(),
Privilege::Insert => "INSERT".to_string(),
Privilege::Update => "UPDATE".to_string(),
Privilege::Delete => "DELETE".to_string(),
Privilege::References => "REFERENCES".to_string(),
Privilege::Trigger => "TRIGGER".to_string(),
Privilege::Connect => "CONNECT".to_string(),
Privilege::Create => "CREATE".to_string(),
Privilege::Temporary => "TEMPORARY".to_string(),
Privilege::Usage => "USAGE".to_string(),
Privilege::CreateInSchema => "CREATE".to_string(),
Privilege::Execute => "EXECUTE".to_string(),
Privilege::All => "ALL".to_string(),
Privilege::Custom(s) => s.clone(),
}
}
pub fn generate_name(&self) -> String {
let target_str = match &self.target {
GrantTarget::Table { table, schema } => {
if let Some(schema) = schema {
format!("{}_{}", schema, table)
} else {
table.clone()
}
}
GrantTarget::Schema(schema) => format!("schema_{}", schema),
GrantTarget::Database(db) => format!("database_{}", db),
GrantTarget::Function { function, schema } => {
if let Some(schema) = schema {
format!("{}_{}_function", schema, function)
} else {
format!("{}_function", function)
}
}
GrantTarget::AllTablesInSchema(schema) => format!("all_tables_in_{}", schema),
GrantTarget::AllFunctionsInSchema(schema) => format!("all_functions_in_{}", schema),
GrantTarget::Role(role) => format!("role_{}", role),
};
format!(
"{}_{}_to_{}",
self.privilege_name().to_lowercase(),
target_str,
self.grantee
)
}
pub fn generate_grant_ddl(&self) -> String {
let privilege_str = self.privilege_name();
let target_str = match &self.target {
GrantTarget::Table { table, schema } => {
if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, table)
} else {
format!("\"{}\"", table)
}
}
GrantTarget::Schema(schema) => format!("SCHEMA \"{}\"", schema),
GrantTarget::Database(db) => format!("DATABASE \"{}\"", db),
GrantTarget::Function { function, schema } => {
if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, function)
} else {
format!("\"{}\"", function)
}
}
GrantTarget::AllTablesInSchema(schema) => {
format!("ALL TABLES IN SCHEMA \"{}\"", schema)
}
GrantTarget::AllFunctionsInSchema(schema) => {
format!("ALL FUNCTIONS IN SCHEMA \"{}\"", schema)
}
GrantTarget::Role(role) => format!("\"{}\"", role),
};
let mut ddl = format!(
"GRANT {} ON {} TO \"{}\"",
privilege_str, target_str, self.grantee
);
if self.with_grant_option {
ddl.push_str(" WITH GRANT OPTION");
}
ddl.push(';');
ddl
}
pub fn generate_revoke_ddl(&self) -> String {
let privilege_str = self.privilege_name();
let target_str = match &self.target {
GrantTarget::Table { table, schema } => {
if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, table)
} else {
format!("\"{}\"", table)
}
}
GrantTarget::Schema(schema) => format!("SCHEMA \"{}\"", schema),
GrantTarget::Database(db) => format!("DATABASE \"{}\"", db),
GrantTarget::Function { function, schema } => {
if let Some(schema) = schema {
format!("\"{}\".\"{}\"", schema, function)
} else {
format!("\"{}\"", function)
}
}
GrantTarget::AllTablesInSchema(schema) => {
format!("ALL TABLES IN SCHEMA \"{}\"", schema)
}
GrantTarget::AllFunctionsInSchema(schema) => {
format!("ALL FUNCTIONS IN SCHEMA \"{}\"", schema)
}
GrantTarget::Role(role) => format!("\"{}\"", role),
};
let mut ddl = format!(
"REVOKE {} ON {} FROM \"{}\"",
privilege_str, target_str, self.grantee
);
if self.with_grant_option {
ddl.push_str(" CASCADE");
}
ddl.push(';');
ddl
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Policy {
pub name: String,
pub table: String,
pub schema: Option<String>,
pub command: PolicyCommand,
pub role: Option<String>,
pub expression: String,
pub check_expression: Option<String>,
pub permissive: bool, }
#[derive(Debug, Clone, PartialEq)]
pub enum PolicyCommand {
All,
Select,
Insert,
Update,
Delete,
}
impl Policy {
pub fn new(
name: impl Into<String>,
table: impl Into<String>,
command: PolicyCommand,
expression: impl Into<String>,
) -> Self {
Self {
name: name.into(),
table: table.into(),
schema: None,
command,
role: None,
expression: expression.into(),
check_expression: None,
permissive: true, }
}
pub fn schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn role(mut self, role: impl Into<String>) -> Self {
self.role = Some(role.into());
self
}
pub fn with_check(mut self, expression: impl Into<String>) -> Self {
self.check_expression = Some(expression.into());
self
}
pub fn restrictive(mut self) -> Self {
self.permissive = false;
self
}
pub fn permissive(mut self) -> Self {
self.permissive = true;
self
}
pub fn to_sql(&self) -> String {
let table_name = if let Some(ref schema) = self.schema {
format!("{}.{}", schema, self.table)
} else if self.table.contains('.') {
self.table.clone()
} else {
format!("\"{}\"", self.table)
};
let mut sql = format!("CREATE POLICY \"{}\" ON {}", self.name, table_name);
match self.command {
PolicyCommand::All => sql.push_str(" FOR ALL"),
PolicyCommand::Select => sql.push_str(" FOR SELECT"),
PolicyCommand::Insert => sql.push_str(" FOR INSERT"),
PolicyCommand::Update => sql.push_str(" FOR UPDATE"),
PolicyCommand::Delete => sql.push_str(" FOR DELETE"),
}
if let Some(role) = &self.role {
sql.push_str(&format!(" TO \"{}\"", role));
}
sql.push_str(&format!(" USING ({})", self.expression));
if let Some(check) = &self.check_expression {
sql.push_str(&format!(" WITH CHECK ({})", check));
}
sql.push(';');
sql
}
pub fn to_drop_sql(&self) -> String {
format!(
"DROP POLICY IF EXISTS \"{}\" ON \"{}\";",
self.name, self.table
)
}
}
impl PolicyCommand {
pub fn to_sql(&self) -> &'static str {
match self {
PolicyCommand::All => "ALL",
PolicyCommand::Select => "SELECT",
PolicyCommand::Insert => "INSERT",
PolicyCommand::Update => "UPDATE",
PolicyCommand::Delete => "DELETE",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Extension {
pub name: String,
pub schema: Option<String>,
pub version: Option<String>,
pub cascade: bool,
pub if_not_exists: bool,
}
impl Extension {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
version: None,
cascade: false,
if_not_exists: false,
}
}
pub fn schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub fn cascade(mut self) -> Self {
self.cascade = true;
self
}
pub fn if_not_exists(mut self) -> Self {
self.if_not_exists = true;
self
}
pub fn to_sql(&self) -> String {
let mut sql = "CREATE EXTENSION".to_string();
if self.if_not_exists {
sql.push_str(" IF NOT EXISTS");
}
sql.push_str(&format!(" \"{}\"", self.name));
if let Some(schema) = &self.schema {
sql.push_str(&format!(" WITH SCHEMA \"{}\"", schema));
}
if let Some(version) = &self.version {
sql.push_str(&format!(" VERSION \"{}\"", version));
}
if self.cascade {
sql.push_str(" CASCADE");
}
sql.push(';');
sql
}
pub fn to_drop_sql(&self) -> String {
let mut sql = format!("DROP EXTENSION IF EXISTS \"{}\"", self.name);
if self.cascade {
sql.push_str(" CASCADE");
}
sql.push(';');
sql
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GucSetting {
pub name: String,
pub value: String,
pub context: GucContext,
pub description: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum GucContext {
System,
Database,
User,
Session,
Transaction,
}
impl GucSetting {
pub fn new(name: impl Into<String>, value: impl Into<String>, context: GucContext) -> Self {
Self {
name: name.into(),
value: value.into(),
context,
description: None,
}
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn to_sql(&self) -> String {
match self.context {
GucContext::System => {
format!("ALTER SYSTEM SET {} = '{}';", self.name, self.value)
}
GucContext::Database => {
format!(
"ALTER DATABASE current_database() SET {} = '{}';",
self.name, self.value
)
}
GucContext::User => {
format!(
"ALTER USER current_user() SET {} = '{}';",
self.name, self.value
)
}
GucContext::Session => {
format!("SET {} = '{}';", self.name, self.value)
}
GucContext::Transaction => {
format!("SET LOCAL {} = '{}';", self.name, self.value)
}
}
}
pub fn to_reset_sql(&self) -> String {
match self.context {
GucContext::System => {
format!("ALTER SYSTEM RESET {};", self.name)
}
GucContext::Database => {
format!("ALTER DATABASE current_database() RESET {};", self.name)
}
GucContext::User => {
format!("ALTER USER current_user() RESET {};", self.name)
}
GucContext::Session => {
format!("RESET {};", self.name)
}
GucContext::Transaction => {
format!("RESET LOCAL {};", self.name)
}
}
}
pub fn get_value_sql(&self) -> String {
format!("SELECT current_setting('{}');", self.name)
}
}
impl GucContext {
pub fn to_sql(&self) -> &'static str {
match self {
GucContext::System => "SYSTEM",
GucContext::Database => "DATABASE",
GucContext::User => "USER",
GucContext::Session => "SESSION",
GucContext::Transaction => "LOCAL",
}
}
}
pub use crate::{RegisteredObject, SchemaObject};