Skip to main content

ignis_db/schema/
mod.rs

1//! Schema definitions for Ignis
2
3use serde::{Deserialize, Serialize};
4
5pub mod composite;
6pub mod procedure;
7pub mod trigger;
8
9use crate::IgnisObject;
10pub use composite::{CompositeField, CompositeType, CompositeTypeRegistry};
11pub use procedure::{
12    FunctionSecurity, FunctionVolatility, ParameterMode, ProcedureLanguage, ProcedureParameter,
13    ProcedureRegistry, StoredFunction, StoredProcedure,
14};
15pub use trigger::{Trigger, TriggerEvent, TriggerOrientation, TriggerReferencing, TriggerTiming};
16
17/// Escape a SQL identifier to prevent SQL injection
18/// This function properly escapes PostgreSQL identifiers
19fn escape_sql_identifier(identifier: &str) -> String {
20    // PostgreSQL identifiers are case-sensitive when quoted
21    // and can contain any character except null bytes
22    // We'll use double quotes for safety
23    format!("\"{}\"", identifier.replace("\"", "\"\"")).to_lowercase()
24}
25
26/// Represents a PostgreSQL sequence
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub struct Sequence {
29    pub name: String,
30    pub schema: Option<String>,
31    pub data_type: String,
32    pub start_value: Option<i64>,
33    pub minimum_value: Option<i64>,
34    pub maximum_value: Option<i64>,
35    pub increment: Option<i64>,
36    pub cycle: Option<bool>,
37    pub cache: Option<i64>,
38    pub owner: Option<String>,
39    pub comment: Option<String>,
40}
41
42impl Sequence {
43    /// Create a new sequence
44    pub fn new(name: impl Into<String>, data_type: impl Into<String>) -> Self {
45        Self {
46            name: name.into(),
47            schema: None,
48            data_type: data_type.into(),
49            start_value: None,
50            minimum_value: None,
51            maximum_value: None,
52            increment: None,
53            cycle: None,
54            cache: None,
55            owner: None,
56            comment: None,
57        }
58    }
59
60    /// Set schema
61    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
62        self.schema = Some(schema.into());
63        self
64    }
65
66    /// Set start value
67    pub fn with_start_value(mut self, start: i64) -> Self {
68        self.start_value = Some(start);
69        self
70    }
71
72    /// Set minimum value
73    pub fn with_minimum_value(mut self, min: i64) -> Self {
74        self.minimum_value = Some(min);
75        self
76    }
77
78    /// Set maximum value
79    pub fn with_maximum_value(mut self, max: i64) -> Self {
80        self.maximum_value = Some(max);
81        self
82    }
83
84    /// Set increment
85    pub fn with_increment(mut self, increment: i64) -> Self {
86        self.increment = Some(increment);
87        self
88    }
89
90    /// Set cycle behavior
91    pub fn with_cycle(mut self, cycle: bool) -> Self {
92        self.cycle = Some(cycle);
93        self
94    }
95
96    /// Set cache size
97    pub fn with_cache(mut self, cache: i64) -> Self {
98        self.cache = Some(cache);
99        self
100    }
101
102    /// Set owner
103    pub fn with_owner(mut self, owner: impl Into<String>) -> Self {
104        self.owner = Some(owner.into());
105        self
106    }
107
108    /// Set comment
109    pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
110        self.comment = Some(comment.into());
111        self
112    }
113
114    /// Get the fully qualified sequence name
115    pub fn qualified_name(&self) -> String {
116        if let Some(ref schema) = self.schema {
117            format!("\"{}\".\"{}\"", schema, self.name)
118        } else {
119            format!("\"{}\"", self.name)
120        }
121    }
122
123    /// Generate CREATE SEQUENCE DDL
124    pub fn generate_create_ddl(&self) -> String {
125        let mut ddl = format!("CREATE SEQUENCE {}", self.qualified_name());
126
127        use std::fmt::Write;
128        write!(ddl, " AS {}", self.data_type).unwrap();
129
130        if let Some(start) = self.start_value {
131            write!(ddl, " START WITH {}", start).unwrap();
132        }
133
134        if let Some(min) = self.minimum_value {
135            write!(ddl, " MINVALUE {}", min).unwrap();
136        }
137
138        if let Some(max) = self.maximum_value {
139            write!(ddl, " MAXVALUE {}", max).unwrap();
140        }
141
142        if let Some(increment) = self.increment {
143            write!(ddl, " INCREMENT BY {}", increment).unwrap();
144        }
145
146        if let Some(cycle) = self.cycle {
147            if cycle {
148                ddl.push_str(" CYCLE");
149            } else {
150                ddl.push_str(" NO CYCLE");
151            }
152        }
153
154        if let Some(cache) = self.cache {
155            ddl.push_str(&format!(" CACHE {}", cache));
156        }
157
158        if let Some(ref owner) = self.owner {
159            ddl.push_str(&format!(" OWNED BY {}", owner));
160        }
161
162        ddl.push(';');
163
164        if let Some(ref comment) = self.comment {
165            ddl.push_str(&format!(
166                "\nCOMMENT ON SEQUENCE {} IS '{}';",
167                self.qualified_name(),
168                comment
169            ));
170        }
171
172        ddl
173    }
174}
175
176/// Represents a database table
177#[derive(Debug, Clone, PartialEq)]
178pub struct Table {
179    pub name: String,
180    pub schema: Option<String>,
181    pub columns: Vec<Column>,
182    pub primary_key: Option<String>,
183    pub constraints: Vec<Constraint>,
184    pub indexes: Vec<Index>,
185    pub rls_enabled: bool,
186    pub policies: Vec<Policy>,
187}
188
189/// Represents a database view
190#[derive(Debug, Clone, PartialEq)]
191pub struct View {
192    pub name: String,
193    pub schema: Option<String>,
194    pub columns: Vec<Column>,
195    pub ddl: Option<String>,
196    pub materialized: bool,
197    pub refresh_strategy: Option<RefreshStrategy>,
198    pub dependencies: Vec<String>,
199    pub indexes: Vec<Index>,
200}
201
202/// Represents a database event (pg_cron job)
203#[derive(Debug, Clone, PartialEq)]
204pub struct Event {
205    pub name: String,
206    pub schema: Option<String>,
207    pub schedule: String,
208    pub command: String,
209    pub database: Option<String>,
210    pub username: Option<String>,
211    pub ddl: String,
212    pub enabled: bool,
213}
214
215impl Event {
216    /// Create a new event with the given name, schedule, and command
217    pub fn new(
218        name: impl Into<String>,
219        schedule: impl Into<String>,
220        command: impl Into<String>,
221    ) -> Self {
222        let name = name.into();
223        let schedule = schedule.into();
224        let command = command.into();
225
226        // Generate default DDL
227        let ddl = format!(
228            "SELECT cron.schedule('{}', '{}', $${}$$)",
229            escape_sql_identifier(&name),
230            escape_sql_identifier(&schedule),
231            command
232        );
233
234        Self {
235            name,
236            schema: None,
237            schedule,
238            command,
239            database: None,
240            username: None,
241            ddl,
242            enabled: true,
243        }
244    }
245
246    /// Create a new event with schema
247    pub fn with_schema(
248        schema: impl Into<String>,
249        name: impl Into<String>,
250        schedule: impl Into<String>,
251        command: impl Into<String>,
252    ) -> Self {
253        let mut event = Self::new(name, schedule, command);
254        event.schema = Some(schema.into());
255        event
256    }
257
258    /// Set the target database for the event
259    pub fn with_database(mut self, database: impl Into<String>) -> Self {
260        self.database = Some(database.into());
261        self
262    }
263
264    /// Set the username for the event execution
265    pub fn with_username(mut self, username: impl Into<String>) -> Self {
266        self.username = Some(username.into());
267        self
268    }
269
270    /// Set custom DDL for the event
271    pub fn with_custom_ddl(mut self, ddl: impl Into<String>) -> Self {
272        self.ddl = ddl.into();
273        self
274    }
275
276    /// Set whether the event is enabled
277    pub fn with_enabled(mut self, enabled: bool) -> Self {
278        self.enabled = enabled;
279        self
280    }
281
282    /// Generate the DDL for creating this event
283    pub fn generate_ddl(&self) -> String {
284        if self.ddl
285            != format!(
286                "SELECT cron.schedule('{}', '{}', $${}$$)",
287                escape_sql_identifier(&self.name),
288                escape_sql_identifier(&self.schedule),
289                self.command
290            )
291        {
292            // Custom DDL provided
293            return self.ddl.clone();
294        }
295
296        let mut ddl = self.ddl.clone();
297
298        // Add database update if specified
299        if let Some(db) = &self.database {
300            ddl.push_str(&format!(
301                "\nUPDATE cron.job SET database = '{}' WHERE jobname = '{}'",
302                db,
303                escape_sql_identifier(&self.name)
304            ));
305        }
306
307        // Add username update if specified
308        if let Some(user) = &self.username {
309            ddl.push_str(&format!(
310                "\nUPDATE cron.job SET username = '{}' WHERE jobname = '{}'",
311                user,
312                escape_sql_identifier(&self.name)
313            ));
314        }
315
316        ddl
317    }
318
319    /// Generate the DDL for dropping this event
320    pub fn generate_drop_ddl(&self) -> String {
321        format!(
322            "SELECT cron.unschedule('{}')",
323            escape_sql_identifier(&self.name)
324        )
325    }
326}
327
328/// Refresh strategy for materialized views
329#[derive(Debug, Clone, PartialEq)]
330pub enum RefreshStrategy {
331    /// Refresh the view concurrently (allows reads during refresh)
332    Concurrent,
333    /// Refresh the view with a lock (blocks reads during refresh)
334    Locked,
335    /// Refresh the view automatically when dependencies change
336    Auto,
337    /// Manual refresh only
338    Manual,
339}
340
341impl Table {
342    /// Create a new table with the given name
343    pub fn new(name: impl Into<String>) -> Self {
344        Self {
345            name: name.into(),
346            schema: None,
347            columns: Vec::new(),
348            primary_key: None,
349            constraints: Vec::new(),
350            indexes: Vec::new(),
351            rls_enabled: false,
352            policies: Vec::new(),
353        }
354    }
355
356    /// Create a new table with schema
357    pub fn with_schema(schema: impl Into<String>, name: impl Into<String>) -> Self {
358        Self {
359            name: name.into(),
360            schema: Some(schema.into()),
361            columns: Vec::new(),
362            primary_key: None,
363            constraints: Vec::new(),
364            indexes: Vec::new(),
365            rls_enabled: false,
366            policies: Vec::new(),
367        }
368    }
369
370    /// Add a column to the table
371    pub fn add_column(mut self, column: Column) -> Self {
372        self.columns.push(column);
373        self
374    }
375
376    /// Set the primary key column
377    pub fn set_primary_key(mut self, pk_column: impl Into<String>) -> Self {
378        self.primary_key = Some(pk_column.into());
379        self
380    }
381
382    /// Add a constraint to the table
383    pub fn add_constraint(mut self, constraint: Constraint) -> Self {
384        self.constraints.push(constraint);
385        self
386    }
387
388    /// Add an index to the table
389    pub fn add_index(mut self, index: Index) -> Self {
390        self.indexes.push(index);
391        self
392    }
393
394    /// Get a mutable reference to a column for configuration
395    pub fn column(&mut self, name: &str) -> Option<&mut Column> {
396        self.columns.iter_mut().find(|col| col.name == name)
397    }
398
399    /// Generate the DDL for creating this table
400    pub fn generate_ddl(&self) -> String {
401        let mut ddl = String::new();
402
403        // Table name with schema
404        let full_name = if let Some(ref schema) = self.schema {
405            format!("\"{}\".\"{}\"", schema, self.name)
406        } else {
407            format!("\"{}\"", self.name)
408        };
409
410        use std::fmt::Write;
411        write!(ddl, "CREATE TABLE {} (\n", full_name).unwrap();
412
413        // Columns
414        let column_defs: Vec<String> = self.columns.iter().map(|col| col.to_sql()).collect();
415        ddl.push_str(&column_defs.join(",\n"));
416
417        // Primary key
418        if let Some(ref pk) = self.primary_key {
419            write!(ddl, ",\n    PRIMARY KEY (\"{}\")", pk).unwrap();
420        }
421
422        // Constraints
423        for constraint in &self.constraints {
424            ddl.push_str(&format!(",\n    {}", constraint.to_sql()));
425        }
426
427        ddl.push_str("\n);");
428
429        // Indexes
430        for index in &self.indexes {
431            ddl.push_str(&format!("\n{}", index.to_sql()));
432        }
433
434        ddl
435    }
436
437    /// Enable Row-Level Security on this table
438    pub fn enable_rls(mut self) -> Self {
439        self.rls_enabled = true;
440        self
441    }
442
443    /// Disable Row-Level Security on this table
444    pub fn disable_rls(mut self) -> Self {
445        self.rls_enabled = false;
446        self
447    }
448
449    /// Add a policy to this table
450    pub fn add_policy(mut self, policy: Policy) -> Self {
451        self.policies.push(policy);
452        self
453    }
454
455    /// Add multiple policies to this table
456    pub fn add_policies(mut self, policies: Vec<Policy>) -> Self {
457        self.policies.extend(policies);
458        self
459    }
460
461    /// Check if RLS is enabled
462    pub fn is_rls_enabled(&self) -> bool {
463        self.rls_enabled
464    }
465
466    /// Get all policies for this table
467    pub fn policies(&self) -> &[Policy] {
468        &self.policies
469    }
470
471    /// Generate RLS DDL for this table
472    pub fn generate_rls_ddl(&self) -> String {
473        let mut ddl = String::new();
474
475        if self.rls_enabled {
476            let full_name = if let Some(ref schema) = self.schema {
477                format!("\"{}\".\"{}\"", schema, self.name)
478            } else {
479                format!("\"{}\"", self.name)
480            };
481
482            ddl.push_str(&format!(
483                "ALTER TABLE {} ENABLE ROW LEVEL SECURITY;\n",
484                full_name
485            ));
486
487            for policy in &self.policies {
488                ddl.push_str(&format!("{}\n", policy.to_sql()));
489            }
490        }
491
492        ddl
493    }
494}
495
496impl View {
497    /// Create a new view
498    pub fn new(name: impl Into<String>) -> Self {
499        Self {
500            name: name.into(),
501            schema: None,
502            columns: Vec::new(),
503            ddl: None,
504            materialized: false,
505            refresh_strategy: None,
506            dependencies: Vec::new(),
507            indexes: Vec::new(),
508        }
509    }
510
511    /// Create a new view with schema
512    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
513        self.schema = Some(schema.into());
514        self
515    }
516
517    /// Add a column to the view
518    pub fn add_column(mut self, column: Column) -> Self {
519        self.columns.push(column);
520        self
521    }
522
523    /// Set the DDL for the view
524    pub fn with_ddl(mut self, ddl: impl Into<String>) -> Self {
525        self.ddl = Some(ddl.into());
526        self
527    }
528
529    /// Set the schema (in-place)
530    pub fn set_schema(&mut self, schema: impl Into<String>) -> &mut Self {
531        self.schema = Some(schema.into());
532        self
533    }
534
535    /// Add a column (in-place)
536    pub fn add_column_mut(&mut self, column: Column) -> &mut Self {
537        self.columns.push(column);
538        self
539    }
540
541    /// Set the DDL (in-place)
542    pub fn set_ddl(&mut self, ddl: impl Into<String>) -> &mut Self {
543        self.ddl = Some(ddl.into());
544        self
545    }
546
547    /// Set the view as materialized
548    pub fn set_materialized(&mut self, materialized: bool) -> &mut Self {
549        self.materialized = materialized;
550        self
551    }
552
553    /// Set the refresh strategy for materialized views
554    pub fn set_refresh_strategy(&mut self, strategy: RefreshStrategy) -> &mut Self {
555        self.refresh_strategy = Some(strategy);
556        self
557    }
558
559    /// Add a dependency (table or view that this view depends on)
560    pub fn add_dependency(&mut self, dependency: impl Into<String>) -> &mut Self {
561        self.dependencies.push(dependency.into());
562        self
563    }
564
565    /// Set multiple dependencies at once
566    pub fn set_dependencies(&mut self, dependencies: Vec<String>) -> &mut Self {
567        self.dependencies = dependencies;
568        self
569    }
570
571    /// Add an index to the view (useful for materialized views)
572    pub fn add_index(&mut self, name: impl Into<String>, columns: Vec<String>) -> &mut Self {
573        let index = Index::new(name.into(), columns, false);
574        self.indexes.push(index);
575        self
576    }
577
578    /// Add a unique index to the view
579    pub fn add_unique_index(&mut self, name: impl Into<String>, columns: Vec<String>) -> &mut Self {
580        let index = Index::new(name.into(), columns, true);
581        self.indexes.push(index);
582        self
583    }
584
585    /// Generate the DDL for creating this view
586    pub fn generate_ddl(&self) -> String {
587        if let Some(ref ddl) = self.ddl {
588            ddl.clone()
589        } else {
590            // Generate a basic CREATE VIEW if no DDL is provided
591            let mut sql = String::new();
592
593            // View name with schema
594            let full_name = if let Some(ref schema) = self.schema {
595                format!("\"{}\".\"{}\"", schema, self.name)
596            } else {
597                format!("\"{}\"", self.name)
598            };
599
600            // Materialized or regular view
601            if self.materialized {
602                sql.push_str(&format!("CREATE MATERIALIZED VIEW {}", full_name));
603            } else {
604                sql.push_str(&format!("CREATE VIEW {}", full_name));
605            }
606
607            sql.push_str(" AS SELECT ");
608
609            // Columns
610            let column_names: Vec<String> = self
611                .columns
612                .iter()
613                .map(|col| format!("\"{}\"", col.name))
614                .collect();
615            sql.push_str(&column_names.join(", "));
616
617            sql.push_str(" FROM /* table_name */;");
618
619            // Add indexes for materialized views
620            if self.materialized && !self.indexes.is_empty() {
621                sql.push('\n');
622                for index in &self.indexes {
623                    sql.push_str(&index.to_sql());
624                    sql.push('\n');
625                }
626            }
627
628            sql
629        }
630    }
631
632    /// Generate the DDL for refreshing a materialized view
633    pub fn generate_refresh_ddl(&self) -> Option<String> {
634        if !self.materialized {
635            return None;
636        }
637
638        let full_name = if let Some(ref schema) = self.schema {
639            format!("\"{}\".\"{}\"", schema, self.name)
640        } else {
641            format!("\"{}\"", self.name)
642        };
643
644        let refresh_strategy = match self.refresh_strategy {
645            Some(RefreshStrategy::Concurrent) => "CONCURRENTLY",
646            Some(RefreshStrategy::Locked) => "",
647            Some(RefreshStrategy::Auto) => "CONCURRENTLY", // Auto refresh is typically concurrent
648            Some(RefreshStrategy::Manual) => "",
649            None => "", // Default to locked refresh
650        };
651
652        Some(format!(
653            "REFRESH MATERIALIZED VIEW {} {};",
654            refresh_strategy, full_name
655        ))
656    }
657
658    /// Get all DDL statements for this view (CREATE + indexes + refresh if materialized)
659    pub fn generate_all_ddl(&self) -> Vec<String> {
660        let mut statements = Vec::new();
661
662        // Main CREATE statement
663        statements.push(self.generate_ddl());
664
665        // Add indexes for materialized views
666        if self.materialized && !self.indexes.is_empty() {
667            for index in &self.indexes {
668                statements.push(index.to_sql());
669            }
670        }
671
672        // Add refresh statement for materialized views
673        if let Some(refresh_ddl) = self.generate_refresh_ddl() {
674            statements.push(refresh_ddl);
675        }
676
677        statements
678    }
679}
680
681impl IgnisObject for Table {
682    #[inline]
683    fn name(&self) -> &str {
684        &self.name
685    }
686
687    #[inline]
688    fn schema(&self) -> Option<&str> {
689        self.schema.as_deref()
690    }
691
692    #[inline]
693    fn ddl(&self) -> &str {
694        // This will be generated dynamically
695        "CREATE TABLE" // Placeholder
696    }
697
698    #[inline]
699    fn object_type(&self) -> &str {
700        "table"
701    }
702}
703
704impl IgnisObject for View {
705    #[inline]
706    fn name(&self) -> &str {
707        &self.name
708    }
709
710    #[inline]
711    fn schema(&self) -> Option<&str> {
712        self.schema.as_deref()
713    }
714
715    #[inline]
716    fn ddl(&self) -> &str {
717        if let Some(ref ddl) = self.ddl {
718            ddl
719        } else {
720            "CREATE VIEW" // Placeholder
721        }
722    }
723
724    #[inline]
725    fn object_type(&self) -> &str {
726        "view"
727    }
728}
729
730/// Table column
731#[derive(Debug, Clone, PartialEq)]
732pub struct Column {
733    pub name: String,
734    pub column_type: ColumnType,
735    pub nullable: bool,
736    pub default: Option<String>,
737    pub unique: bool,
738    pub references: Option<ForeignKey>,
739    pub check: Option<String>,
740}
741
742impl Column {
743    /// Create a new column
744    pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
745        Self {
746            name: name.into(),
747            column_type,
748            nullable: true,
749            default: None,
750            unique: false,
751            references: None,
752            check: None,
753        }
754    }
755
756    /// Set the column as not nullable
757    pub fn not_null(mut self) -> Self {
758        self.nullable = false;
759        self
760    }
761
762    /// Set the column as nullable
763    pub fn nullable(mut self) -> Self {
764        self.nullable = true;
765        self
766    }
767
768    /// Set the column as unique
769    pub fn unique(mut self) -> Self {
770        self.unique = true;
771        self
772    }
773
774    /// Set the default value
775    pub fn default(mut self, default: impl Into<String>) -> Self {
776        self.default = Some(default.into());
777        self
778    }
779
780    /// Set the foreign key reference
781    pub fn references(mut self, fk: ForeignKey) -> Self {
782        self.references = Some(fk);
783        self
784    }
785
786    /// Set the column as not nullable (in-place)
787    #[inline]
788    pub fn set_not_null(&mut self) -> &mut Self {
789        self.nullable = false;
790        self
791    }
792
793    /// Set the column as nullable (in-place)
794    #[inline]
795    pub fn set_nullable(&mut self) -> &mut Self {
796        self.nullable = true;
797        self
798    }
799
800    /// Set the column as unique (in-place)
801    #[inline]
802    pub fn set_unique(&mut self) -> &mut Self {
803        self.unique = true;
804        self
805    }
806
807    /// Set the default value (in-place)
808    pub fn set_default(&mut self, default: impl Into<String>) -> &mut Self {
809        self.default = Some(default.into());
810        self
811    }
812
813    /// Set the foreign key reference (in-place)
814    pub fn set_references(&mut self, fk: ForeignKey) -> &mut Self {
815        self.references = Some(fk);
816        self
817    }
818
819    /// Add a check constraint
820    pub fn check(self, _expression: impl Into<String>) -> Self {
821        // For now, we'll store check constraints in the table
822        // This will be enhanced when we add table-level constraints
823        self
824    }
825
826    /// Convert the column to SQL DDL
827    pub fn to_sql(&self) -> String {
828        let mut sql = format!("    \"{}\" {}", self.name, self.column_type.to_sql());
829
830        if !self.nullable {
831            sql.push_str(" NOT NULL");
832        }
833
834        if let Some(ref default) = self.default {
835            // Convert sequence-based defaults to SERIAL for new table creation
836            if default.contains("nextval(")
837                && self.column_type == ColumnType::Int4
838                && self.name == "id"
839            {
840                // This is likely a SERIAL column, use SERIAL instead
841                sql = format!("    \"{}\" SERIAL", self.name);
842                if !self.nullable {
843                    sql.push_str(" NOT NULL");
844                }
845            } else {
846                sql.push_str(&format!(" DEFAULT {}", default));
847            }
848        }
849
850        if self.unique {
851            sql.push_str(" UNIQUE");
852        }
853
854        if let Some(ref fk) = self.references {
855            sql.push_str(&format!(" REFERENCES \"{}\"(\"{}\")", fk.table, fk.column));
856        }
857
858        sql
859    }
860
861    /// Generate column definition for DDL (alias for to_sql)
862    pub fn generate_column_definition(&self) -> String {
863        self.to_sql()
864    }
865}
866
867/// PostgreSQL column types
868#[derive(Debug, Clone, PartialEq)]
869pub enum ColumnType {
870    Int2,
871    Int4,
872    Int8,
873    Varchar(Option<usize>),
874    Text,
875    Bool,
876    Uuid,
877    Timestamptz,
878    Date,
879    Time,
880    Json,
881    Jsonb,
882    Char,
883    Bytea,
884    Numeric(Option<usize>, Option<usize>),
885    Array(Box<ColumnType>),
886    Custom(String),
887    // Auto-increment types
888    Serial,      // PostgreSQL SERIAL (auto-increment i32)
889    BigSerial,   // PostgreSQL BIGSERIAL (auto-increment i64)
890    SmallSerial, // PostgreSQL SMALLSERIAL (auto-increment i16)
891}
892
893impl Default for ColumnType {
894    fn default() -> Self {
895        ColumnType::Text
896    }
897}
898
899impl ColumnType {
900    /// Convert the column type to SQL
901    #[inline]
902    pub fn to_sql(&self) -> String {
903        match self {
904            ColumnType::Int2 => "SMALLINT".to_string(),
905            ColumnType::Int4 => "INTEGER".to_string(),
906            ColumnType::Int8 => "BIGINT".to_string(),
907            ColumnType::Varchar(None) => "VARCHAR".to_string(),
908            ColumnType::Varchar(Some(length)) => format!("VARCHAR({})", length),
909            ColumnType::Text => "TEXT".to_string(),
910            ColumnType::Bool => "BOOLEAN".to_string(),
911            ColumnType::Uuid => "UUID".to_string(),
912            ColumnType::Timestamptz => "TIMESTAMPTZ".to_string(),
913            ColumnType::Date => "DATE".to_string(),
914            ColumnType::Time => "TIME".to_string(),
915            ColumnType::Json => "JSON".to_string(),
916            ColumnType::Jsonb => "JSONB".to_string(),
917            ColumnType::Char => "CHAR".to_string(),
918            ColumnType::Bytea => "BYTEA".to_string(),
919            ColumnType::Numeric(None, None) => "NUMERIC".to_string(),
920            ColumnType::Numeric(Some(precision), None) => format!("NUMERIC({})", precision),
921            ColumnType::Numeric(Some(precision), Some(scale)) => {
922                format!("NUMERIC({},{})", precision, scale)
923            }
924            ColumnType::Numeric(None, Some(scale)) => format!("NUMERIC(38,{})", scale), // Default precision
925            ColumnType::Array(element_type) => format!("{}[]", element_type.to_sql()),
926            ColumnType::Custom(custom_type) => custom_type.clone(),
927            // Auto-increment types
928            ColumnType::Serial => "SERIAL".to_string(),
929            ColumnType::BigSerial => "BIGSERIAL".to_string(),
930            ColumnType::SmallSerial => "SMALLSERIAL".to_string(),
931        }
932    }
933}
934
935/// Foreign key constraint
936#[derive(Debug, Clone, PartialEq)]
937pub struct ForeignKey {
938    pub table: String,
939    pub column: String,
940}
941
942/// Represents a table constraint
943#[derive(Debug, Clone, PartialEq)]
944pub struct Constraint {
945    pub name: String,
946    pub constraint_type: ConstraintType,
947}
948
949impl Constraint {
950    /// Convert the constraint to SQL
951    pub fn to_sql(&self) -> String {
952        match &self.constraint_type {
953            ConstraintType::Check(expression) => {
954                format!("CONSTRAINT \"{}\" CHECK ({})", self.name, expression)
955            }
956            ConstraintType::Unique(columns) => {
957                let cols: Vec<String> = columns.iter().map(|c| format!("\"{}\"", c)).collect();
958                format!("CONSTRAINT \"{}\" UNIQUE ({})", self.name, cols.join(", "))
959            }
960        }
961    }
962}
963
964/// Types of table constraints
965#[derive(Debug, Clone, PartialEq)]
966pub enum ConstraintType {
967    Check(String),
968    Unique(Vec<String>),
969}
970
971/// Table index
972#[derive(Debug, Clone, PartialEq)]
973pub struct Index {
974    pub name: String,
975    pub columns: Vec<String>,
976    pub unique: bool,
977}
978
979impl Index {
980    /// Create a new index
981    pub fn new(name: impl Into<String>, columns: Vec<String>, unique: bool) -> Self {
982        Self {
983            name: name.into(),
984            columns,
985            unique,
986        }
987    }
988
989    /// Convert the index to SQL
990    pub fn to_sql(&self) -> String {
991        let unique = if self.unique { "UNIQUE " } else { "" };
992        let cols: Vec<String> = self.columns.iter().map(|c| format!("\"{}\"", c)).collect();
993
994        format!(
995            "CREATE {}INDEX \"{}\" ON \"{}\" ({});",
996            unique,
997            self.name,
998            "table_name",
999            cols.join(", ")
1000        )
1001    }
1002}
1003
1004/// Index metadata for the macro system
1005#[derive(Debug, Clone, PartialEq)]
1006pub struct IndexMeta {
1007    pub name: &'static str,
1008    pub table: &'static str,
1009    pub schema: Option<&'static str>,
1010    pub unique: bool,
1011    pub concurrent: bool,
1012    pub index_type: IndexType,
1013    pub columns: &'static [&'static str],
1014}
1015
1016impl IndexMeta {
1017    /// Generate the DDL for creating this index
1018    pub fn ddl(&self) -> String {
1019        let mut ddl = String::new();
1020
1021        ddl.push_str("CREATE ");
1022        if self.unique {
1023            ddl.push_str("UNIQUE ");
1024        }
1025        if self.concurrent {
1026            ddl.push_str("CONCURRENTLY ");
1027        }
1028
1029        ddl.push_str("INDEX ");
1030
1031        let index_name = if let Some(schema) = self.schema {
1032            format!("\"{}\".\"{}\"", schema, self.name)
1033        } else {
1034            format!("\"{}\"", self.name)
1035        };
1036        ddl.push_str(&index_name);
1037
1038        ddl.push_str(" ON ");
1039
1040        let table_name = if let Some(schema) = self.schema {
1041            format!("\"{}\".\"{}\"", schema, self.table)
1042        } else {
1043            format!("\"{}\"", self.table)
1044        };
1045        ddl.push_str(&table_name);
1046
1047        // Index type
1048        match self.index_type {
1049            IndexType::BTree => {} // Default, no need to specify
1050            IndexType::GIN => ddl.push_str(" USING GIN"),
1051            IndexType::GIST => ddl.push_str(" USING GIST"),
1052            IndexType::BRIN => ddl.push_str(" USING BRIN"),
1053            IndexType::Hash => ddl.push_str(" USING HASH"),
1054            IndexType::SPGIST => ddl.push_str(" USING SPGIST"),
1055        }
1056
1057        // Columns
1058        ddl.push_str(" (");
1059        for (i, column) in self.columns.iter().enumerate() {
1060            if i > 0 {
1061                ddl.push_str(", ");
1062            }
1063            ddl.push_str(&format!("\"{}\"", column));
1064        }
1065        ddl.push_str(")");
1066
1067        ddl.push_str(";");
1068        ddl
1069    }
1070
1071    /// Generate the DDL for creating this index (alias for ddl method)
1072    pub fn generate_ddl(&self) -> String {
1073        self.ddl()
1074    }
1075}
1076
1077/// Index type variants
1078#[derive(Debug, Clone, PartialEq)]
1079pub enum IndexType {
1080    BTree,
1081    GIN,
1082    GIST,
1083    BRIN,
1084    Hash,
1085    SPGIST,
1086}
1087
1088impl Default for IndexType {
1089    fn default() -> Self {
1090        IndexType::BTree
1091    }
1092}
1093
1094impl std::fmt::Display for IndexType {
1095    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1096        match self {
1097            IndexType::BTree => write!(f, "BTree"),
1098            IndexType::GIN => write!(f, "GIN"),
1099            IndexType::GIST => write!(f, "GIST"),
1100            IndexType::BRIN => write!(f, "BRIN"),
1101            IndexType::Hash => write!(f, "Hash"),
1102            IndexType::SPGIST => write!(f, "SPGIST"),
1103        }
1104    }
1105}
1106
1107impl From<&str> for ColumnType {
1108    fn from(type_str: &str) -> Self {
1109        match type_str.to_uppercase().as_str() {
1110            "INT4" | "INTEGER" | "INT" => ColumnType::Int4,
1111            "INT8" | "BIGINT" => ColumnType::Int8,
1112            "TEXT" => ColumnType::Text,
1113            "VARCHAR" => ColumnType::Varchar(None),
1114            "BOOLEAN" | "BOOL" => ColumnType::Bool,
1115            "UUID" => ColumnType::Uuid,
1116            "TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" => ColumnType::Timestamptz,
1117            "NUMERIC" | "DECIMAL" => ColumnType::Numeric(None, None),
1118            "JSONB" => ColumnType::Jsonb,
1119            // Auto-increment types
1120            "SERIAL" => ColumnType::Serial,
1121            "BIGSERIAL" => ColumnType::BigSerial,
1122            "SMALLSERIAL" => ColumnType::SmallSerial,
1123            _ => ColumnType::Text, // Default fallback
1124        }
1125    }
1126}
1127
1128/// Table metadata for the macro system
1129#[derive(Debug, Clone)]
1130pub struct TableMeta {
1131    pub name: &'static str,
1132    pub schema: Option<&'static str>,
1133    pub primary_key: &'static str,
1134    pub columns: &'static [(&'static str, ColumnType)],
1135}
1136
1137impl TableMeta {
1138    /// Create a new table metadata
1139    pub const fn new(
1140        name: &'static str,
1141        schema: Option<&'static str>,
1142        primary_key: &'static str,
1143        columns: &'static [(&'static str, ColumnType)],
1144    ) -> Self {
1145        Self {
1146            name,
1147            schema,
1148            primary_key,
1149            columns,
1150        }
1151    }
1152}
1153
1154/// PostgreSQL role representation
1155#[derive(Debug, Clone, PartialEq)]
1156pub struct Role {
1157    pub name: String,
1158    pub password: Option<String>,
1159    pub superuser: bool,
1160    pub createdb: bool,
1161    pub createrole: bool,
1162    pub inherit: bool,
1163    pub login: bool,
1164    pub replication: bool,
1165    pub connection_limit: Option<i32>,
1166    pub valid_until: Option<String>,
1167    pub member_of: Vec<String>,
1168    pub members: Vec<String>,
1169}
1170
1171/// Grant/Revoke operations
1172#[derive(Debug, Clone, PartialEq)]
1173pub struct Grant {
1174    pub privilege: Privilege,
1175    pub target: GrantTarget,
1176    pub grantee: String,
1177    pub grantor: Option<String>,
1178    pub with_grant_option: bool,
1179}
1180
1181/// Privilege types
1182#[derive(Debug, Clone, PartialEq)]
1183pub enum Privilege {
1184    // Table privileges
1185    Select,
1186    Insert,
1187    Update,
1188    Delete,
1189    References,
1190    Trigger,
1191    // Database privileges
1192    Connect,
1193    Create,
1194    Temporary,
1195    // Schema privileges
1196    Usage,
1197    CreateInSchema,
1198    // Function privileges
1199    Execute,
1200    // All privileges
1201    All,
1202    // Custom privilege string
1203    Custom(String),
1204}
1205
1206/// Grant targets
1207#[derive(Debug, Clone, PartialEq)]
1208pub enum GrantTarget {
1209    Table {
1210        table: String,
1211        schema: Option<String>,
1212    },
1213    Schema(String),
1214    Database(String),
1215    Function {
1216        function: String,
1217        schema: Option<String>,
1218    },
1219    AllTablesInSchema(String),
1220    AllFunctionsInSchema(String),
1221    Role(String),
1222}
1223
1224impl Role {
1225    /// Create a new role with default settings
1226    pub fn new(name: impl Into<String>) -> Self {
1227        Self {
1228            name: name.into(),
1229            password: None,
1230            superuser: false,
1231            createdb: false,
1232            createrole: false,
1233            inherit: true,
1234            login: false,
1235            replication: false,
1236            connection_limit: None,
1237            valid_until: None,
1238            member_of: Vec::new(),
1239            members: Vec::new(),
1240        }
1241    }
1242
1243    /// Set password
1244    pub fn with_password(mut self, password: impl Into<String>) -> Self {
1245        self.password = Some(password.into());
1246        self
1247    }
1248
1249    /// Set superuser privileges
1250    pub fn with_superuser(mut self, superuser: bool) -> Self {
1251        self.superuser = superuser;
1252        self
1253    }
1254
1255    /// Set database creation privileges
1256    pub fn with_createdb(mut self, createdb: bool) -> Self {
1257        self.createdb = createdb;
1258        self
1259    }
1260
1261    /// Set role creation privileges
1262    pub fn with_createrole(mut self, createrole: bool) -> Self {
1263        self.createrole = createrole;
1264        self
1265    }
1266
1267    /// Set inheritance behavior
1268    pub fn with_inherit(mut self, inherit: bool) -> Self {
1269        self.inherit = inherit;
1270        self
1271    }
1272
1273    /// Set login capability
1274    pub fn with_login(mut self, login: bool) -> Self {
1275        self.login = login;
1276        self
1277    }
1278
1279    /// Set replication privileges
1280    pub fn with_replication(mut self, replication: bool) -> Self {
1281        self.replication = replication;
1282        self
1283    }
1284
1285    /// Set connection limit
1286    pub fn with_connection_limit(mut self, limit: i32) -> Self {
1287        self.connection_limit = Some(limit);
1288        self
1289    }
1290
1291    /// Set validity period
1292    pub fn with_valid_until(mut self, until: impl Into<String>) -> Self {
1293        self.valid_until = Some(until.into());
1294        self
1295    }
1296
1297    /// Add parent roles (inheritance)
1298    pub fn with_member_of(mut self, roles: Vec<String>) -> Self {
1299        self.member_of = roles;
1300        self
1301    }
1302
1303    /// Add member roles
1304    pub fn with_members(mut self, members: Vec<String>) -> Self {
1305        self.members = members;
1306        self
1307    }
1308
1309    /// Generate CREATE ROLE DDL
1310    pub fn generate_create_ddl(&self) -> String {
1311        let mut ddl = format!("CREATE ROLE \"{}\"", self.name);
1312
1313        if self.login {
1314            ddl.push_str(" LOGIN");
1315        } else {
1316            ddl.push_str(" NOLOGIN");
1317        }
1318        if self.superuser {
1319            ddl.push_str(" SUPERUSER");
1320        } else {
1321            ddl.push_str(" NOSUPERUSER");
1322        }
1323        if self.createdb {
1324            ddl.push_str(" CREATEDB");
1325        } else {
1326            ddl.push_str(" NOCREATEDB");
1327        }
1328        if self.createrole {
1329            ddl.push_str(" CREATEROLE");
1330        } else {
1331            ddl.push_str(" NOCREATEROLE");
1332        }
1333        if self.inherit {
1334            ddl.push_str(" INHERIT");
1335        } else {
1336            ddl.push_str(" NOINHERIT");
1337        }
1338        if self.replication {
1339            ddl.push_str(" REPLICATION");
1340        } else {
1341            ddl.push_str(" NOREPLICATION");
1342        }
1343
1344        if let Some(limit) = self.connection_limit {
1345            ddl.push_str(&format!(" CONNECTION LIMIT {}", limit));
1346        }
1347
1348        if let Some(ref password) = self.password {
1349            ddl.push_str(&format!(" PASSWORD '{}'", password));
1350        }
1351
1352        if let Some(ref until) = self.valid_until {
1353            ddl.push_str(&format!(" VALID UNTIL '{}'", until));
1354        }
1355
1356        ddl.push(';');
1357
1358        // Add membership grants
1359        for parent in &self.member_of {
1360            ddl.push_str(&format!("\nGRANT \"{}\" TO \"{}\";", parent, self.name));
1361        }
1362
1363        for member in &self.members {
1364            ddl.push_str(&format!("\nGRANT \"{}\" TO \"{}\";", self.name, member));
1365        }
1366
1367        ddl
1368    }
1369
1370    /// Generate ALTER ROLE DDL for modifications
1371    pub fn generate_alter_ddl(&self, old_role: &Role) -> String {
1372        let mut ddl = String::new();
1373
1374        if self.login != old_role.login {
1375            ddl.push_str(&format!(
1376                "ALTER ROLE \"{}\" {};\n",
1377                self.name,
1378                if self.login { "LOGIN" } else { "NOLOGIN" }
1379            ));
1380        }
1381
1382        if self.superuser != old_role.superuser {
1383            ddl.push_str(&format!(
1384                "ALTER ROLE \"{}\" {};\n",
1385                self.name,
1386                if self.superuser {
1387                    "SUPERUSER"
1388                } else {
1389                    "NOSUPERUSER"
1390                }
1391            ));
1392        }
1393
1394        if self.createdb != old_role.createdb {
1395            ddl.push_str(&format!(
1396                "ALTER ROLE \"{}\" {};\n",
1397                self.name,
1398                if self.createdb {
1399                    "CREATEDB"
1400                } else {
1401                    "NOCREATEDB"
1402                }
1403            ));
1404        }
1405
1406        if self.createrole != old_role.createrole {
1407            ddl.push_str(&format!(
1408                "ALTER ROLE \"{}\" {};\n",
1409                self.name,
1410                if self.createrole {
1411                    "CREATEROLE"
1412                } else {
1413                    "NOCREATEROLE"
1414                }
1415            ));
1416        }
1417
1418        if self.inherit != old_role.inherit {
1419            ddl.push_str(&format!(
1420                "ALTER ROLE \"{}\" {};\n",
1421                self.name,
1422                if self.inherit { "INHERIT" } else { "NOINHERIT" }
1423            ));
1424        }
1425
1426        if self.replication != old_role.replication {
1427            ddl.push_str(&format!(
1428                "ALTER ROLE \"{}\" {};\n",
1429                self.name,
1430                if self.replication {
1431                    "REPLICATION"
1432                } else {
1433                    "NOREPLICATION"
1434                }
1435            ));
1436        }
1437
1438        if self.connection_limit != old_role.connection_limit {
1439            if let Some(limit) = self.connection_limit {
1440                ddl.push_str(&format!(
1441                    "ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
1442                    self.name, limit
1443                ));
1444            } else {
1445                ddl.push_str(&format!(
1446                    "ALTER ROLE \"{}\" CONNECTION LIMIT -1;\n",
1447                    self.name
1448                ));
1449            }
1450        }
1451
1452        if self.password != old_role.password {
1453            if let Some(ref password) = self.password {
1454                ddl.push_str(&format!(
1455                    "ALTER ROLE \"{}\" PASSWORD '{}';\n",
1456                    self.name, password
1457                ));
1458            }
1459        }
1460
1461        if self.valid_until != old_role.valid_until {
1462            if let Some(ref until) = self.valid_until {
1463                ddl.push_str(&format!(
1464                    "ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
1465                    self.name, until
1466                ));
1467            } else {
1468                ddl.push_str(&format!(
1469                    "ALTER ROLE \"{}\" VALID UNTIL 'infinity';\n",
1470                    self.name
1471                ));
1472            }
1473        }
1474
1475        // Handle membership changes
1476        let old_member_of: std::collections::HashSet<_> = old_role.member_of.iter().collect();
1477        let new_member_of: std::collections::HashSet<_> = self.member_of.iter().collect();
1478
1479        // Add new memberships
1480        for parent in &self.member_of {
1481            if !old_member_of.contains(parent) {
1482                ddl.push_str(&format!("GRANT \"{}\" TO \"{}\";\n", parent, self.name));
1483            }
1484        }
1485
1486        // Remove old memberships
1487        for parent in &old_role.member_of {
1488            if !new_member_of.contains(parent) {
1489                ddl.push_str(&format!("REVOKE \"{}\" FROM \"{}\";\n", parent, self.name));
1490            }
1491        }
1492
1493        // Handle member changes
1494        let old_members: std::collections::HashSet<_> = old_role.members.iter().collect();
1495        let new_members: std::collections::HashSet<_> = self.members.iter().collect();
1496
1497        // Add new members
1498        for member in &self.members {
1499            if !old_members.contains(member) {
1500                ddl.push_str(&format!("GRANT \"{}\" TO \"{}\";\n", self.name, member));
1501            }
1502        }
1503
1504        // Remove old members
1505        for member in &old_role.members {
1506            if !new_members.contains(member) {
1507                ddl.push_str(&format!("REVOKE \"{}\" FROM \"{}\";\n", self.name, member));
1508            }
1509        }
1510
1511        ddl
1512    }
1513
1514    /// Generate DROP ROLE DDL
1515    pub fn generate_drop_ddl(&self) -> String {
1516        format!("DROP ROLE IF EXISTS \"{}\";", self.name)
1517    }
1518}
1519
1520impl Grant {
1521    /// Create a new grant
1522    pub fn new(privilege: Privilege, target: GrantTarget, grantee: impl Into<String>) -> Self {
1523        Self {
1524            privilege,
1525            target,
1526            grantee: grantee.into(),
1527            grantor: None,
1528            with_grant_option: false,
1529        }
1530    }
1531
1532    /// Set grantor
1533    pub fn with_grantor(mut self, grantor: impl Into<String>) -> Self {
1534        self.grantor = Some(grantor.into());
1535        self
1536    }
1537
1538    /// Enable grant option
1539    pub fn with_grant_option(mut self, with_grant_option: bool) -> Self {
1540        self.with_grant_option = with_grant_option;
1541        self
1542    }
1543
1544    /// Get privilege name as string
1545    pub fn privilege_name(&self) -> String {
1546        match &self.privilege {
1547            Privilege::Select => "SELECT".to_string(),
1548            Privilege::Insert => "INSERT".to_string(),
1549            Privilege::Update => "UPDATE".to_string(),
1550            Privilege::Delete => "DELETE".to_string(),
1551            Privilege::References => "REFERENCES".to_string(),
1552            Privilege::Trigger => "TRIGGER".to_string(),
1553            Privilege::Connect => "CONNECT".to_string(),
1554            Privilege::Create => "CREATE".to_string(),
1555            Privilege::Temporary => "TEMPORARY".to_string(),
1556            Privilege::Usage => "USAGE".to_string(),
1557            Privilege::CreateInSchema => "CREATE".to_string(),
1558            Privilege::Execute => "EXECUTE".to_string(),
1559            Privilege::All => "ALL".to_string(),
1560            Privilege::Custom(s) => s.clone(),
1561        }
1562    }
1563
1564    /// Generate unique name for this grant
1565    pub fn generate_name(&self) -> String {
1566        let target_str = match &self.target {
1567            GrantTarget::Table { table, schema } => {
1568                if let Some(schema) = schema {
1569                    format!("{}_{}", schema, table)
1570                } else {
1571                    table.clone()
1572                }
1573            }
1574            GrantTarget::Schema(schema) => format!("schema_{}", schema),
1575            GrantTarget::Database(db) => format!("database_{}", db),
1576            GrantTarget::Function { function, schema } => {
1577                if let Some(schema) = schema {
1578                    format!("{}_{}_function", schema, function)
1579                } else {
1580                    format!("{}_function", function)
1581                }
1582            }
1583            GrantTarget::AllTablesInSchema(schema) => format!("all_tables_in_{}", schema),
1584            GrantTarget::AllFunctionsInSchema(schema) => format!("all_functions_in_{}", schema),
1585            GrantTarget::Role(role) => format!("role_{}", role),
1586        };
1587
1588        format!(
1589            "{}_{}_to_{}",
1590            self.privilege_name().to_lowercase(),
1591            target_str,
1592            self.grantee
1593        )
1594    }
1595
1596    /// Generate GRANT DDL
1597    pub fn generate_grant_ddl(&self) -> String {
1598        let privilege_str = self.privilege_name();
1599
1600        let target_str = match &self.target {
1601            GrantTarget::Table { table, schema } => {
1602                if let Some(schema) = schema {
1603                    format!("\"{}\".\"{}\"", schema, table)
1604                } else {
1605                    format!("\"{}\"", table)
1606                }
1607            }
1608            GrantTarget::Schema(schema) => format!("SCHEMA \"{}\"", schema),
1609            GrantTarget::Database(db) => format!("DATABASE \"{}\"", db),
1610            GrantTarget::Function { function, schema } => {
1611                if let Some(schema) = schema {
1612                    format!("\"{}\".\"{}\"", schema, function)
1613                } else {
1614                    format!("\"{}\"", function)
1615                }
1616            }
1617            GrantTarget::AllTablesInSchema(schema) => {
1618                format!("ALL TABLES IN SCHEMA \"{}\"", schema)
1619            }
1620            GrantTarget::AllFunctionsInSchema(schema) => {
1621                format!("ALL FUNCTIONS IN SCHEMA \"{}\"", schema)
1622            }
1623            GrantTarget::Role(role) => format!("\"{}\"", role),
1624        };
1625
1626        let mut ddl = format!(
1627            "GRANT {} ON {} TO \"{}\"",
1628            privilege_str, target_str, self.grantee
1629        );
1630
1631        if self.with_grant_option {
1632            ddl.push_str(" WITH GRANT OPTION");
1633        }
1634
1635        ddl.push(';');
1636        ddl
1637    }
1638
1639    /// Generate REVOKE DDL
1640    pub fn generate_revoke_ddl(&self) -> String {
1641        let privilege_str = self.privilege_name();
1642
1643        let target_str = match &self.target {
1644            GrantTarget::Table { table, schema } => {
1645                if let Some(schema) = schema {
1646                    format!("\"{}\".\"{}\"", schema, table)
1647                } else {
1648                    format!("\"{}\"", table)
1649                }
1650            }
1651            GrantTarget::Schema(schema) => format!("SCHEMA \"{}\"", schema),
1652            GrantTarget::Database(db) => format!("DATABASE \"{}\"", db),
1653            GrantTarget::Function { function, schema } => {
1654                if let Some(schema) = schema {
1655                    format!("\"{}\".\"{}\"", schema, function)
1656                } else {
1657                    format!("\"{}\"", function)
1658                }
1659            }
1660            GrantTarget::AllTablesInSchema(schema) => {
1661                format!("ALL TABLES IN SCHEMA \"{}\"", schema)
1662            }
1663            GrantTarget::AllFunctionsInSchema(schema) => {
1664                format!("ALL FUNCTIONS IN SCHEMA \"{}\"", schema)
1665            }
1666            GrantTarget::Role(role) => format!("\"{}\"", role),
1667        };
1668
1669        let mut ddl = format!(
1670            "REVOKE {} ON {} FROM \"{}\"",
1671            privilege_str, target_str, self.grantee
1672        );
1673
1674        if self.with_grant_option {
1675            ddl.push_str(" CASCADE");
1676        }
1677
1678        ddl.push(';');
1679        ddl
1680    }
1681}
1682
1683/// PostgreSQL Row-Level Security Policy
1684#[derive(Debug, Clone, PartialEq)]
1685pub struct Policy {
1686    pub name: String,
1687    pub table: String,
1688    pub schema: Option<String>,
1689    pub command: PolicyCommand,
1690    pub role: Option<String>,
1691    pub expression: String,
1692    pub check_expression: Option<String>,
1693    pub permissive: bool, // true for PERMISSIVE, false for RESTRICTIVE
1694}
1695
1696/// Policy command types (what operations the policy applies to)
1697#[derive(Debug, Clone, PartialEq)]
1698pub enum PolicyCommand {
1699    All,
1700    Select,
1701    Insert,
1702    Update,
1703    Delete,
1704}
1705
1706impl Policy {
1707    /// Create a new policy
1708    pub fn new(
1709        name: impl Into<String>,
1710        table: impl Into<String>,
1711        command: PolicyCommand,
1712        expression: impl Into<String>,
1713    ) -> Self {
1714        Self {
1715            name: name.into(),
1716            table: table.into(),
1717            schema: None,
1718            command,
1719            role: None,
1720            expression: expression.into(),
1721            check_expression: None,
1722            permissive: true, // Default to permissive
1723        }
1724    }
1725
1726    /// Set the schema for this policy
1727    pub fn schema(mut self, schema: impl Into<String>) -> Self {
1728        self.schema = Some(schema.into());
1729        self
1730    }
1731
1732    /// Set the role this policy applies to
1733    pub fn role(mut self, role: impl Into<String>) -> Self {
1734        self.role = Some(role.into());
1735        self
1736    }
1737
1738    /// Set the WITH CHECK expression
1739    pub fn with_check(mut self, expression: impl Into<String>) -> Self {
1740        self.check_expression = Some(expression.into());
1741        self
1742    }
1743
1744    /// Set policy as restrictive (default is permissive)
1745    pub fn restrictive(mut self) -> Self {
1746        self.permissive = false;
1747        self
1748    }
1749
1750    /// Set policy as permissive (default)
1751    pub fn permissive(mut self) -> Self {
1752        self.permissive = true;
1753        self
1754    }
1755
1756    /// Convert policy to SQL DDL
1757    pub fn to_sql(&self) -> String {
1758        // Handle schema-qualified table names correctly
1759        let table_name = if let Some(ref schema) = self.schema {
1760            format!("{}.{}", schema, self.table)
1761        } else if self.table.contains('.') {
1762            // Table name already includes schema
1763            self.table.clone()
1764        } else {
1765            format!("\"{}\"", self.table)
1766        };
1767
1768        let mut sql = format!("CREATE POLICY \"{}\" ON {}", self.name, table_name);
1769
1770        // Add command
1771        match self.command {
1772            PolicyCommand::All => sql.push_str(" FOR ALL"),
1773            PolicyCommand::Select => sql.push_str(" FOR SELECT"),
1774            PolicyCommand::Insert => sql.push_str(" FOR INSERT"),
1775            PolicyCommand::Update => sql.push_str(" FOR UPDATE"),
1776            PolicyCommand::Delete => sql.push_str(" FOR DELETE"),
1777        }
1778
1779        // Add role if specified
1780        if let Some(role) = &self.role {
1781            sql.push_str(&format!(" TO \"{}\"", role));
1782        }
1783
1784        // Add permissive/restrictive (PostgreSQL doesn't use PERMISSIVE/RESTRICTIVE in CREATE POLICY)
1785        // These are only used in ALTER POLICY statements
1786
1787        // Add USING expression
1788        sql.push_str(&format!(" USING ({})", self.expression));
1789
1790        // Add WITH CHECK expression if specified
1791        if let Some(check) = &self.check_expression {
1792            sql.push_str(&format!(" WITH CHECK ({})", check));
1793        }
1794
1795        sql.push(';');
1796        sql
1797    }
1798
1799    /// Convert policy to DROP SQL
1800    pub fn to_drop_sql(&self) -> String {
1801        format!(
1802            "DROP POLICY IF EXISTS \"{}\" ON \"{}\";",
1803            self.name, self.table
1804        )
1805    }
1806}
1807
1808impl PolicyCommand {
1809    /// Convert to SQL string
1810    pub fn to_sql(&self) -> &'static str {
1811        match self {
1812            PolicyCommand::All => "ALL",
1813            PolicyCommand::Select => "SELECT",
1814            PolicyCommand::Insert => "INSERT",
1815            PolicyCommand::Update => "UPDATE",
1816            PolicyCommand::Delete => "DELETE",
1817        }
1818    }
1819}
1820
1821/// PostgreSQL Extension
1822#[derive(Debug, Clone, PartialEq)]
1823pub struct Extension {
1824    pub name: String,
1825    pub schema: Option<String>,
1826    pub version: Option<String>,
1827    pub cascade: bool,
1828    pub if_not_exists: bool,
1829}
1830
1831impl Extension {
1832    /// Create a new extension
1833    pub fn new(name: impl Into<String>) -> Self {
1834        Self {
1835            name: name.into(),
1836            schema: None,
1837            version: None,
1838            cascade: false,
1839            if_not_exists: false,
1840        }
1841    }
1842
1843    /// Set the schema for this extension
1844    pub fn schema(mut self, schema: impl Into<String>) -> Self {
1845        self.schema = Some(schema.into());
1846        self
1847    }
1848
1849    /// Set the version for this extension
1850    pub fn version(mut self, version: impl Into<String>) -> Self {
1851        self.version = Some(version.into());
1852        self
1853    }
1854
1855    /// Enable CASCADE for this extension
1856    pub fn cascade(mut self) -> Self {
1857        self.cascade = true;
1858        self
1859    }
1860
1861    /// Enable IF NOT EXISTS for this extension
1862    pub fn if_not_exists(mut self) -> Self {
1863        self.if_not_exists = true;
1864        self
1865    }
1866
1867    /// Convert extension to SQL DDL
1868    pub fn to_sql(&self) -> String {
1869        let mut sql = "CREATE EXTENSION".to_string();
1870
1871        if self.if_not_exists {
1872            sql.push_str(" IF NOT EXISTS");
1873        }
1874
1875        sql.push_str(&format!(" \"{}\"", self.name));
1876
1877        if let Some(schema) = &self.schema {
1878            sql.push_str(&format!(" WITH SCHEMA \"{}\"", schema));
1879        }
1880
1881        if let Some(version) = &self.version {
1882            sql.push_str(&format!(" VERSION \"{}\"", version));
1883        }
1884
1885        if self.cascade {
1886            sql.push_str(" CASCADE");
1887        }
1888
1889        sql.push(';');
1890        sql
1891    }
1892
1893    /// Convert extension to DROP SQL
1894    pub fn to_drop_sql(&self) -> String {
1895        let mut sql = format!("DROP EXTENSION IF EXISTS \"{}\"", self.name);
1896
1897        if self.cascade {
1898            sql.push_str(" CASCADE");
1899        }
1900
1901        sql.push(';');
1902        sql
1903    }
1904}
1905
1906/// Global User Configuration (GUC) setting
1907#[derive(Debug, Clone, PartialEq)]
1908pub struct GucSetting {
1909    pub name: String,
1910    pub value: String,
1911    pub context: GucContext,
1912    pub description: Option<String>,
1913}
1914
1915/// GUC context levels
1916#[derive(Debug, Clone, PartialEq)]
1917pub enum GucContext {
1918    /// System-wide setting (requires superuser)
1919    System,
1920    /// Database-level setting
1921    Database,
1922    /// User-level setting
1923    User,
1924    /// Session-level setting
1925    Session,
1926    /// Transaction-level setting
1927    Transaction,
1928}
1929
1930impl GucSetting {
1931    /// Create a new GUC setting
1932    pub fn new(name: impl Into<String>, value: impl Into<String>, context: GucContext) -> Self {
1933        Self {
1934            name: name.into(),
1935            value: value.into(),
1936            context,
1937            description: None,
1938        }
1939    }
1940
1941    /// Set a description for this GUC setting
1942    pub fn description(mut self, description: impl Into<String>) -> Self {
1943        self.description = Some(description.into());
1944        self
1945    }
1946
1947    /// Convert GUC setting to SQL
1948    pub fn to_sql(&self) -> String {
1949        match self.context {
1950            GucContext::System => {
1951                format!("ALTER SYSTEM SET {} = '{}';", self.name, self.value)
1952            }
1953            GucContext::Database => {
1954                format!(
1955                    "ALTER DATABASE current_database() SET {} = '{}';",
1956                    self.name, self.value
1957                )
1958            }
1959            GucContext::User => {
1960                format!(
1961                    "ALTER USER current_user() SET {} = '{}';",
1962                    self.name, self.value
1963                )
1964            }
1965            GucContext::Session => {
1966                format!("SET {} = '{}';", self.name, self.value)
1967            }
1968            GucContext::Transaction => {
1969                format!("SET LOCAL {} = '{}';", self.name, self.value)
1970            }
1971        }
1972    }
1973
1974    /// Convert GUC setting to reset SQL
1975    pub fn to_reset_sql(&self) -> String {
1976        match self.context {
1977            GucContext::System => {
1978                format!("ALTER SYSTEM RESET {};", self.name)
1979            }
1980            GucContext::Database => {
1981                format!("ALTER DATABASE current_database() RESET {};", self.name)
1982            }
1983            GucContext::User => {
1984                format!("ALTER USER current_user() RESET {};", self.name)
1985            }
1986            GucContext::Session => {
1987                format!("RESET {};", self.name)
1988            }
1989            GucContext::Transaction => {
1990                format!("RESET LOCAL {};", self.name)
1991            }
1992        }
1993    }
1994
1995    /// Get current value SQL
1996    pub fn get_value_sql(&self) -> String {
1997        format!("SELECT current_setting('{}');", self.name)
1998    }
1999}
2000
2001impl GucContext {
2002    /// Convert to SQL string
2003    pub fn to_sql(&self) -> &'static str {
2004        match self {
2005            GucContext::System => "SYSTEM",
2006            GucContext::Database => "DATABASE",
2007            GucContext::User => "USER",
2008            GucContext::Session => "SESSION",
2009            GucContext::Transaction => "LOCAL",
2010        }
2011    }
2012}
2013
2014// Re-export types for use in other modules
2015pub use crate::{RegisteredObject, SchemaObject};