1pub mod composite;
4pub mod procedure;
5
6#[macro_export]
8macro_rules! impl_ignis_model {
9 ($struct_name:ident, $table:expr, $pk:expr) => {
10 impl ::ignis_db::IgnisModel for $struct_name {
11 const TABLE: &'static str = $table;
12 const PK: &'static str = $pk;
13 const SCHEMA: Option<&'static str> = None;
14 const FULL_TABLE_NAME: &'static str = $table;
15
16 fn get_primary_key_value(&self) -> anyhow::Result<::ignis_db::BindValue> {
17 Err(anyhow::anyhow!(
18 "get_primary_key_value must be implemented for {}",
19 stringify!($struct_name)
20 ))
21 }
22 }
23 };
24 ($struct_name:ident, $table:expr, $pk:expr, $schema:expr) => {
25 impl ::ignis_db::IgnisModel for $struct_name {
26 const TABLE: &'static str = $table;
27 const PK: &'static str = $pk;
28 const SCHEMA: Option<&'static str> = Some($schema);
29 const FULL_TABLE_NAME: &'static str = concat!($schema, ".", $table);
30
31 fn get_primary_key_value(&self) -> anyhow::Result<::ignis_db::BindValue> {
32 Err(anyhow::anyhow!(
33 "get_primary_key_value must be implemented for {}",
34 stringify!($struct_name)
35 ))
36 }
37 }
38 };
39}
40
41#[macro_export]
43macro_rules! impl_insertable {
44 ($struct_name:ident) => {
45 impl ::ignis_db::Insertable for $struct_name {
46 fn insert<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
47 where
48 E: sqlx::Executor<'e, Database = sqlx::Postgres>,
49 {
50 async move {
51 use $crate::macros::parameter_binding::{SafeInsertBuilder, BindValue};
52
53 let mut builder = SafeInsertBuilder::new(Self::FULL_TABLE_NAME)
55 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
56
57 let builder = $crate::impl_insertable!(@add_fields self, builder);
60
61 builder.execute(executor).await
63 }
64 }
65 }
66 };
67
68 (@add_fields $self:expr, $builder:expr) => {
70 $builder
72 };
73}
74
75#[macro_export]
77macro_rules! impl_updatable {
78 ($struct_name:ident) => {
79 impl ::ignis_db::Updatable for $struct_name {
80 fn update<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
81 where
82 E: sqlx::Executor<'e, Database = sqlx::Postgres>,
83 {
84 async move {
85 use $crate::macros::parameter_binding::{SafeUpdateBuilder, BindValue};
86
87 let mut builder = SafeUpdateBuilder::new(Self::FULL_TABLE_NAME)
89 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
90
91 let builder = $crate::impl_updatable!(@add_set_fields self, builder);
94
95 let pk_value = self.get_primary_key_value()
97 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
98 let pk_bind_value = $crate::impl_updatable!(@convert_to_bind_value pk_value);
99
100 let builder = builder.r#where(Self::PK, pk_bind_value)
101 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
102
103 builder.execute(executor).await
105 }
106 }
107 }
108 };
109
110 (@add_set_fields $self:expr, $builder:expr) => {
112 $builder
114 };
115
116 (@convert_to_bind_value $value:expr) => {
118 match $value {
119 $crate::BindValue::Int4(v) => $crate::macros::parameter_binding::BindValue::Int4(v),
120 $crate::BindValue::Int8(v) => $crate::macros::parameter_binding::BindValue::Int8(v),
121 $crate::BindValue::Text(v) => $crate::macros::parameter_binding::BindValue::Text(v),
122 $crate::BindValue::Bool(v) => $crate::macros::parameter_binding::BindValue::Bool(v),
123 $crate::BindValue::Uuid(v) => $crate::macros::parameter_binding::BindValue::Uuid(v),
124 $crate::BindValue::Timestamptz(v) => $crate::macros::parameter_binding::BindValue::Timestamptz(v),
125 $crate::BindValue::Numeric(v) => $crate::macros::parameter_binding::BindValue::Numeric(v),
126 $crate::BindValue::Jsonb(v) => $crate::macros::parameter_binding::BindValue::Jsonb(v),
127 $crate::BindValue::Composite(v) => $crate::macros::parameter_binding::BindValue::Composite(v),
128 $crate::BindValue::Array(v) => $crate::macros::parameter_binding::BindValue::Array(v),
129 $crate::BindValue::Null => $crate::macros::parameter_binding::BindValue::Null,
130 }
131 };
132}
133
134#[macro_export]
136macro_rules! impl_deletable {
137 ($struct_name:ident) => {
138 impl ::ignis_db::Deletable for $struct_name {
139 fn delete<'e, E>(&self, executor: E) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
140 where
141 E: sqlx::Executor<'e, Database = sqlx::Postgres>,
142 {
143 async move {
144 use $crate::macros::parameter_binding::{SafeDeleteBuilder, BindValue};
145
146 let mut builder = SafeDeleteBuilder::new(Self::FULL_TABLE_NAME)
148 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
149
150 let pk_value = self.get_primary_key_value()
152 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
153 let pk_bind_value = $crate::impl_deletable!(@convert_to_bind_value pk_value);
154
155 builder = builder.r#where(Self::PK, pk_bind_value)
156 .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
157
158 builder.execute(executor).await
160 }
161 }
162 }
163 };
164
165 (@convert_to_bind_value $value:expr) => {
167 match $value {
168 $crate::BindValue::Int4(v) => $crate::macros::parameter_binding::BindValue::Int4(v),
169 $crate::BindValue::Int8(v) => $crate::macros::parameter_binding::BindValue::Int8(v),
170 $crate::BindValue::Text(v) => $crate::macros::parameter_binding::BindValue::Text(v),
171 $crate::BindValue::Bool(v) => $crate::macros::parameter_binding::BindValue::Bool(v),
172 $crate::BindValue::Uuid(v) => $crate::macros::parameter_binding::BindValue::Uuid(v),
173 $crate::BindValue::Timestamptz(v) => $crate::macros::parameter_binding::BindValue::Timestamptz(v),
174 $crate::BindValue::Numeric(v) => $crate::macros::parameter_binding::BindValue::Numeric(v),
175 $crate::BindValue::Jsonb(v) => $crate::macros::parameter_binding::BindValue::Jsonb(v),
176 $crate::BindValue::Composite(v) => $crate::macros::parameter_binding::BindValue::Composite(v),
177 $crate::BindValue::Array(v) => $crate::macros::parameter_binding::BindValue::Array(v),
178 $crate::BindValue::Null => $crate::macros::parameter_binding::BindValue::Null,
179 }
180 };
181}
182
183#[macro_export]
209macro_rules! table {
210 (
212 $table_name:ident ($first_pk:ident, $($rest_pk:ident),+ $(,)?) {
213 $($col_name:ident -> $col_type:tt),* $(,)?
214 }
215 ) => {
216 pub mod $table_name {
217 use $crate::schema::{Table, Column, ColumnType, TableMeta};
218
219 pub fn table() -> Table {
221 let mut table = Table::new(stringify!($table_name));
222
223 $(
225 table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
226 )*
227
228 let pk_columns = vec![stringify!($first_pk).to_string(), $(stringify!($rest_pk).to_string()),+];
230 table = table.set_primary_key(&pk_columns.join(", "));
231
232 table
233 }
234
235 pub fn pk() -> Vec<String> {
237 vec![stringify!($first_pk).to_string(), $(stringify!($rest_pk).to_string()),+]
238 }
239
240 $(
241 pub fn $col_name() -> $crate::dsl::Column<$crate::table!(@rust_type $col_type)> {
243 $crate::dsl::Column::new(stringify!($col_name))
244 .from_table(stringify!($table_name))
245 }
246 )*
247
248 pub fn meta() -> TableMeta {
250 TableMeta::new(
251 stringify!($table_name),
252 None,
253 $crate::table!(@pk_string $first_pk, $($rest_pk),+),
254 &[
255 $(
256 (stringify!($col_name), $crate::table!(@resolve_column_type $col_type)),
257 )*
258 ],
259 )
260 }
261
262 pub fn configure<F>(mutator: F) -> Table
264 where
265 F: FnOnce(&mut Table) -> &mut Table,
266 {
267 let mut table = table();
268 mutator(&mut table);
269 table
270 }
271
272 pub struct Columns;
274
275 impl Columns {
276 $(
277 pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::table!(@rust_type $col_type)> {
278 $crate::dsl::TypedColumn::new(
279 Column::new(stringify!($col_name).to_string(), $crate::table!(@resolve_column_type $col_type)),
280 stringify!($table_name).to_string(),
281 None
282 )
283 }
284 )*
285 }
286
287 pub fn typed_query() -> $crate::dsl::TypedQuery {
289 $crate::dsl::TypedQuery::new().from_table(table())
290 }
291 }
292
293 inventory::submit! {
295 $crate::RegisteredObject($crate::SchemaObject {
296 kind: "table",
297 name: stringify!($table_name),
298 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),+), "));"),
299 schema: None,
300 })
301 }
302 };
303
304 (
306 $table_name:ident ($pk:ident) {
307 $($col_name:ident -> $col_type:tt),* $(,)?
308 }
309 ) => {
310 pub mod $table_name {
311 use $crate::schema::{Table, Column, ColumnType, TableMeta};
312
313 pub fn table() -> Table {
315 let mut table = Table::new(stringify!($table_name));
316
317 $(
319 table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
320 )*
321
322 table = table.set_primary_key(stringify!($pk));
324
325 table
326 }
327
328 pub fn pk() -> $crate::dsl::Column<i32> {
330 $crate::dsl::Column::new(stringify!($pk))
331 .from_table(stringify!($table_name))
332 }
333
334 $(
335 pub fn $col_name() -> $crate::dsl::Column<$crate::table!(@rust_type $col_type)> {
337 $crate::dsl::Column::new(stringify!($col_name))
338 .from_table(stringify!($table_name))
339 }
340 )*
341
342 pub fn meta() -> TableMeta {
344 TableMeta::new(
345 stringify!($table_name),
346 None,
347 stringify!($pk),
348 &[
349 $(
350 (stringify!($col_name), $crate::table!(@resolve_column_type $col_type)),
351 )*
352 ],
353 )
354 }
355
356 pub fn configure<F>(mutator: F) -> Table
358 where
359 F: FnOnce(&mut Table) -> &mut Table,
360 {
361 let mut table = table();
362 mutator(&mut table);
363 table
364 }
365
366 pub struct Columns;
368
369 impl Columns {
370 $(
371 pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::table!(@rust_type $col_type)> {
373 $crate::dsl::TypedColumn::new(
374 Column::new(stringify!($col_name).to_string(), $crate::table!(@resolve_column_type $col_type)),
375 stringify!($table_name).to_string(),
376 None
377 )
378 }
379 )*
380 }
381
382 pub fn typed_query() -> $crate::dsl::TypedQuery {
384 $crate::dsl::TypedQuery::new().from_table(table())
385 }
386 }
387
388 inventory::submit! {
390 $crate::RegisteredObject($crate::SchemaObject {
391 kind: "table",
392 name: stringify!($table_name),
393 ddl: concat!("CREATE TABLE \"", stringify!($table_name), "\" (", $crate::table!(@ddl_columns $($col_name -> $col_type),*), ", PRIMARY KEY (\"", stringify!($pk), "\"));"),
394 schema: None,
395 })
396 }
397 };
398
399 (@resolve_column_type $type:ident) => { $crate::column_type_mapping!($type) };
401 (@resolve_column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
402 (@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
404
405 (@column_type $type:ident) => { $crate::column_type_mapping!($type) };
407 (@column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
408
409 (@rust_type $type:ident) => { $crate::rust_type_mapping!($type) };
410 (@rust_type Custom($rust_type:ty, $type_name:expr)) => { $crate::rust_type_mapping!(Custom($rust_type)) };
411
412 (@ddl_columns $first_col:ident -> Custom($rust_type:ty, $type_name:expr)) => {
414 concat!("\"", stringify!($first_col), "\" ", $crate::table!(@sql_type Custom($rust_type, $type_name)))
415 };
416 (@ddl_columns $first_col:ident -> $first_type:ident) => {
417 concat!("\"", stringify!($first_col), "\" ", $crate::table!(@sql_type $first_type))
418 };
419 (@ddl_columns $first_col:ident -> $first_type:ident, $($rest_col:ident -> $rest_type:tt),*) => {
420 concat!(
421 "\"", stringify!($first_col), "\" ", $crate::table!(@sql_type $first_type), ", ",
422 $crate::table!(@ddl_columns $($rest_col -> $rest_type),*)
423 )
424 };
425 (@ddl_columns $first_col:ident -> Custom($rust_type:ty, $type_name:expr), $($rest_col:ident -> $rest_type:tt),*) => {
426 concat!(
427 "\"", stringify!($first_col), "\" ", $crate::table!(@sql_type Custom($rust_type, $type_name)), ", ",
428 $crate::table!(@ddl_columns $($rest_col -> $rest_type),*)
429 )
430 };
431
432 (@sql_type $type:ident) => { $crate::sql_type_mapping!($type) };
433 (@sql_type Custom($rust_type:ty, $type_name:expr)) => {
434 $crate::sql_type_mapping!(Custom($type_name))
435 };
436
437 (@pk_columns $first_pk:ident) => {
439 concat!("\"", stringify!($first_pk), "\"")
440 };
441 (@pk_columns $first_pk:ident, $($rest_pk:ident),+) => {
442 concat!(
443 "\"", stringify!($first_pk), "\", ",
444 $crate::table!(@pk_columns $($rest_pk),+)
445 )
446 };
447
448 (@pk_string $first_pk:ident) => {
450 stringify!($first_pk)
451 };
452 (@pk_string $first_pk:ident, $($rest_pk:ident),+) => {
453 concat!(
454 stringify!($first_pk), ", ",
455 $crate::table!(@pk_string $($rest_pk),+)
456 )
457 };
458}
459
460#[macro_export]
490macro_rules! view {
491 (
492 $view_name:ident ($pk:ident) {
493 $($col_name:ident -> $col_type:tt),* $(,)?
494 }
495 ) => {
496 pub mod $view_name {
497 use $crate::schema::{View, Column, ColumnType};
498
499 pub fn view() -> View {
501 let mut view = View::new(stringify!($view_name));
502
503 $(
505 view = view.add_column(Column::new(stringify!($col_name), $crate::view!(@column_type $col_type)));
506 )*
507
508 view
509 }
510
511 pub fn pk() -> $crate::dsl::Column<i32> {
513 $crate::dsl::Column::new(stringify!($pk))
514 .from_table(stringify!($view_name))
515 }
516
517 $(
518 pub fn $col_name() -> $crate::dsl::Column<$crate::view!(@rust_type $col_type)> {
520 $crate::dsl::Column::new(stringify!($col_name))
521 .from_table(stringify!($view_name))
522 }
523 )*
524
525 pub fn configure<F>(mutator: F) -> View
527 where
528 F: FnOnce(&mut View) -> &mut View,
529 {
530 let mut view = view();
531 mutator(&mut view);
532 view
533 }
534
535 pub fn materialized<F>(mutator: F) -> View
537 where
538 F: FnOnce(&mut View) -> &mut View,
539 {
540 let mut view = view();
541 view.set_materialized(true);
542 mutator(&mut view);
543 view
544 }
545
546 pub struct Columns;
548
549 impl Columns {
550 $(
551 pub fn $col_name() -> $crate::dsl::TypedColumn<$crate::view!(@rust_type $col_type)> {
553 $crate::dsl::TypedColumn::new(
554 Column::new(stringify!($col_name).to_string(), $crate::view!(@column_type $col_type)),
555 stringify!($view_name).to_string(),
556 None
557 )
558 }
559 )*
560 }
561
562 pub fn typed_query() -> $crate::dsl::TypedQuery {
564 $crate::dsl::TypedQuery::new().from_view(view())
565 }
566 }
567
568 inventory::submit! {
570 $crate::RegisteredObject($crate::SchemaObject {
571 kind: "view",
572 name: stringify!($view_name),
573 ddl: concat!("CREATE VIEW \"", stringify!($view_name), "\" AS SELECT ", $crate::view!(@ddl_columns $($col_name -> $col_type),*), " FROM /* table_name */;"),
574 schema: None,
575 })
576 }
577 };
578
579 (@resolve_column_type $type:ident) => { $crate::column_type_mapping!($type) };
581 (@resolve_column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
582 (@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
584
585 (@column_type $type:ident) => { $crate::column_type_mapping!($type) };
587 (@column_type Custom($rust_type:ty, $type_name:expr)) => { $crate::column_type_mapping!(Custom($type_name)) };
588
589 (@rust_type $type:ident) => { $crate::rust_type_mapping!($type) };
590 (@rust_type Custom($rust_type:ty, $type_name:expr)) => { $crate::rust_type_mapping!(Custom($rust_type)) };
591
592 (@ddl_columns $first_col:ident -> $first_type:ident) => {
594 concat!("\"", stringify!($first_col), "\"")
595 };
596 (@ddl_columns $first_col:ident -> $first_type:ident, $($rest_col:ident -> $rest_type:ident),*) => {
597 concat!(
598 "\"", stringify!($first_col), "\", ",
599 $crate::view!(@ddl_columns $($rest_col -> $rest_type),*)
600 )
601 };
602}
603
604#[macro_export]
621macro_rules! index {
622 (
624 $index_name:ident ($table_name:ident, $($col_name:ident),* $(,)?)
625 ) => {
626 pub mod $index_name {
627 use $crate::schema::{IndexMeta, IndexType};
628
629 pub fn meta() -> IndexMeta {
631 IndexMeta {
632 name: stringify!($index_name),
633 table: stringify!($table_name),
634 schema: None,
635 unique: false,
636 concurrent: false,
637 index_type: IndexType::BTree,
638 columns: &[$(stringify!($col_name)),*],
639 }
640 }
641
642 pub fn name() -> &'static str {
644 stringify!($index_name)
645 }
646
647 pub fn table() -> &'static str {
649 stringify!($table_name)
650 }
651
652 pub fn columns() -> &'static [&'static str] {
654 &[$(stringify!($col_name)),*]
655 }
656
657 pub fn composite_fields() -> Vec<&'static str> {
659 vec![]
660 }
661
662 pub fn expression() -> Option<&'static str> {
664 None
665 }
666 }
667
668 inventory::submit! {
670 $crate::RegisteredObject($crate::SchemaObject {
671 kind: "index",
672 name: stringify!($index_name),
673 ddl: concat!("CREATE INDEX \"", stringify!($index_name), "\" ON \"", stringify!($table_name), "\" (", $crate::index!(@columns $($col_name),*), ");"),
674 schema: None,
675 })
676 }
677 };
678
679 (
681 $index_name:ident ($table_name:ident, [$($col_spec:tt),* $(,)?]) {
682 $(unique: $unique:ident,)?
683 $(concurrent: $concurrent:ident,)?
684 $(index_type: $index_type:ident,)?
685 $(composite_fields: [$($composite_field:expr),* $(,)?],)?
686 $(where_clause: $where_clause:expr,)?
687 }
688 ) => {
689 pub mod $index_name {
690 use $crate::schema::{IndexMeta, IndexType};
691
692 pub fn meta() -> IndexMeta {
694 IndexMeta {
695 name: stringify!($index_name),
696 table: stringify!($table_name),
697 schema: None,
698 unique: $crate::index!(@bool_value $($unique)?),
699 concurrent: $crate::index!(@bool_value $($concurrent)?),
700 index_type: $crate::index!(@index_type $($index_type)?),
701 columns: &[$crate::index!(@extract_columns $($col_spec),*)],
702 }
703 }
704
705 pub fn name() -> &'static str {
707 stringify!($index_name)
708 }
709
710 pub fn table() -> &'static str {
712 stringify!($table_name)
713 }
714
715 pub fn columns() -> &'static [&'static str] {
717 &[$crate::index!(@extract_columns $($col_spec),*)]
718 }
719
720 pub fn composite_fields() -> Vec<&'static str> {
722 vec![$($($composite_field),*)?]
723 }
724
725 pub fn where_clause() -> Option<&'static str> {
727 $($crate::index!(@optional_string $where_clause))?
728 }
729
730 pub fn expression() -> Option<&'static str> {
732 None
733 }
734 }
735
736 inventory::submit! {
738 $crate::RegisteredObject($crate::SchemaObject {
739 kind: "index",
740 name: stringify!($index_name),
741 ddl: "", schema: None,
743 })
744 }
745 };
746
747 (
749 $index_name:ident ($table_name:ident) {
750 expression: $expression:expr,
751 $(unique: $unique:ident,)?
752 $(concurrent: $concurrent:ident,)?
753 $(index_type: $index_type:ident,)?
754 $(where_clause: $where_clause:expr,)?
755 }
756 ) => {
757 pub mod $index_name {
758 use $crate::schema::{IndexMeta, IndexType};
759
760 pub fn meta() -> IndexMeta {
762 IndexMeta {
763 name: stringify!($index_name),
764 table: stringify!($table_name),
765 schema: None,
766 unique: $crate::index!(@bool_value $($unique)?),
767 concurrent: $crate::index!(@bool_value $($concurrent)?),
768 index_type: $crate::index!(@index_type $($index_type)?),
769 columns: &[], }
771 }
772
773 pub fn name() -> &'static str {
775 stringify!($index_name)
776 }
777
778 pub fn table() -> &'static str {
780 stringify!($table_name)
781 }
782
783 pub fn columns() -> &'static [&'static str] {
785 &[]
786 }
787
788 pub fn composite_fields() -> Vec<&'static str> {
790 vec![]
791 }
792
793 pub fn expression() -> Option<&'static str> {
795 Some($expression)
796 }
797
798 pub fn where_clause() -> Option<&'static str> {
800 $($crate::index!(@optional_string $where_clause))?
801 }
802 }
803
804 inventory::submit! {
806 $crate::RegisteredObject($crate::SchemaObject {
807 kind: "index",
808 name: stringify!($index_name),
809 ddl: "", schema: None,
811 })
812 }
813 };
814
815 (@extract_columns $col:ident) => { stringify!($col) };
819 (@extract_columns ($composite:tt).$field:ident) => { concat!(stringify!($composite), ".", stringify!($field)) };
820 (@extract_columns $col:ident, $($rest:tt),*) => {
821 stringify!($col), $crate::index!(@extract_columns $($rest),*)
822 };
823 (@extract_columns ($composite:tt).$field:ident, $($rest:tt),*) => {
824 concat!(stringify!($composite), ".", stringify!($field)), $crate::index!(@extract_columns $($rest),*)
825 };
826
827 (@bool_value) => { false };
829 (@bool_value true) => { true };
830 (@bool_value false) => { false };
831
832 (@index_type) => { IndexType::BTree };
834 (@index_type btree) => { IndexType::BTree };
835 (@index_type hash) => { IndexType::Hash };
836 (@index_type gin) => { IndexType::GIN };
837 (@index_type gist) => { IndexType::GiST };
838 (@index_type spgist) => { IndexType::SPGIST };
839 (@index_type brin) => { IndexType::BRIN };
840
841 (@optional_string $value:expr) => { Some($value) };
843
844 (@columns $first_col:ident) => {
846 concat!("\"", stringify!($first_col), "\"")
847 };
848 (@columns $first_col:ident, $($rest_col:ident),*) => {
849 concat!(
850 "\"", stringify!($first_col), "\", ",
851 $crate::index!(@columns $($rest_col),*)
852 )
853 };
854}
855
856#[macro_export]
884macro_rules! trigger {
885 (
887 $trigger_name:ident ($table_name:ident) -> $function_name:ident {
888 timing: $timing:ident,
889 events: [$($event:ident),* $(,)?],
890 orientation: $orientation:ident
891 $(, condition: $condition:expr)?
892 $(, update_columns: [$($update_col:ident),* $(,)?])?
893 $(, composite_fields: [$($composite_field:expr),* $(,)?])?
894 }
895 ) => {
896 pub mod $trigger_name {
897 use $crate::schema::{Trigger, TriggerTiming, TriggerEvent, TriggerOrientation};
898
899 pub fn trigger() -> Trigger {
901 let mut trigger = Trigger::new(
902 stringify!($trigger_name),
903 stringify!($table_name),
904 $crate::trigger!(@timing $timing),
905 vec![$($crate::trigger!(@event $event)),*],
906 stringify!($function_name)
907 );
908
909 trigger = trigger.with_orientation($crate::trigger!(@orientation $orientation));
910
911 $(trigger = trigger.with_condition($condition);)?
912
913 $(trigger = trigger.with_update_columns(vec![$(stringify!($update_col).to_string()),*]);)?
914
915 trigger
916 }
917
918 pub fn name() -> &'static str {
920 stringify!($trigger_name)
921 }
922
923 pub fn table() -> &'static str {
925 stringify!($table_name)
926 }
927
928 pub fn function() -> &'static str {
930 stringify!($function_name)
931 }
932
933 pub fn composite_fields() -> Vec<&'static str> {
935 vec![$($($composite_field),*)?]
936 }
937 }
938
939 inventory::submit! {
941 $crate::RegisteredObject($crate::SchemaObject {
942 kind: "trigger",
943 name: stringify!($trigger_name),
944 ddl: "", schema: None,
946 })
947 }
948 };
949
950 (
952 $trigger_name:ident ($schema:ident . $table_name:ident) -> $function_schema:ident . $function_name:ident {
953 timing: $timing:ident,
954 events: [$($event:ident),* $(,)?],
955 orientation: $orientation:ident
956 $(, condition: $condition:expr)?
957 $(, update_columns: [$($update_col:ident),* $(,)?])?
958 $(, composite_fields: [$($composite_field:expr),* $(,)?])?
959 }
960 ) => {
961 pub mod $trigger_name {
962 use $crate::schema::{Trigger, TriggerTiming, TriggerEvent, TriggerOrientation};
963
964 pub fn trigger() -> Trigger {
966 let mut trigger = Trigger::new(
967 stringify!($trigger_name),
968 stringify!($table_name),
969 $crate::trigger!(@timing $timing),
970 vec![$($crate::trigger!(@event $event)),*],
971 stringify!($function_name)
972 );
973
974 trigger = trigger
975 .with_table_schema(stringify!($schema))
976 .with_function_schema(stringify!($function_schema))
977 .with_orientation($crate::trigger!(@orientation $orientation));
978
979 $(trigger = trigger.with_condition($condition);)?
980
981 $(trigger = trigger.with_update_columns(vec![$(stringify!($update_col).to_string()),*]);)?
982
983 trigger
984 }
985
986 pub fn name() -> &'static str {
988 stringify!($trigger_name)
989 }
990
991 pub fn table() -> &'static str {
993 stringify!($table_name)
994 }
995
996 pub fn function() -> &'static str {
998 stringify!($function_name)
999 }
1000
1001 pub fn composite_fields() -> Vec<&'static str> {
1003 vec![$($($composite_field),*)?]
1004 }
1005 }
1006
1007 inventory::submit! {
1009 $crate::RegisteredObject($crate::SchemaObject {
1010 kind: "trigger",
1011 name: stringify!($trigger_name),
1012 ddl: "", schema: Some(stringify!($schema)),
1014 })
1015 }
1016 };
1017
1018 (@timing before) => { TriggerTiming::Before };
1020 (@timing after) => { TriggerTiming::After };
1021 (@timing instead_of) => { TriggerTiming::InsteadOf };
1022
1023 (@event insert) => { TriggerEvent::Insert };
1025 (@event update) => { TriggerEvent::Update };
1026 (@event delete) => { TriggerEvent::Delete };
1027 (@event truncate) => { TriggerEvent::Truncate };
1028
1029 (@orientation row) => { TriggerOrientation::Row };
1031 (@orientation statement) => { TriggerOrientation::Statement };
1032}
1033
1034#[macro_export]
1057macro_rules! composite {
1058 (
1059 $type_name:ident {
1060 $($field_name:ident: $field_type:ident),* $(,)?
1061 }
1062 ) => {
1063 #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1065 pub struct $type_name {
1066 $(pub $field_name: $crate::composite!(@rust_field_type $field_type),)*
1067 }
1068
1069 impl $type_name {
1070 pub fn composite_type() -> $crate::schema::CompositeType {
1072 use $crate::schema::{CompositeType, CompositeField};
1073 let name = stringify!($type_name)
1075 .chars()
1076 .enumerate()
1077 .flat_map(|(i, c)| {
1078 if i > 0 && c.is_ascii_uppercase() {
1079 vec!['_', c.to_ascii_lowercase()]
1080 } else {
1081 vec![c.to_ascii_lowercase()]
1082 }
1083 })
1084 .collect::<String>();
1085 let mut composite = CompositeType::new(name);
1086
1087 $(
1088 composite = composite.with_field(
1089 stringify!($field_name),
1090 $crate::composite!(@sql_type $field_type),
1091 false );
1093 )*
1094
1095 composite
1096 }
1097
1098 pub fn type_name() -> String {
1100 stringify!($type_name)
1102 .chars()
1103 .enumerate()
1104 .flat_map(|(i, c)| {
1105 if i > 0 && c.is_ascii_uppercase() {
1106 vec!['_', c.to_ascii_lowercase()]
1107 } else {
1108 vec![c.to_ascii_lowercase()]
1109 }
1110 })
1111 .collect::<String>()
1112 }
1113
1114 pub fn registry() -> Vec<$crate::schema::CompositeType> {
1116 vec![Self::composite_type()]
1117 }
1118
1119 pub fn generate_create_ddl() -> String {
1121 Self::composite_type().generate_create_ddl()
1122 }
1123
1124 pub fn pg_type_name() -> &'static str {
1126 const TYPE_NAME: &str = stringify!($type_name);
1129 if TYPE_NAME == "Address" {
1130 "address"
1131 } else if TYPE_NAME == "Point" {
1132 "point"
1133 } else if TYPE_NAME == "ContactInfo" {
1134 "contact_info"
1135 } else if TYPE_NAME == "UserProfile" {
1136 "user_profile"
1137 } else if TYPE_NAME == "CompanyInfo" {
1138 "company_info"
1139 } else {
1140 "unknown_type"
1141 }
1142 }
1143
1144 pub fn generate_drop_ddl() -> String {
1146 format!("DROP TYPE IF EXISTS \"{}\" CASCADE;", Self::pg_type_name())
1147 }
1148 }
1149
1150 impl From<$type_name> for $crate::macros::parameter_binding::BindValue {
1152 fn from(value: $type_name) -> Self {
1153 match serde_json::to_value(value) {
1155 Ok(json_value) => $crate::macros::parameter_binding::BindValue::Composite(json_value),
1156 Err(_) => $crate::macros::parameter_binding::BindValue::Null, }
1158 }
1159 }
1160
1161 inventory::submit! {
1167 $crate::RegisteredObject($crate::SchemaObject {
1168 kind: "composite_type",
1169 name: stringify!($type_name),
1170 ddl: "", schema: None,
1172 })
1173 }
1174 };
1175
1176 (@sql_type Text) => { "TEXT" };
1178 (@sql_type Varchar) => { "VARCHAR" };
1179 (@sql_type Int2) => { "SMALLINT" };
1180 (@sql_type Int4) => { "INTEGER" };
1181 (@sql_type Int8) => { "BIGINT" };
1182 (@sql_type Real) => { "REAL" };
1183 (@sql_type DoublePrecision) => { "DOUBLE PRECISION" };
1184 (@sql_type Numeric) => { "NUMERIC" };
1185 (@sql_type Bool) => { "BOOLEAN" };
1186 (@sql_type Date) => { "DATE" };
1187 (@sql_type Time) => { "TIME" };
1188 (@sql_type Timestamp) => { "TIMESTAMP" };
1189 (@sql_type Timestamptz) => { "TIMESTAMPTZ" };
1190 (@sql_type Uuid) => { "UUID" };
1191 (@sql_type Json) => { "JSON" };
1192 (@sql_type Jsonb) => { "JSONB" };
1193 (@sql_type Bytea) => { "BYTEA" };
1194 (@sql_type Inet) => { "INET" };
1195 (@sql_type Cidr) => { "CIDR" };
1196 (@sql_type MacAddr) => { "MACADDR" };
1197 (@sql_type $custom_type:ident) => { stringify!($custom_type) };
1199
1200 (@rust_field_type Text) => { String };
1202 (@rust_field_type Varchar) => { String };
1203 (@rust_field_type Int2) => { i16 };
1204 (@rust_field_type Int4) => { i32 };
1205 (@rust_field_type Int8) => { i64 };
1206 (@rust_field_type Real) => { f32 };
1207 (@rust_field_type DoublePrecision) => { f64 };
1208 (@rust_field_type Numeric) => { rust_decimal::Decimal };
1209 (@rust_field_type Bool) => { bool };
1210 (@rust_field_type Date) => { chrono::NaiveDate };
1211 (@rust_field_type Time) => { chrono::NaiveTime };
1212 (@rust_field_type Timestamp) => { chrono::NaiveDateTime };
1213 (@rust_field_type Timestamptz) => { chrono::DateTime<chrono::Utc> };
1214 (@rust_field_type Uuid) => { uuid::Uuid };
1215 (@rust_field_type Json) => { serde_json::Value };
1216 (@rust_field_type Jsonb) => { serde_json::Value };
1217 (@rust_field_type Bytea) => { Vec<u8> };
1218 (@rust_field_type $custom_type:ident) => { $custom_type };
1220}
1221
1222#[macro_export]
1224macro_rules! column_type_mapping {
1225 (Int2) => {
1226 ColumnType::Int2
1227 };
1228 (Int4) => {
1229 ColumnType::Int4
1230 };
1231 (Int8) => {
1232 ColumnType::Int8
1233 };
1234 (Varchar) => {
1235 ColumnType::Varchar(None)
1236 };
1237 (Text) => {
1238 ColumnType::Text
1239 };
1240 (Bool) => {
1241 ColumnType::Bool
1242 };
1243 (Uuid) => {
1244 ColumnType::Uuid
1245 };
1246 (Timestamptz) => {
1247 ColumnType::Timestamptz
1248 };
1249 (Date) => {
1250 ColumnType::Date
1251 };
1252 (Time) => {
1253 ColumnType::Time
1254 };
1255 (Json) => {
1256 ColumnType::Json
1257 };
1258 (Jsonb) => {
1259 ColumnType::Jsonb
1260 };
1261 (Char) => {
1262 ColumnType::Char
1263 };
1264 (Numeric) => {
1265 ColumnType::Numeric(None, None)
1266 };
1267 (Array) => {
1268 ColumnType::Text
1269 };
1270 (Custom($type_name:expr)) => {
1272 ColumnType::Custom($type_name.to_string())
1273 };
1274 (Serial) => {
1276 ColumnType::Serial
1277 };
1278 (BigSerial) => {
1279 ColumnType::BigSerial
1280 };
1281 (SmallSerial) => {
1282 ColumnType::SmallSerial
1283 };
1284}
1285
1286#[macro_export]
1288macro_rules! rust_type_mapping {
1289 (Int2) => { i16 };
1290 (Int4) => { i32 };
1291 (Int8) => { i64 };
1292 (Varchar) => { String };
1293 (Text) => { String };
1294 (Bool) => { bool };
1295 (Uuid) => { uuid::Uuid };
1296 (Timestamptz) => { chrono::DateTime<chrono::Utc> };
1297 (Date) => { chrono::NaiveDate };
1298 (Time) => { chrono::NaiveTime };
1299 (Json) => { serde_json::Value };
1300 (Jsonb) => { serde_json::Value };
1301 (Char) => { char };
1302 (Numeric) => { rust_decimal::Decimal };
1303 (Array) => { Vec<String> };
1304 (Custom($rust_type:ty)) => { $rust_type };
1306 (Serial) => { i32 }; (BigSerial) => { i64 }; (SmallSerial) => { i16 }; }
1311
1312#[macro_export]
1314macro_rules! sql_type_mapping {
1315 (Int2) => {
1316 "SMALLINT"
1317 };
1318 (Int4) => {
1319 "INTEGER"
1320 };
1321 (Int8) => {
1322 "BIGINT"
1323 };
1324 (Varchar) => {
1325 "VARCHAR"
1326 };
1327 (Text) => {
1328 "TEXT"
1329 };
1330 (Bool) => {
1331 "BOOLEAN"
1332 };
1333 (Uuid) => {
1334 "UUID"
1335 };
1336 (Timestamptz) => {
1337 "TIMESTAMPTZ"
1338 };
1339 (Date) => {
1340 "DATE"
1341 };
1342 (Time) => {
1343 "TIME"
1344 };
1345 (Json) => {
1346 "JSON"
1347 };
1348 (Jsonb) => {
1349 "JSONB"
1350 };
1351 (Char) => {
1352 "CHAR"
1353 };
1354 (Numeric) => {
1355 "NUMERIC"
1356 };
1357 (Array) => {
1358 "TEXT[]"
1359 };
1360 (Custom($type_name:expr)) => {
1362 $type_name
1363 };
1364 (Serial) => {
1366 "SERIAL"
1367 };
1368 (BigSerial) => {
1369 "BIGSERIAL"
1370 };
1371 (SmallSerial) => {
1372 "SMALLSERIAL"
1373 };
1374}
1375
1376pub mod sql_safety;
1378pub mod parameter_binding;
1380
1381#[macro_export]
1428macro_rules! event {
1429 (
1431 $schedule:literal;
1432 $command:literal
1433 ) => {
1434 inventory::submit! {
1435 $crate::RegisteredObject($crate::SchemaObject {
1436 kind: "event",
1437 name: concat!("event_", line!()),
1438 ddl: concat!("SELECT cron.schedule('", concat!("event_", line!()), "', '", $schedule, "', $$", $command, "$$)"),
1439 schema: None,
1440 })
1441 }
1442 };
1443
1444 (
1446 #[name = $name:literal]
1447 $schedule:literal;
1448 $command:literal
1449 ) => {
1450 inventory::submit! {
1451 $crate::RegisteredObject($crate::SchemaObject {
1452 kind: "event",
1453 name: $name,
1454 ddl: concat!("SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$)"),
1455 schema: None,
1456 })
1457 }
1458 };
1459
1460 (
1462 #[name = $name:literal]
1463 #[database = $db:literal]
1464 $schedule:literal;
1465 $command:literal
1466 ) => {
1467 inventory::submit! {
1468 $crate::RegisteredObject($crate::SchemaObject {
1469 kind: "event",
1470 name: $name,
1471 ddl: concat!(
1472 "SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
1473 "\nUPDATE cron.job SET database = '", $db, "' WHERE jobname = '", $name, "'"
1474 ),
1475 schema: None,
1476 })
1477 }
1478 };
1479
1480 (
1482 #[name = $name:literal]
1483 #[username = $user:literal]
1484 $schedule:literal;
1485 $command:literal
1486 ) => {
1487 inventory::submit! {
1488 $crate::RegisteredObject($crate::SchemaObject {
1489 kind: "event",
1490 name: $name,
1491 ddl: concat!(
1492 "SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
1493 "\nUPDATE cron.job SET username = '", $user, "' WHERE jobname = '", $name, "'"
1494 ),
1495 schema: None,
1496 })
1497 }
1498 };
1499
1500 (
1502 #[name = $name:literal]
1503 #[ddl = $ddl:literal]
1504 $schedule:literal;
1505 $command:literal
1506 ) => {
1507 inventory::submit! {
1508 $crate::RegisteredObject($crate::SchemaObject {
1509 kind: "event",
1510 name: $name,
1511 ddl: $ddl,
1512 schema: None,
1513 })
1514 }
1515 };
1516
1517 (
1519 #[name = $name:literal]
1520 #[database = $db:literal]
1521 #[username = $user:literal]
1522 $schedule:literal;
1523 $command:literal
1524 ) => {
1525 inventory::submit! {
1526 $crate::RegisteredObject($crate::SchemaObject {
1527 kind: "event",
1528 name: $name,
1529 ddl: concat!(
1530 "SELECT cron.schedule('", $name, "', '", $schedule, "', $$", $command, "$$);",
1531 "\nUPDATE cron.job SET database = '", $db, "' WHERE jobname = '", $name, "';",
1532 "\nUPDATE cron.job SET username = '", $user, "' WHERE jobname = '", $name, "'"
1533 ),
1534 schema: None,
1535 })
1536 }
1537 };
1538}
1539
1540#[macro_export]
1558macro_rules! role {
1559 (
1561 $role_name:ident
1562 ) => {
1563 inventory::submit! {
1564 $crate::RegisteredObject($crate::SchemaObject {
1565 kind: "role",
1566 name: stringify!($role_name),
1567 ddl: concat!("CREATE ROLE \"", stringify!($role_name), "\" NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT NOREPLICATION;"),
1568 schema: None,
1569 })
1570 }
1571 };
1572}
1573
1574#[macro_export]
1592macro_rules! grant {
1593 (
1595 $privilege:ident ON $table:ident TO $grantee:ident
1596 ) => {
1597 inventory::submit! {
1598 $crate::RegisteredObject($crate::SchemaObject {
1599 kind: "grant",
1600 name: concat!(stringify!($privilege), "_on_", stringify!($table), "_to_", stringify!($grantee)),
1601 ddl: concat!("GRANT ", stringify!($privilege), " ON ", stringify!($table), " TO ", stringify!($grantee), ";"),
1602 schema: None,
1603 })
1604 }
1605 };
1606
1607 (
1609 $($privilege:ident),+ ON $table:ident TO $grantee:ident
1610 ) => {
1611 inventory::submit! {
1612 $crate::RegisteredObject($crate::SchemaObject {
1613 kind: "grant",
1614 name: concat!("privileges_on_", stringify!($table), "_to_", stringify!($grantee)),
1615 ddl: concat!(
1616 "GRANT ",
1617 $crate::grant!(@join_privileges $($privilege),+),
1618 " ON ", stringify!($table),
1619 " TO ", stringify!($grantee), ";"
1620 ),
1621 schema: None,
1622 })
1623 }
1624 };
1625
1626 (@join_privileges $first:ident) => { stringify!($first) };
1628 (@join_privileges $first:ident, $($rest:ident),+) => {
1629 concat!(stringify!($first), ", ", $crate::grant!(@join_privileges $($rest),+))
1630 };
1631}