Skip to main content

ignis_db/macros/
mod.rs

1//! Macro system for Ignis
2
3pub mod composite;
4pub mod procedure;
5
6/// Macro to implement IgnisModel trait for a struct
7#[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 to implement Insertable trait for a struct
42#[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                    // Create safe insert builder
54                    let mut builder = SafeInsertBuilder::new(Self::FULL_TABLE_NAME)
55                        .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
56
57                    // Add all fields from the struct
58                    // This will be expanded by the macro system to include all fields
59                    let builder = $crate::impl_insertable!(@add_fields self, builder);
60
61                    // Execute the insert
62                    builder.execute(executor).await
63                }
64            }
65        }
66    };
67
68    // Helper macro to add fields - this will be implemented per struct
69    (@add_fields $self:expr, $builder:expr) => {
70        // Default implementation - override in specific structs
71        $builder
72    };
73}
74
75/// Macro to implement Updatable trait for a struct
76#[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                    // Create safe update builder
88                    let mut builder = SafeUpdateBuilder::new(Self::FULL_TABLE_NAME)
89                        .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
90
91                    // Add all fields from the struct (SET clauses)
92                    // This will be expanded by the macro system to include all fields
93                    let builder = $crate::impl_updatable!(@add_set_fields self, builder);
94
95                    // Add WHERE clause for primary key
96                    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                    // Execute the update
104                    builder.execute(executor).await
105                }
106            }
107        }
108    };
109
110    // Helper macro to add SET fields - this will be implemented per struct
111    (@add_set_fields $self:expr, $builder:expr) => {
112        // Default implementation - override in specific structs
113        $builder
114    };
115
116    // Helper macro to convert BindValue to our internal BindValue
117    (@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 to implement Deletable trait for a struct
135#[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                    // Create safe delete builder
147                    let mut builder = SafeDeleteBuilder::new(Self::FULL_TABLE_NAME)
148                        .map_err(|e| sqlx::Error::Protocol(e.to_string().into()))?;
149
150                    // Add WHERE clause for primary key
151                    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                    // Execute the delete
159                    builder.execute(executor).await
160                }
161            }
162        }
163    };
164
165    // Helper macro to convert BindValue to our internal BindValue
166    (@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 for defining database tables
184///
185/// # Example
186/// ```
187/// use ignis_db::table;
188///
189/// table! {
190///     users (id) {
191///         id -> Int4,
192///         email -> Varchar,
193///         created_at -> Timestamptz,
194///     }
195/// }
196///
197/// // Then use builder pattern for constraints:
198/// users::configure(|t| {
199///     if let Some(email_col) = t.column("email") {
200///         email_col.set_not_null().set_unique();
201///     }
202///     if let Some(name_col) = t.column("name") {
203///         name_col.set_not_null();
204///     }
205///     t
206/// });
207/// ```
208#[macro_export]
209macro_rules! table {
210    // Pattern for composite primary keys with custom types (requires at least 2 PKs)
211    (
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            /// Get the table definition
220            pub fn table() -> Table {
221                let mut table = Table::new(stringify!($table_name));
222
223                // Add columns
224                $(
225                    table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
226                )*
227
228                // Set composite primary key
229                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            /// Get composite primary key columns
236            pub fn pk() -> Vec<String> {
237                vec![stringify!($first_pk).to_string(), $(stringify!($rest_pk).to_string()),+]
238            }
239
240            $(
241                /// Get the $col_name column
242                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            /// Get table metadata
249            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            /// Configure table constraints using builder pattern
263            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            /// Get typed columns for type-safe queries
273            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            /// Start a type-safe query
288            pub fn typed_query() -> $crate::dsl::TypedQuery {
289                $crate::dsl::TypedQuery::new().from_table(table())
290            }
291        }
292
293        // Register the table in the inventory system
294        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    // Pattern for single primary key with custom types
305    (
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            /// Get the table definition
314            pub fn table() -> Table {
315                let mut table = Table::new(stringify!($table_name));
316
317                // Add columns
318                $(
319                    table = table.add_column(Column::new(stringify!($col_name), $crate::table!(@resolve_column_type $col_type)));
320                )*
321
322                // Set primary key
323                table = table.set_primary_key(stringify!($pk));
324
325                table
326            }
327
328            /// Get the primary key column
329            pub fn pk() -> $crate::dsl::Column<i32> {
330                $crate::dsl::Column::new(stringify!($pk))
331                    .from_table(stringify!($table_name))
332            }
333
334            $(
335                /// Get the $col_name column
336                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            /// Table metadata
343            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            /// Configure table constraints using builder pattern
357            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            /// Get typed columns for type-safe queries
367            pub struct Columns;
368
369            impl Columns {
370                $(
371                    /// Get typed column for $col_name
372                    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            /// Start a type-safe query
383            pub fn typed_query() -> $crate::dsl::TypedQuery {
384                $crate::dsl::TypedQuery::new().from_table(table())
385            }
386        }
387
388        // Register the table in the inventory system
389        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 - handles both simple and Custom types
400    (@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    // Handle string literals as custom type names (simplified syntax)
403    (@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
404
405    // Delegate to shared type mappings
406    (@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    // Generate DDL columns string
413    (@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    // Generate primary key columns string for DDL
438    (@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    // Generate primary key string for metadata
449    (@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 for defining database views
461///
462/// # Example
463/// ```
464/// use ignis_db::view;
465///
466/// view! {
467///     active_users (id) {
468///         id -> Int4,
469///         name -> Varchar,
470///         email -> Varchar,
471///     }
472/// }
473///
474/// // With custom DDL:
475/// view! {
476///     user_stats (id) {
477///         id -> Int4,
478///         post_count -> Int4,
479///         last_active -> Timestamptz,
480///     }
481/// }
482///
483/// // Then use builder pattern for complex views:
484/// user_stats::configure(|v| {
485///     v.set_ddl("CREATE VIEW user_stats AS SELECT u.id, COUNT(p.id) as post_count, MAX(p.created_at) as last_active FROM users u LEFT JOIN posts p ON u.id = p.user_id GROUP BY u.id");
486///     v
487/// });
488/// ```
489#[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            /// Get the view definition
500            pub fn view() -> View {
501                let mut view = View::new(stringify!($view_name));
502
503                // Add columns
504                $(
505                    view = view.add_column(Column::new(stringify!($col_name), $crate::view!(@column_type $col_type)));
506                )*
507
508                view
509            }
510
511            /// Get the primary key column (for consistency with table! macro)
512            pub fn pk() -> $crate::dsl::Column<i32> {
513                $crate::dsl::Column::new(stringify!($pk))
514                    .from_table(stringify!($view_name))
515            }
516
517            $(
518                /// Get the $col_name column
519                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            /// Configure view using builder pattern
526            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            /// Create a materialized view with the given configuration
536            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            /// Get typed columns for type-safe queries
547            pub struct Columns;
548
549            impl Columns {
550                $(
551                    /// Get typed column for $col_name
552                    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            /// Start a type-safe query
563            pub fn typed_query() -> $crate::dsl::TypedQuery {
564                $crate::dsl::TypedQuery::new().from_view(view())
565            }
566        }
567
568        // Register the view in the inventory system
569        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 - handles both simple and Custom types
580    (@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    // Handle string literals as custom type names (simplified syntax)
583    (@resolve_column_type $type_name:expr) => { $crate::column_type_mapping!(Custom($type_name)) };
584
585    // Delegate to shared type mappings
586    (@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    // Generate DDL columns string
593    (@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/// Enhanced macro for creating database indexes with composite type support
605///
606/// # Example
607/// ```rust
608/// use ignis_db::index;
609///
610/// // Basic index on regular columns
611/// index! {
612///     users_email_idx (users, email)
613/// }
614///
615/// // Composite index with multiple columns
616/// index! {
617///     users_name_status_idx (users, first_name, last_name, status)
618/// }
619/// ```
620#[macro_export]
621macro_rules! index {
622    // Basic index with simple column list (backward compatibility)
623    (
624        $index_name:ident ($table_name:ident, $($col_name:ident),* $(,)?)
625    ) => {
626        pub mod $index_name {
627            use $crate::schema::{IndexMeta, IndexType};
628
629            /// Get the index metadata
630            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            /// Get the index name
643            pub fn name() -> &'static str {
644                stringify!($index_name)
645            }
646
647            /// Get the table name
648            pub fn table() -> &'static str {
649                stringify!($table_name)
650            }
651
652            /// Get the column names
653            pub fn columns() -> &'static [&'static str] {
654                &[$(stringify!($col_name)),*]
655            }
656
657            /// Get composite fields (empty for basic index)
658            pub fn composite_fields() -> Vec<&'static str> {
659                vec![]
660            }
661
662            /// Get index expression (None for column-based index)
663            pub fn expression() -> Option<&'static str> {
664                None
665            }
666        }
667
668        // Register the index in the inventory system
669        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    // Enhanced index with column array and options
680    (
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            /// Get the index metadata
693            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            /// Get the index name
706            pub fn name() -> &'static str {
707                stringify!($index_name)
708            }
709
710            /// Get the table name
711            pub fn table() -> &'static str {
712                stringify!($table_name)
713            }
714
715            /// Get the column specifications
716            pub fn columns() -> &'static [&'static str] {
717                &[$crate::index!(@extract_columns $($col_spec),*)]
718            }
719
720            /// Get composite fields
721            pub fn composite_fields() -> Vec<&'static str> {
722                vec![$($($composite_field),*)?]
723            }
724
725            /// Get WHERE clause if any
726            pub fn where_clause() -> Option<&'static str> {
727                $($crate::index!(@optional_string $where_clause))?
728            }
729
730            /// Get index expression (None for column-based index)
731            pub fn expression() -> Option<&'static str> {
732                None
733            }
734        }
735
736        // Register the index in the inventory system
737        inventory::submit! {
738            $crate::RegisteredObject($crate::SchemaObject {
739                kind: "index",
740                name: stringify!($index_name),
741                ddl: "", // Will be generated dynamically
742                schema: None,
743            })
744        }
745    };
746
747    // Functional index with expressions
748    (
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            /// Get the index metadata
761            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: &[], // Empty for expression-based index
770                }
771            }
772
773            /// Get the index name
774            pub fn name() -> &'static str {
775                stringify!($index_name)
776            }
777
778            /// Get the table name
779            pub fn table() -> &'static str {
780                stringify!($table_name)
781            }
782
783            /// Get the column names (empty for expression index)
784            pub fn columns() -> &'static [&'static str] {
785                &[]
786            }
787
788            /// Get composite fields (empty for expression index)
789            pub fn composite_fields() -> Vec<&'static str> {
790                vec![]
791            }
792
793            /// Get index expression
794            pub fn expression() -> Option<&'static str> {
795                Some($expression)
796            }
797
798            /// Get WHERE clause if any
799            pub fn where_clause() -> Option<&'static str> {
800                $($crate::index!(@optional_string $where_clause))?
801            }
802        }
803
804        // Register the index in the inventory system
805        inventory::submit! {
806            $crate::RegisteredObject($crate::SchemaObject {
807                kind: "index",
808                name: stringify!($index_name),
809                ddl: "", // Will be generated dynamically
810                schema: None,
811            })
812        }
813    };
814
815    // Helper macros
816
817    // Extract column names from various column specifications
818    (@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    // Boolean value helper
828    (@bool_value) => { false };
829    (@bool_value true) => { true };
830    (@bool_value false) => { false };
831
832    // Index type helper
833    (@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 helper
842    (@optional_string $value:expr) => { Some($value) };
843
844    // Legacy column helper for backward compatibility
845    (@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 for defining PostgreSQL triggers
857///
858/// # Example
859/// ```rust
860/// use ignis_db::trigger;
861///
862/// // Simple audit trigger
863/// trigger! {
864///     audit_users_trigger (users) -> audit_function {
865///         timing: after,
866///         events: [insert, update, delete],
867///         orientation: row
868///     }
869/// }
870///
871/// // Complex trigger with conditions and composite type support
872/// trigger! {
873///     validate_address_trigger (users) -> validate_address_func {
874///         timing: before,
875///         events: [insert, update],
876///         orientation: row,
877///         condition: "NEW.address IS NOT NULL",
878///         update_columns: [address, phone],
879///         composite_fields: ["address.street", "address.city"]
880///     }
881/// }
882/// ```
883#[macro_export]
884macro_rules! trigger {
885    // Basic trigger definition
886    (
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            /// Get the trigger definition
900            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            /// Get trigger metadata
919            pub fn name() -> &'static str {
920                stringify!($trigger_name)
921            }
922
923            /// Get table name
924            pub fn table() -> &'static str {
925                stringify!($table_name)
926            }
927
928            /// Get function name
929            pub fn function() -> &'static str {
930                stringify!($function_name)
931            }
932
933            /// Get composite fields if any
934            pub fn composite_fields() -> Vec<&'static str> {
935                vec![$($($composite_field),*)?]
936            }
937        }
938
939        // Register trigger in inventory system
940        inventory::submit! {
941            $crate::RegisteredObject($crate::SchemaObject {
942                kind: "trigger",
943                name: stringify!($trigger_name),
944                ddl: "", // Will be generated dynamically
945                schema: None,
946            })
947        }
948    };
949
950    // Trigger with schema support
951    (
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            /// Get the trigger definition
965            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            /// Get trigger metadata
987            pub fn name() -> &'static str {
988                stringify!($trigger_name)
989            }
990
991            /// Get table name
992            pub fn table() -> &'static str {
993                stringify!($table_name)
994            }
995
996            /// Get function name
997            pub fn function() -> &'static str {
998                stringify!($function_name)
999            }
1000
1001            /// Get composite fields if any
1002            pub fn composite_fields() -> Vec<&'static str> {
1003                vec![$($($composite_field),*)?]
1004            }
1005        }
1006
1007        // Register trigger in inventory system
1008        inventory::submit! {
1009            $crate::RegisteredObject($crate::SchemaObject {
1010                kind: "trigger",
1011                name: stringify!($trigger_name),
1012                ddl: "", // Will be generated dynamically
1013                schema: Some(stringify!($schema)),
1014            })
1015        }
1016    };
1017
1018    // Helper macros for timing mapping
1019    (@timing before) => { TriggerTiming::Before };
1020    (@timing after) => { TriggerTiming::After };
1021    (@timing instead_of) => { TriggerTiming::InsteadOf };
1022
1023    // Helper macros for event mapping
1024    (@event insert) => { TriggerEvent::Insert };
1025    (@event update) => { TriggerEvent::Update };
1026    (@event delete) => { TriggerEvent::Delete };
1027    (@event truncate) => { TriggerEvent::Truncate };
1028
1029    // Helper macros for orientation mapping
1030    (@orientation row) => { TriggerOrientation::Row };
1031    (@orientation statement) => { TriggerOrientation::Statement };
1032}
1033
1034/// Macro for defining PostgreSQL composite types
1035///
1036/// # Example
1037/// ```rust
1038/// use ignis_db::composite;
1039///
1040/// composite! {
1041///     Address {
1042///         street: Text,
1043///         city: Text,
1044///         state: Varchar,
1045///         zipcode: Varchar,
1046///     }
1047/// }
1048///
1049/// composite! {
1050///     Point {
1051///         x: Real,
1052///         y: Real,
1053///     }
1054/// }
1055/// ```
1056#[macro_export]
1057macro_rules! composite {
1058    (
1059        $type_name:ident {
1060            $($field_name:ident: $field_type:ident),* $(,)?
1061        }
1062    ) => {
1063        // Generate both the struct and associated functions
1064        #[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            /// Get the composite type definition
1071            pub fn composite_type() -> $crate::schema::CompositeType {
1072                use $crate::schema::{CompositeType, CompositeField};
1073                // Convert PascalCase to snake_case for PostgreSQL compatibility
1074                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 // not nullable by default
1092                    );
1093                )*
1094
1095                composite
1096            }
1097
1098            /// Get the composite type name
1099            pub fn type_name() -> String {
1100                // Convert PascalCase to snake_case for PostgreSQL compatibility
1101                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            /// Get a registry of composite types (returns empty for now - placeholder)
1115            pub fn registry() -> Vec<$crate::schema::CompositeType> {
1116                vec![Self::composite_type()]
1117            }
1118
1119            /// Generate CREATE TYPE DDL for this composite type
1120            pub fn generate_create_ddl() -> String {
1121                Self::composite_type().generate_create_ddl()
1122            }
1123
1124            /// Get the PostgreSQL type name for this composite type
1125            pub fn pg_type_name() -> &'static str {
1126                // For now, return a hardcoded name based on the type
1127                // This is a temporary fix until we can implement proper const evaluation
1128                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            /// Generate DROP TYPE DDL for this composite type
1145            pub fn generate_drop_ddl() -> String {
1146                format!("DROP TYPE IF EXISTS \"{}\" CASCADE;", Self::pg_type_name())
1147            }
1148        }
1149
1150        // Implement BindValue conversion for the composite type
1151        impl From<$type_name> for $crate::macros::parameter_binding::BindValue {
1152            fn from(value: $type_name) -> Self {
1153                // Serialize to JSON for database binding
1154                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, // Fallback
1157                }
1158            }
1159        }
1160
1161        // TODO: Vec<CompositeType> support requires implementing From<Vec<T>> for BindValue
1162        // This violates orphan rules when composite types are defined outside ignis-db crate
1163        // For now, users must use arrays in raw SQL or implement their own conversion
1164
1165        // Register composite type in inventory system
1166        inventory::submit! {
1167            $crate::RegisteredObject($crate::SchemaObject {
1168                kind: "composite_type",
1169                name: stringify!($type_name),
1170                ddl: "", // Will be generated dynamically
1171                schema: None,
1172            })
1173        }
1174    };
1175
1176    // Helper macro for SQL type mapping
1177    (@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    // For custom/composite types, use the type name (will be converted later)
1198    (@sql_type $custom_type:ident) => { stringify!($custom_type) };
1199
1200    // Rust field type mapping for composite fields
1201    (@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    // For custom/composite types, use the type name directly
1219    (@rust_field_type $custom_type:ident) => { $custom_type };
1220}
1221
1222/// Shared column type mappings to eliminate duplication
1223#[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 types (composite types, enums, etc.)
1271    (Custom($type_name:expr)) => {
1272        ColumnType::Custom($type_name.to_string())
1273    };
1274    // Auto-increment types
1275    (Serial) => {
1276        ColumnType::Serial
1277    };
1278    (BigSerial) => {
1279        ColumnType::BigSerial
1280    };
1281    (SmallSerial) => {
1282        ColumnType::SmallSerial
1283    };
1284}
1285
1286/// Shared Rust type mappings
1287#[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 types require explicit Rust type specification
1305    (Custom($rust_type:ty)) => { $rust_type };
1306    // Auto-increment types map to their underlying Rust types
1307    (Serial) => { i32 };        // SERIAL is essentially INTEGER with auto-increment
1308    (BigSerial) => { i64 };     // BIGSERIAL is essentially BIGINT with auto-increment
1309    (SmallSerial) => { i16 };   // SMALLSERIAL is essentially SMALLINT with auto-increment
1310}
1311
1312/// Shared SQL type mappings for DDL
1313#[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 types use the provided type name directly
1361    (Custom($type_name:expr)) => {
1362        $type_name
1363    };
1364    // Auto-increment types
1365    (Serial) => {
1366        "SERIAL"
1367    };
1368    (BigSerial) => {
1369        "BIGSERIAL"
1370    };
1371    (SmallSerial) => {
1372        "SMALLSERIAL"
1373    };
1374}
1375
1376// SQL Safety module for injection prevention
1377pub mod sql_safety;
1378// Parameter Binding Safety module for CRUD operations
1379pub mod parameter_binding;
1380
1381/// Event macro for pg_cron scheduled jobs
1382///
1383/// Creates pg_cron scheduled jobs with Rust syntax
1384///
1385/// # Basic Usage
1386///
1387/// ```rust
1388/// use ignis_db::event;
1389///
1390/// // Simple cron schedule
1391/// event! {
1392///     "0 0 * * *";
1393///     "VACUUM ANALYZE;"
1394/// }
1395///
1396/// // Named event
1397/// event! {
1398///     #[name = "daily_cleanup"]
1399///     "0 3 * * *";
1400///     "DELETE FROM logs WHERE created_at < NOW() - INTERVAL '30 days';"
1401/// }
1402///
1403/// // Event with database setting
1404/// event! {
1405///     #[name = "maintenance"]
1406///     #[database = "mydb"]
1407///     "0 2 * * 0";
1408///     "VACUUM ANALYZE;"
1409/// }
1410///
1411/// // Event with username setting
1412/// event! {
1413///     #[name = "reports"]
1414///     #[username = "reporter"]
1415///     "0 9 * * 1";
1416///     "SELECT generate_weekly_report();"
1417/// }
1418///
1419/// // Custom DDL override
1420/// event! {
1421///     #[name = "custom_job"]
1422///     #[ddl = "SELECT cron.schedule('custom_job', '*/5 * * * *', $$SELECT status();$$)"]
1423///     "*/5 * * * *";
1424///     "SELECT status();"
1425/// }
1426/// ```
1427#[macro_export]
1428macro_rules! event {
1429    // Pattern 1: Simple cron schedule with no attributes
1430    (
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    // Pattern 2: Named event only
1445    (
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    // Pattern 3: Named event with database
1461    (
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    // Pattern 4: Named event with username
1481    (
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    // Pattern 5: Named event with custom DDL
1501    (
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    // Pattern 6: Named event with both database and username
1518    (
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/// Role definition macro
1541///
1542/// # Examples
1543///
1544/// ```rust
1545/// use ignis_db::role;
1546///
1547/// // Basic role
1548/// role! {
1549///     app_user
1550/// }
1551///
1552/// // Role with attributes
1553/// role! {
1554///     admin_user
1555/// }
1556/// ```
1557#[macro_export]
1558macro_rules! role {
1559    // Pattern 1: Basic role
1560    (
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/// Grant definition macro
1575///
1576/// # Examples
1577///
1578/// ```rust
1579/// use ignis_db::grant;
1580///
1581/// // Basic grant
1582/// grant! {
1583///     SELECT ON users TO app_user
1584/// }
1585///
1586/// // Multiple privileges
1587/// grant! {
1588///     SELECT, INSERT ON users TO app_user
1589/// }
1590/// ```
1591#[macro_export]
1592macro_rules! grant {
1593    // Pattern 1: Single privilege on table
1594    (
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    // Pattern 2: Multiple privileges on table
1608    (
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    // Helper to join multiple privileges
1627    (@join_privileges $first:ident) => { stringify!($first) };
1628    (@join_privileges $first:ident, $($rest:ident),+) => {
1629        concat!(stringify!($first), ", ", $crate::grant!(@join_privileges $($rest),+))
1630    };
1631}