pub mod composite;
pub mod procedure;
#[macro_export]
macro_rules! impl_ignis_model {
($struct_name:ident, $table:expr, $pk:expr) => {
impl ::ignis_db::IgnisModel for $struct_name {
const TABLE: &'static str = $table;
const PK: &'static str = $pk;
const SCHEMA: Option<&'static str> = None;
const FULL_TABLE_NAME: &'static str = $table;
fn get_primary_key_value(&self) -> anyhow::Result<::ignis_db::BindValue> {
Err(anyhow::anyhow!(
"get_primary_key_value must be implemented for {}",
stringify!($struct_name)
))
}
}
};
($struct_name:ident, $table:expr, $pk:expr, $schema:expr) => {
impl ::ignis_db::IgnisModel for $struct_name {
const TABLE: &'static str = $table;
const PK: &'static str = $pk;
const SCHEMA: Option<&'static str> = Some($schema);
const FULL_TABLE_NAME: &'static str = concat!($schema, ".", $table);
fn get_primary_key_value(&self) -> anyhow::Result<::ignis_db::BindValue> {
Err(anyhow::anyhow!(
"get_primary_key_value must be implemented for {}",
stringify!($struct_name)
))
}
}
};
}
#[macro_export]
macro_rules! impl_insertable {
($struct_name:ident) => {
impl ::ignis_db::Insertable for $struct_name {
fn insert<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
async move {
use $crate::macros::parameter_binding::{SafeInsertBuilder, BindValue};
let mut builder = SafeInsertBuilder::new(Self::FULL_TABLE_NAME)
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
let builder = $crate::impl_insertable!(@add_fields self, builder);
builder.execute(executor).await
}
}
}
};
(@add_fields $self:expr, $builder:expr) => {
$builder
};
}
#[macro_export]
macro_rules! impl_updatable {
($struct_name:ident) => {
impl ::ignis_db::Updatable for $struct_name {
fn update<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
async move {
use $crate::macros::parameter_binding::{SafeUpdateBuilder, BindValue};
let mut builder = SafeUpdateBuilder::new(Self::FULL_TABLE_NAME)
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
let builder = $crate::impl_updatable!(@add_set_fields self, builder);
let pk_value = self.get_primary_key_value()
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
let pk_bind_value = $crate::impl_updatable!(@convert_to_bind_value pk_value);
let builder = builder.r#where(Self::PK, pk_bind_value)
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
builder.execute(executor).await
}
}
}
};
(@add_set_fields $self:expr, $builder:expr) => {
$builder
};
(@convert_to_bind_value $value:expr) => {
match $value {
$crate::BindValue::Int4(v) => $crate::macros::parameter_binding::BindValue::Int4(v),
$crate::BindValue::Int8(v) => $crate::macros::parameter_binding::BindValue::Int8(v),
$crate::BindValue::Text(v) => $crate::macros::parameter_binding::BindValue::Text(v),
$crate::BindValue::Bool(v) => $crate::macros::parameter_binding::BindValue::Bool(v),
$crate::BindValue::Uuid(v) => $crate::macros::parameter_binding::BindValue::Uuid(v),
$crate::BindValue::Timestamptz(v) => $crate::macros::parameter_binding::BindValue::Timestamptz(v),
$crate::BindValue::Numeric(v) => $crate::macros::parameter_binding::BindValue::Numeric(v),
$crate::BindValue::Jsonb(v) => $crate::macros::parameter_binding::BindValue::Jsonb(v),
$crate::BindValue::Composite(v) => $crate::macros::parameter_binding::BindValue::Composite(v),
$crate::BindValue::Array(v) => $crate::macros::parameter_binding::BindValue::Array(v),
$crate::BindValue::Null => $crate::macros::parameter_binding::BindValue::Null,
}
};
}
#[macro_export]
macro_rules! impl_deletable {
($struct_name:ident) => {
impl ::ignis_db::Deletable for $struct_name {
fn delete<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
async move {
use $crate::macros::parameter_binding::{SafeDeleteBuilder, BindValue};
let mut builder = SafeDeleteBuilder::new(Self::FULL_TABLE_NAME)
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
let pk_value = self.get_primary_key_value()
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
let pk_bind_value = $crate::impl_deletable!(@convert_to_bind_value pk_value);
builder = builder.r#where(Self::PK, pk_bind_value)
.map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
builder.execute(executor).await
}
}
}
};
(@convert_to_bind_value $value:expr) => {
match $value {
$crate::BindValue::Int4(v) => $crate::macros::parameter_binding::BindValue::Int4(v),
$crate::BindValue::Int8(v) => $crate::macros::parameter_binding::BindValue::Int8(v),
$crate::BindValue::Text(v) => $crate::macros::parameter_binding::BindValue::Text(v),
$crate::BindValue::Bool(v) => $crate::macros::parameter_binding::BindValue::Bool(v),
$crate::BindValue::Uuid(v) => $crate::macros::parameter_binding::BindValue::Uuid(v),
$crate::BindValue::Timestamptz(v) => $crate::macros::parameter_binding::BindValue::Timestamptz(v),
$crate::BindValue::Numeric(v) => $crate::macros::parameter_binding::BindValue::Numeric(v),
$crate::BindValue::Jsonb(v) => $crate::macros::parameter_binding::BindValue::Jsonb(v),
$crate::BindValue::Composite(v) => $crate::macros::parameter_binding::BindValue::Composite(v),
$crate::BindValue::Array(v) => $crate::macros::parameter_binding::BindValue::Array(v),
$crate::BindValue::Null => $crate::macros::parameter_binding::BindValue::Null,
}
};
}
#[macro_export]
macro_rules! table {
(
$table_name:ident ($first_pk:ident, $($rest_pk:ident),+ $(,)?) {
$($col_name:ident -> $col_type:tt),* $(,)?
}
) => {
pub mod $table_name {
use $crate::schema::{Table, Column, ColumnType, TableMeta};
pub fn table() -> Table {
let mut table = Table::new(stringify!($table_name));
$(
table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
)*
let pk_columns = vec![stringify!($first_pk).to_string(), $(stringify!($rest_pk).to_string()),+];
table = table.set_primary_key(&pk_columns.join(", "));
table
}
pub fn pk() -> Vec<String> {
vec![stringify!($first_pk).to_string(), $(stringify!($rest_pk).to_string()),+]
}
$(
pub fn $col_name() -> $crate::dsl::Column<$crate::table!(@rust_type $col_type)> {
$crate::dsl::Column::new(stringify!($col_name))
.from_table(stringify!($table_name))
}
)*
pub fn meta() -> TableMeta {
TableMeta::new(
stringify!($table_name),
None,
$crate::table!(@pk_string $first_pk, $($rest_pk),+),
&[
$(
(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)),
)*
],
)
}
pub fn configure<F>(mutator: F) -> Table
where
F: FnOnce(&mut Table) -> &mut Table,
{
let mut table = table();
mutator(&mut table);
table
}
pub struct Columns;
impl Columns {
$(
pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::table!(@rust_type $col_type)> {
$crate::dsl::TypedColumn::new(
Column::new(stringify!($col_name).to_string(), $crate::table!(@resolve_column_type $col_type)),
stringify!($table_name).to_string(),
None
)
}
)*
}
pub fn typed_query() -> $crate::dsl::TypedQuery {
$crate::dsl::TypedQuery::new().from_table(table())
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "table",
name: stringify!($table_name),
ddl: concat!("CREATE TABLE \"", stringify!($table_name), "\" (", $crate::table!(@ddl_columns $($col_name -> $col_type),*), ", PRIMARY KEY (", $crate::table!(@pk_columns $first_pk, $($rest_pk),+), "));"),
schema: None,
})
}
};
(
$table_name:ident ($pk:ident) {
$($col_name:ident -> $col_type:tt),* $(,)?
}
) => {
pub mod $table_name {
use $crate::schema::{Table, Column, ColumnType, TableMeta};
pub fn table() -> Table {
let mut table = Table::new(stringify!($table_name));
$(
table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
)*
table = table.set_primary_key(stringify!($pk));
table
}
pub fn pk() -> $crate::dsl::Column<i32> {
$crate::dsl::Column::new(stringify!($pk))
.from_table(stringify!($table_name))
}
$(
pub fn $col_name() -> $crate::dsl::Column<$crate::table!(@rust_type $col_type)> {
$crate::dsl::Column::new(stringify!($col_name))
.from_table(stringify!($table_name))
}
)*
pub fn meta() -> TableMeta {
TableMeta::new(
stringify!($table_name),
None,
stringify!($pk),
&[
$(
(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)),
)*
],
)
}
pub fn configure<F>(mutator: F) -> Table
where
F: FnOnce(&mut Table) -> &mut Table,
{
let mut table = table();
mutator(&mut table);
table
}
pub struct Columns;
impl Columns {
$(
pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::table!(@rust_type $col_type)> {
$crate::dsl::TypedColumn::new(
Column::new(stringify!($col_name).to_string(), $crate::table!(@resolve_column_type $col_type)),
stringify!($table_name).to_string(),
None
)
}
)*
}
pub fn typed_query() -> $crate::dsl::TypedQuery {
$crate::dsl::TypedQuery::new().from_table(table())
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "table",
name: stringify!($table_name),
ddl: concat!("CREATE TABLE \"", stringify!($table_name), "\" (", $crate::table!(@ddl_columns $($col_name -> $col_type),*), ", PRIMARY KEY (\"", stringify!($pk), "\"));"),
schema: None,
})
}
};
(@resolve_column_type $type:ident) => { $crate::column_type_mapping!($type) };
(@resolve_column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
(@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
(@column_type $type:ident) => { $crate::column_type_mapping!($type) };
(@column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
(@rust_type $type:ident) => { $crate::rust_type_mapping!($type) };
(@rust_type Custom($rust_type:ty, $type_name:expr)) => { $crate::rust_type_mapping!(Custom($rust_type)) };
(@ddl_columns $first_col:ident -> Custom($rust_type:ty, $type_name:expr)) => {
concat!("\"", stringify!($first_col), "\" ", $crate::table!(@sql_type Custom($rust_type, $type_name)))
};
(@ddl_columns $first_col:ident -> $first_type:ident) => {
concat!("\"", stringify!($first_col), "\" ", $crate::table!(@sql_type $first_type))
};
(@ddl_columns $first_col:ident -> $first_type:ident, $($rest_col:ident -> $rest_type:tt),*) => {
concat!(
"\"", stringify!($first_col), "\" ", $crate::table!(@sql_type $first_type), ", ",
$crate::table!(@ddl_columns $($rest_col -> $rest_type),*)
)
};
(@ddl_columns $first_col:ident -> Custom($rust_type:ty, $type_name:expr), $($rest_col:ident -> $rest_type:tt),*) => {
concat!(
"\"", stringify!($first_col), "\" ", $crate::table!(@sql_type Custom($rust_type, $type_name)), ", ",
$crate::table!(@ddl_columns $($rest_col -> $rest_type),*)
)
};
(@sql_type $type:ident) => { $crate::sql_type_mapping!($type) };
(@sql_type Custom($rust_type:ty, $type_name:expr)) => {
$crate::sql_type_mapping!(Custom($type_name))
};
(@pk_columns $first_pk:ident) => {
concat!("\"", stringify!($first_pk), "\"")
};
(@pk_columns $first_pk:ident, $($rest_pk:ident),+) => {
concat!(
"\"", stringify!($first_pk), "\", ",
$crate::table!(@pk_columns $($rest_pk),+)
)
};
(@pk_string $first_pk:ident) => {
stringify!($first_pk)
};
(@pk_string $first_pk:ident, $($rest_pk:ident),+) => {
concat!(
stringify!($first_pk), ", ",
$crate::table!(@pk_string $($rest_pk),+)
)
};
}
#[macro_export]
macro_rules! view {
(
$view_name:ident ($pk:ident) {
$($col_name:ident -> $col_type:tt),* $(,)?
}
) => {
pub mod $view_name {
use $crate::schema::{View, Column, ColumnType};
pub fn view() -> View {
let mut view = View::new(stringify!($view_name));
$(
view = view.add_column(Column::new(stringify!($col_name), $crate::view!(@column_type $col_type)));
)*
view
}
pub fn pk() -> $crate::dsl::Column<i32> {
$crate::dsl::Column::new(stringify!($pk))
.from_table(stringify!($view_name))
}
$(
pub fn $col_name() -> $crate::dsl::Column<$crate::view!(@rust_type $col_type)> {
$crate::dsl::Column::new(stringify!($col_name))
.from_table(stringify!($view_name))
}
)*
pub fn configure<F>(mutator: F) -> View
where
F: FnOnce(&mut View) -> &mut View,
{
let mut view = view();
mutator(&mut view);
view
}
pub fn materialized<F>(mutator: F) -> View
where
F: FnOnce(&mut View) -> &mut View,
{
let mut view = view();
view.set_materialized(true);
mutator(&mut view);
view
}
pub struct Columns;
impl Columns {
$(
pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::view!(@rust_type $col_type)> {
$crate::dsl::TypedColumn::new(
Column::new(stringify!($col_name).to_string(), $crate::view!(@column_type $col_type)),
stringify!($view_name).to_string(),
None
)
}
)*
}
pub fn typed_query() -> $crate::dsl::TypedQuery {
$crate::dsl::TypedQuery::new().from_view(view())
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "view",
name: stringify!($view_name),
ddl: concat!("CREATE VIEW \"", stringify!($view_name), "\" AS SELECT ", $crate::view!(@ddl_columns $($col_name -> $col_type),*), " FROM /* table_name */;"),
schema: None,
})
}
};
(@resolve_column_type $type:ident) => { $crate::column_type_mapping!($type) };
(@resolve_column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
(@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
(@column_type $type:ident) => { $crate::column_type_mapping!($type) };
(@column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
(@rust_type $type:ident) => { $crate::rust_type_mapping!($type) };
(@rust_type Custom($rust_type:ty, $type_name:expr)) => { $crate::rust_type_mapping!(Custom($rust_type)) };
(@ddl_columns $first_col:ident -> $first_type:ident) => {
concat!("\"", stringify!($first_col), "\"")
};
(@ddl_columns $first_col:ident -> $first_type:ident, $($rest_col:ident -> $rest_type:ident),*) => {
concat!(
"\"", stringify!($first_col), "\", ",
$crate::view!(@ddl_columns $($rest_col -> $rest_type),*)
)
};
}
#[macro_export]
macro_rules! index {
(
$index_name:ident ($table_name:ident, $($col_name:ident),* $(,)?)
) => {
pub mod $index_name {
use $crate::schema::{IndexMeta, IndexType};
pub fn meta() -> IndexMeta {
IndexMeta {
name: stringify!($index_name),
table: stringify!($table_name),
schema: None,
unique: false,
concurrent: false,
index_type: IndexType::BTree,
columns: &[$(stringify!($col_name)),*],
}
}
pub fn name() -> &'static str {
stringify!($index_name)
}
pub fn table() -> &'static str {
stringify!($table_name)
}
pub fn columns() -> &'static [&'static str] {
&[$(stringify!($col_name)),*]
}
pub fn composite_fields() -> Vec<&'static str> {
vec![]
}
pub fn expression() -> Option<&'static str> {
None
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "index",
name: stringify!($index_name),
ddl: concat!("CREATE INDEX \"", stringify!($index_name), "\" ON \"", stringify!($table_name), "\" (", $crate::index!(@columns $($col_name),*), ");"),
schema: None,
})
}
};
(
$index_name:ident ($table_name:ident, [$($col_spec:tt),* $(,)?]) {
$(unique: $unique:ident,)?
$(concurrent: $concurrent:ident,)?
$(index_type: $index_type:ident,)?
$(composite_fields: [$($composite_field:expr),* $(,)?],)?
$(where_clause: $where_clause:expr,)?
}
) => {
pub mod $index_name {
use $crate::schema::{IndexMeta, IndexType};
pub fn meta() -> IndexMeta {
IndexMeta {
name: stringify!($index_name),
table: stringify!($table_name),
schema: None,
unique: $crate::index!(@bool_value $($unique)?),
concurrent: $crate::index!(@bool_value $($concurrent)?),
index_type: $crate::index!(@index_type $($index_type)?),
columns: &[$crate::index!(@extract_columns $($col_spec),*)],
}
}
pub fn name() -> &'static str {
stringify!($index_name)
}
pub fn table() -> &'static str {
stringify!($table_name)
}
pub fn columns() -> &'static [&'static str] {
&[$crate::index!(@extract_columns $($col_spec),*)]
}
pub fn composite_fields() -> Vec<&'static str> {
vec![$($($composite_field),*)?]
}
pub fn where_clause() -> Option<&'static str> {
$($crate::index!(@optional_string $where_clause))?
}
pub fn expression() -> Option<&'static str> {
None
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "index",
name: stringify!($index_name),
ddl: "", schema: None,
})
}
};
(
$index_name:ident ($table_name:ident) {
expression: $expression:expr,
$(unique: $unique:ident,)?
$(concurrent: $concurrent:ident,)?
$(index_type: $index_type:ident,)?
$(where_clause: $where_clause:expr,)?
}
) => {
pub mod $index_name {
use $crate::schema::{IndexMeta, IndexType};
pub fn meta() -> IndexMeta {
IndexMeta {
name: stringify!($index_name),
table: stringify!($table_name),
schema: None,
unique: $crate::index!(@bool_value $($unique)?),
concurrent: $crate::index!(@bool_value $($concurrent)?),
index_type: $crate::index!(@index_type $($index_type)?),
columns: &[], }
}
pub fn name() -> &'static str {
stringify!($index_name)
}
pub fn table() -> &'static str {
stringify!($table_name)
}
pub fn columns() -> &'static [&'static str] {
&[]
}
pub fn composite_fields() -> Vec<&'static str> {
vec![]
}
pub fn expression() -> Option<&'static str> {
Some($expression)
}
pub fn where_clause() -> Option<&'static str> {
$($crate::index!(@optional_string $where_clause))?
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "index",
name: stringify!($index_name),
ddl: "", schema: None,
})
}
};
(@extract_columns $col:ident) => { stringify!($col) };
(@extract_columns ($composite:tt).$field:ident) => { concat!(stringify!($composite), ".", stringify!($field)) };
(@extract_columns $col:ident, $($rest:tt),*) => {
stringify!($col), $crate::index!(@extract_columns $($rest),*)
};
(@extract_columns ($composite:tt).$field:ident, $($rest:tt),*) => {
concat!(stringify!($composite), ".", stringify!($field)), $crate::index!(@extract_columns $($rest),*)
};
(@bool_value) => { false };
(@bool_value true) => { true };
(@bool_value false) => { false };
(@index_type) => { IndexType::BTree };
(@index_type btree) => { IndexType::BTree };
(@index_type hash) => { IndexType::Hash };
(@index_type gin) => { IndexType::GIN };
(@index_type gist) => { IndexType::GiST };
(@index_type spgist) => { IndexType::SPGIST };
(@index_type brin) => { IndexType::BRIN };
(@optional_string $value:expr) => { Some($value) };
(@columns $first_col:ident) => {
concat!("\"", stringify!($first_col), "\"")
};
(@columns $first_col:ident, $($rest_col:ident),*) => {
concat!(
"\"", stringify!($first_col), "\", ",
$crate::index!(@columns $($rest_col),*)
)
};
}
#[macro_export]
macro_rules! trigger {
(
$trigger_name:ident ($table_name:ident) -> $function_name:ident {
timing: $timing:ident,
events: [$($event:ident),* $(,)?],
orientation: $orientation:ident
$(, condition: $condition:expr)?
$(, update_columns: [$($update_col:ident),* $(,)?])?
$(, composite_fields: [$($composite_field:expr),* $(,)?])?
}
) => {
pub mod $trigger_name {
use $crate::schema::{Trigger, TriggerTiming, TriggerEvent, TriggerOrientation};
pub fn trigger() -> Trigger {
let mut trigger = Trigger::new(
stringify!($trigger_name),
stringify!($table_name),
$crate::trigger!(@timing $timing),
vec![$($crate::trigger!(@event $event)),*],
stringify!($function_name)
);
trigger = trigger.with_orientation($crate::trigger!(@orientation $orientation));
$(trigger = trigger.with_condition($condition);)?
$(trigger = trigger.with_update_columns(vec![$(stringify!($update_col).to_string()),*]);)?
trigger
}
pub fn name() -> &'static str {
stringify!($trigger_name)
}
pub fn table() -> &'static str {
stringify!($table_name)
}
pub fn function() -> &'static str {
stringify!($function_name)
}
pub fn composite_fields() -> Vec<&'static str> {
vec![$($($composite_field),*)?]
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "trigger",
name: stringify!($trigger_name),
ddl: "", schema: None,
})
}
};
(
$trigger_name:ident ($schema:ident . $table_name:ident) -> $function_schema:ident . $function_name:ident {
timing: $timing:ident,
events: [$($event:ident),* $(,)?],
orientation: $orientation:ident
$(, condition: $condition:expr)?
$(, update_columns: [$($update_col:ident),* $(,)?])?
$(, composite_fields: [$($composite_field:expr),* $(,)?])?
}
) => {
pub mod $trigger_name {
use $crate::schema::{Trigger, TriggerTiming, TriggerEvent, TriggerOrientation};
pub fn trigger() -> Trigger {
let mut trigger = Trigger::new(
stringify!($trigger_name),
stringify!($table_name),
$crate::trigger!(@timing $timing),
vec![$($crate::trigger!(@event $event)),*],
stringify!($function_name)
);
trigger = trigger
.with_table_schema(stringify!($schema))
.with_function_schema(stringify!($function_schema))
.with_orientation($crate::trigger!(@orientation $orientation));
$(trigger = trigger.with_condition($condition);)?
$(trigger = trigger.with_update_columns(vec![$(stringify!($update_col).to_string()),*]);)?
trigger
}
pub fn name() -> &'static str {
stringify!($trigger_name)
}
pub fn table() -> &'static str {
stringify!($table_name)
}
pub fn function() -> &'static str {
stringify!($function_name)
}
pub fn composite_fields() -> Vec<&'static str> {
vec![$($($composite_field),*)?]
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "trigger",
name: stringify!($trigger_name),
ddl: "", schema: Some(stringify!($schema)),
})
}
};
(@timing before) => { TriggerTiming::Before };
(@timing after) => { TriggerTiming::After };
(@timing instead_of) => { TriggerTiming::InsteadOf };
(@event insert) => { TriggerEvent::Insert };
(@event update) => { TriggerEvent::Update };
(@event delete) => { TriggerEvent::Delete };
(@event truncate) => { TriggerEvent::Truncate };
(@orientation row) => { TriggerOrientation::Row };
(@orientation statement) => { TriggerOrientation::Statement };
}
#[macro_export]
macro_rules! composite {
(
$type_name:ident {
$($field_name:ident: $field_type:ident),* $(,)?
}
) => {
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct $type_name {
$(pub $field_name: $crate::composite!(@rust_field_type $field_type),)*
}
impl $type_name {
pub fn composite_type() -> $crate::schema::CompositeType {
use $crate::schema::{CompositeType, CompositeField};
let name = stringify!($type_name)
.chars()
.enumerate()
.flat_map(|(i, c)| {
if i > 0 && c.is_ascii_uppercase() {
vec!['_', c.to_ascii_lowercase()]
} else {
vec![c.to_ascii_lowercase()]
}
})
.collect::<String>();
let mut composite = CompositeType::new(name);
$(
composite = composite.with_field(
stringify!($field_name),
$crate::composite!(@sql_type $field_type),
false );
)*
composite
}
pub fn type_name() -> String {
stringify!($type_name)
.chars()
.enumerate()
.flat_map(|(i, c)| {
if i > 0 && c.is_ascii_uppercase() {
vec!['_', c.to_ascii_lowercase()]
} else {
vec![c.to_ascii_lowercase()]
}
})
.collect::<String>()
}
pub fn registry() -> Vec<$crate::schema::CompositeType> {
vec![Self::composite_type()]
}
pub fn generate_create_ddl() -> String {
Self::composite_type().generate_create_ddl()
}
pub fn pg_type_name() -> &'static str {
const TYPE_NAME: &str = stringify!($type_name);
if TYPE_NAME == "Address" {
"address"
} else if TYPE_NAME == "Point" {
"point"
} else if TYPE_NAME == "ContactInfo" {
"contact_info"
} else if TYPE_NAME == "UserProfile" {
"user_profile"
} else if TYPE_NAME == "CompanyInfo" {
"company_info"
} else {
"unknown_type"
}
}
pub fn generate_drop_ddl() -> String {
format!("DROP TYPE IF EXISTS \"{}\" CASCADE;", Self::pg_type_name())
}
}
impl From<$type_name> for $crate::macros::parameter_binding::BindValue {
fn from(value: $type_name) -> Self {
match serde_json::to_value(value) {
Ok(json_value) => $crate::macros::parameter_binding::BindValue::Composite(json_value),
Err(_) => $crate::macros::parameter_binding::BindValue::Null, }
}
}
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "composite_type",
name: stringify!($type_name),
ddl: "", schema: None,
})
}
};
(@sql_type Text) => { "TEXT" };
(@sql_type Varchar) => { "VARCHAR" };
(@sql_type Int2) => { "SMALLINT" };
(@sql_type Int4) => { "INTEGER" };
(@sql_type Int8) => { "BIGINT" };
(@sql_type Real) => { "REAL" };
(@sql_type DoublePrecision) => { "DOUBLE PRECISION" };
(@sql_type Numeric) => { "NUMERIC" };
(@sql_type Bool) => { "BOOLEAN" };
(@sql_type Date) => { "DATE" };
(@sql_type Time) => { "TIME" };
(@sql_type Timestamp) => { "TIMESTAMP" };
(@sql_type Timestamptz) => { "TIMESTAMPTZ" };
(@sql_type Uuid) => { "UUID" };
(@sql_type Json) => { "JSON" };
(@sql_type Jsonb) => { "JSONB" };
(@sql_type Bytea) => { "BYTEA" };
(@sql_type Inet) => { "INET" };
(@sql_type Cidr) => { "CIDR" };
(@sql_type MacAddr) => { "MACADDR" };
(@sql_type $custom_type:ident) => { stringify!($custom_type) };
(@rust_field_type Text) => { String };
(@rust_field_type Varchar) => { String };
(@rust_field_type Int2) => { i16 };
(@rust_field_type Int4) => { i32 };
(@rust_field_type Int8) => { i64 };
(@rust_field_type Real) => { f32 };
(@rust_field_type DoublePrecision) => { f64 };
(@rust_field_type Numeric) => { rust_decimal::Decimal };
(@rust_field_type Bool) => { bool };
(@rust_field_type Date) => { chrono::NaiveDate };
(@rust_field_type Time) => { chrono::NaiveTime };
(@rust_field_type Timestamp) => { chrono::NaiveDateTime };
(@rust_field_type Timestamptz) => { chrono::DateTime<chrono::Utc> };
(@rust_field_type Uuid) => { uuid::Uuid };
(@rust_field_type Json) => { serde_json::Value };
(@rust_field_type Jsonb) => { serde_json::Value };
(@rust_field_type Bytea) => { Vec<u8> };
(@rust_field_type $custom_type:ident) => { $custom_type };
}
#[macro_export]
macro_rules! column_type_mapping {
(Int2) => {
ColumnType::Int2
};
(Int4) => {
ColumnType::Int4
};
(Int8) => {
ColumnType::Int8
};
(Varchar) => {
ColumnType::Varchar(None)
};
(Text) => {
ColumnType::Text
};
(Bool) => {
ColumnType::Bool
};
(Uuid) => {
ColumnType::Uuid
};
(Timestamptz) => {
ColumnType::Timestamptz
};
(Date) => {
ColumnType::Date
};
(Time) => {
ColumnType::Time
};
(Json) => {
ColumnType::Json
};
(Jsonb) => {
ColumnType::Jsonb
};
(Char) => {
ColumnType::Char
};
(Numeric) => {
ColumnType::Numeric(None, None)
};
(Array) => {
ColumnType::Text
};
(Custom($type_name:expr)) => {
ColumnType::Custom($type_name.to_string())
};
(Serial) => {
ColumnType::Serial
};
(BigSerial) => {
ColumnType::BigSerial
};
(SmallSerial) => {
ColumnType::SmallSerial
};
}
#[macro_export]
macro_rules! rust_type_mapping {
(Int2) => { i16 };
(Int4) => { i32 };
(Int8) => { i64 };
(Varchar) => { String };
(Text) => { String };
(Bool) => { bool };
(Uuid) => { uuid::Uuid };
(Timestamptz) => { chrono::DateTime<chrono::Utc> };
(Date) => { chrono::NaiveDate };
(Time) => { chrono::NaiveTime };
(Json) => { serde_json::Value };
(Jsonb) => { serde_json::Value };
(Char) => { char };
(Numeric) => { rust_decimal::Decimal };
(Array) => { Vec<String> };
(Custom($rust_type:ty)) => { $rust_type };
(Serial) => { i32 }; (BigSerial) => { i64 }; (SmallSerial) => { i16 }; }
#[macro_export]
macro_rules! sql_type_mapping {
(Int2) => {
"SMALLINT"
};
(Int4) => {
"INTEGER"
};
(Int8) => {
"BIGINT"
};
(Varchar) => {
"VARCHAR"
};
(Text) => {
"TEXT"
};
(Bool) => {
"BOOLEAN"
};
(Uuid) => {
"UUID"
};
(Timestamptz) => {
"TIMESTAMPTZ"
};
(Date) => {
"DATE"
};
(Time) => {
"TIME"
};
(Json) => {
"JSON"
};
(Jsonb) => {
"JSONB"
};
(Char) => {
"CHAR"
};
(Numeric) => {
"NUMERIC"
};
(Array) => {
"TEXT[]"
};
(Custom($type_name:expr)) => {
$type_name
};
(Serial) => {
"SERIAL"
};
(BigSerial) => {
"BIGSERIAL"
};
(SmallSerial) => {
"SMALLSERIAL"
};
}
pub mod sql_safety;
pub mod parameter_binding;
#[macro_export]
macro_rules! event {
(
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: concat!("event_", line!()),
ddl: concat!("SELECT cron.schedule('", concat!("event_", line!()), "', '", $schedule, "', $$", $command, "$$)"),
schema: None,
})
}
};
(
#[name = $name:literal]
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: $name,
ddl: concat!("SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$)"),
schema: None,
})
}
};
(
#[name = $name:literal]
#[database = $db:literal]
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: $name,
ddl: concat!(
"SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
"\nUPDATE cron.job SET database = '", $db, "' WHERE jobname = '", $name, "'"
),
schema: None,
})
}
};
(
#[name = $name:literal]
#[username = $user:literal]
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: $name,
ddl: concat!(
"SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
"\nUPDATE cron.job SET username = '", $user, "' WHERE jobname = '", $name, "'"
),
schema: None,
})
}
};
(
#[name = $name:literal]
#[ddl = $ddl:literal]
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: $name,
ddl: $ddl,
schema: None,
})
}
};
(
#[name = $name:literal]
#[database = $db:literal]
#[username = $user:literal]
$schedule:literal;
$command:literal
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "event",
name: $name,
ddl: concat!(
"SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
"\nUPDATE cron.job SET database = '", $db, "' WHERE jobname = '", $name, "';",
"\nUPDATE cron.job SET username = '", $user, "' WHERE jobname = '", $name, "'"
),
schema: None,
})
}
};
}
#[macro_export]
macro_rules! role {
(
$role_name:ident
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "role",
name: stringify!($role_name),
ddl: concat!("CREATE ROLE \"", stringify!($role_name), "\" NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT NOREPLICATION;"),
schema: None,
})
}
};
}
#[macro_export]
macro_rules! grant {
(
$privilege:ident ON $table:ident TO $grantee:ident
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "grant",
name: concat!(stringify!($privilege), "_on_", stringify!($table), "_to_", stringify!($grantee)),
ddl: concat!("GRANT ", stringify!($privilege), " ON ", stringify!($table), " TO ", stringify!($grantee), ";"),
schema: None,
})
}
};
(
$($privilege:ident),+ ON $table:ident TO $grantee:ident
) => {
inventory::submit! {
$crate::RegisteredObject($crate::SchemaObject {
kind: "grant",
name: concat!("privileges_on_", stringify!($table), "_to_", stringify!($grantee)),
ddl: concat!(
"GRANT ",
$crate::grant!(@join_privileges $($privilege),+),
" ON ", stringify!($table),
" TO ", stringify!($grantee), ";"
),
schema: None,
})
}
};
(@join_privileges $first:ident) => { stringify!($first) };
(@join_privileges $first:ident, $($rest:ident),+) => {
concat!(stringify!($first), ", ", $crate::grant!(@join_privileges $($rest),+))
};
}