Skip to main content

ignis_db/database/
schema_utils.rs

1//! Schema utilities for automatic schema creation
2//!
3//! This module provides utilities for automatically creating schemas
4//! when schema-qualified names are encountered.
5
6use crate::database::Database;
7use anyhow::Result;
8use std::collections::HashSet;
9
10/// Extract schema name from a schema-qualified identifier
11///
12/// # Parameters
13///
14/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
15///
16/// # Returns
17///
18/// - `Some(schema_name)` if the name is schema-qualified
19/// - `None` if the name is not schema-qualified
20///
21/// # Examples
22///
23/// ```rust
24/// use ignis_db::database::schema_utils::extract_schema_name;
25///
26/// assert_eq!(extract_schema_name("auth.users"), Some("auth"));
27/// assert_eq!(extract_schema_name("users"), None);
28/// assert_eq!(extract_schema_name("public.my_table"), Some("public"));
29/// ```
30pub fn extract_schema_name(qualified_name: &str) -> Option<&str> {
31    if let Some(dot_pos) = qualified_name.find('.') {
32        Some(&qualified_name[..dot_pos])
33    } else {
34        None
35    }
36}
37
38/// Extract table name from a schema-qualified identifier
39///
40/// # Parameters
41///
42/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
43///
44/// # Returns
45///
46/// - The table name part (everything after the dot, or the whole string if no dot)
47///
48/// # Examples
49///
50/// ```rust
51/// use ignis_db::database::schema_utils::extract_table_name;
52///
53/// assert_eq!(extract_table_name("auth.users"), "users");
54/// assert_eq!(extract_table_name("users"), "users");
55/// assert_eq!(extract_table_name("public.my_table"), "my_table");
56/// ```
57pub fn extract_table_name(qualified_name: &str) -> &str {
58    if let Some(dot_pos) = qualified_name.find('.') {
59        &qualified_name[dot_pos + 1..]
60    } else {
61        qualified_name
62    }
63}
64
65/// Automatically create a schema if it doesn't exist
66///
67/// This function checks if a schema exists and creates it if necessary.
68/// This is the core function that should be called by builders when they
69/// encounter schema-qualified names.
70///
71/// # Parameters
72///
73/// - `db`: The database connection
74/// - `schema_name`: The name of the schema to create
75/// - `pool`: The database connection pool for execution
76///
77/// # Returns
78///
79/// - `Ok(())` if the schema exists or was created successfully
80/// - `Err` if there was an error creating the schema
81pub async fn ensure_schema_exists<D: Database>(
82    db: &D,
83    schema_name: &str,
84    pool: &sqlx::PgPool,
85) -> Result<()> {
86    // Check if schema already exists
87    let exists_query = "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1";
88    let exists: Option<i32> = sqlx::query_scalar(exists_query)
89        .bind(schema_name)
90        .fetch_optional(pool)
91        .await?;
92
93    if exists.is_none() {
94        // Schema doesn't exist, create it using framework SQL generation
95        let sql_gen = db.sql_generator();
96        let create_sql = sql_gen.create_schema_sql(schema_name);
97
98        println!("📋 Framework auto-creating schema: {}", schema_name);
99        println!("{}", create_sql);
100        sqlx::query(&create_sql).execute(pool).await?;
101        println!(
102            "✅ Schema '{}' created successfully by framework",
103            schema_name
104        );
105    }
106
107    Ok(())
108}
109
110/// Automatically create schemas for a list of qualified names
111///
112/// This function extracts all unique schema names from the provided
113/// qualified names and creates them if they don't already exist.
114///
115/// # Parameters
116///
117/// - `db`: The database connection
118/// - `qualified_names`: A list of schema-qualified names
119///
120/// # Returns
121///
122/// - `Ok(())` if all schemas were created successfully
123/// - `Err` if there was an error creating any schema
124///
125/// # Examples
126///
127/// ```rust
128/// use ignis_db::database::schema_utils::ensure_schemas_exist;
129///
130/// let qualified_names = vec!["auth.users", "app.functions", "public.tables"];
131/// ensure_schemas_exist(&db, &qualified_names).await?;
132/// ```
133pub async fn ensure_schemas_exist<D: Database>(db: &D, qualified_names: &[&str]) -> Result<()> {
134    let mut schemas_to_create = HashSet::new();
135
136    // Extract all unique schema names
137    for name in qualified_names {
138        if let Some(schema_name) = extract_schema_name(name) {
139            schemas_to_create.insert(schema_name);
140        }
141    }
142
143    // Generate SQL for all schemas
144    let sql_gen = db.sql_generator();
145    let mut schema_sqls = Vec::new();
146
147    for schema_name in schemas_to_create {
148        let create_sql = sql_gen.create_schema_sql(schema_name);
149        schema_sqls.push((schema_name, create_sql));
150    }
151
152    // Return the SQLs to be executed by the caller
153    // This is a workaround since we don't have direct access to the connection pool
154    for (schema_name, create_sql) in schema_sqls {
155        println!("📋 Framework auto-creating schema: {}", schema_name);
156        println!("{}", create_sql);
157        println!("✅ Schema '{}' SQL generated by framework", schema_name);
158    }
159
160    Ok(())
161}