Skip to main content

ignis_db/
lib.rs

1//! Ignis: A comprehensive PostgreSQL ORM with macro-driven schema management
2//!
3//! This crate provides compile-time type safety with sqlx execution,
4//! comprehensive macro system, and sophisticated migration management.
5
6pub mod builders;
7pub mod code_parsing;
8pub mod codegen;
9pub mod common;
10pub mod config;
11pub mod connection;
12pub mod database;
13pub mod dsl;
14pub mod exec;
15pub mod introspection;
16pub mod macros;
17pub mod migrate;
18pub mod schema;
19
20// Re-export commonly used items
21pub use connection::{ConnectionManager, PoolStats};
22pub use database::{Database, DatabaseConfig, DatabaseType, MySQL, PostgreSQL};
23pub use dsl::{
24    call_function, call_procedure, Column as DslColumn, CompositeField, CompositeFieldBuilder,
25    CompositeFieldRef, FunctionCall, ProcedureCall, Query, Source,
26};
27pub use exec::transaction::{
28    execute_transaction, IsolationLevel, TransactionConfig, TransactionManager,
29};
30pub use schema::{
31    Column, ColumnType, CompositeField as SchemaCompositeField, CompositeType, IndexMeta,
32    IndexType, StoredFunction, StoredProcedure, Table, TableMeta, Trigger, TriggerEvent,
33    TriggerOrientation, TriggerTiming,
34};
35
36// Re-export derive macros
37pub use ignis_derive::*;
38
39// Note: table! macro is automatically exported due to #[macro_export]
40
41// Re-export common types for derive macros
42pub use anyhow::{anyhow, Result};
43
44/// Core trait that all Ignis objects must implement
45pub trait IgnisObject: Send + Sync {
46    /// Get the name of this object
47    fn name(&self) -> &str;
48
49    /// Get the schema this object belongs to (if any)
50    fn schema(&self) -> Option<&str>;
51
52    /// Get the DDL for creating this object
53    fn ddl(&self) -> &str;
54
55    /// Get the type of this object
56    fn object_type(&self) -> &str;
57}
58
59/// Schema object that can be registered in the inventory system
60#[derive(Debug, Clone)]
61pub struct SchemaObject {
62    pub kind: &'static str,
63    pub name: &'static str,
64    pub ddl: &'static str,
65    pub schema: Option<&'static str>,
66}
67
68impl IgnisObject for SchemaObject {
69    #[inline]
70    fn name(&self) -> &str {
71        self.name
72    }
73
74    #[inline]
75    fn schema(&self) -> Option<&str> {
76        self.schema
77    }
78
79    #[inline]
80    fn ddl(&self) -> &str {
81        self.ddl
82    }
83
84    #[inline]
85    fn object_type(&self) -> &str {
86        self.kind
87    }
88}
89
90/// Wrapper type for inventory registration
91pub struct RegisteredObject(pub SchemaObject);
92
93// Automatic registration via inventory
94inventory::collect!(RegisteredObject);
95
96/// Type alias for registered objects in the inventory
97pub type RegisteredObjectRef = &'static RegisteredObject;
98
99/// Get an iterator over all registered schema objects
100pub fn iter_registered() -> impl Iterator<Item = &'static RegisteredObject> {
101    inventory::iter::<RegisteredObject>()
102}
103
104/// Get all registered objects of a specific type
105pub fn get_registered_by_type(
106    object_type: &str,
107) -> impl Iterator<Item = &'static RegisteredObject> + '_ {
108    iter_registered().filter(move |obj| obj.0.object_type() == object_type)
109}
110
111/// Get all registered tables
112pub fn get_registered_tables() -> impl Iterator<Item = &'static RegisteredObject> {
113    get_registered_by_type("table")
114}
115
116/// Get all registered views
117pub fn get_registered_views() -> impl Iterator<Item = &'static RegisteredObject> {
118    get_registered_by_type("view")
119}
120
121/// Get all registered procedures
122pub fn get_registered_procedures() -> impl Iterator<Item = &'static RegisteredObject> {
123    get_registered_by_type("procedure")
124}
125
126/// Get all registered functions
127pub fn get_registered_functions() -> impl Iterator<Item = &'static RegisteredObject> {
128    get_registered_by_type("function")
129}
130
131/// Get all registered triggers
132pub fn get_registered_triggers() -> impl Iterator<Item = &'static RegisteredObject> {
133    get_registered_by_type("trigger")
134}
135
136/// Get all registered events
137pub fn get_registered_events() -> impl Iterator<Item = &'static RegisteredObject> {
138    get_registered_by_type("event")
139}
140
141// Model traits for CRUD operations
142pub trait IgnisModel {
143    const TABLE: &'static str;
144    const PK: &'static str; // For single PK or comma-separated list for composite
145    const SCHEMA: Option<&'static str>;
146    const FULL_TABLE_NAME: &'static str;
147
148    fn get_primary_key_value(&self) -> anyhow::Result<BindValue>;
149    fn get_composite_key_values(&self) -> anyhow::Result<Vec<(&'static str, BindValue)>> {
150        // Default implementation for single primary key
151        Ok(vec![(Self::PK, self.get_primary_key_value()?)])
152    }
153}
154
155pub trait Insertable {
156    fn insert<'e, E>(
157        &self,
158        executor: E,
159    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
160    where
161        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
162}
163
164pub trait Updatable {
165    fn update<'e, E>(
166        &self,
167        executor: E,
168    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
169    where
170        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
171}
172
173pub trait Deletable {
174    fn delete<'e, E>(
175        &self,
176        executor: E,
177    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
178    where
179        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
180}
181
182// BindValue enum for type-safe parameter binding
183// Re-export the consolidated BindValue from parameter_binding module
184pub use macros::parameter_binding::BindValue;
185
186// From implementations are now in the consolidated BindValue in parameter_binding module
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    // Test table definition
193    crate::table! {
194        users (id) {
195            id -> Int4,
196            email -> Varchar,
197            created_at -> Timestamptz,
198        }
199    }
200
201    #[test]
202    fn test_table_macro() {
203        // Test that the table module was created
204        let table = users::table();
205        assert_eq!(table.name, "users");
206        assert_eq!(table.primary_key, Some("id".to_string()));
207        assert_eq!(table.columns.len(), 3);
208
209        // Test column accessors
210        let id_col = users::id();
211        assert_eq!(id_col.name, "id");
212
213        let email_col = users::email();
214        assert_eq!(email_col.name, "email");
215
216        let created_at_col = users::created_at();
217        assert_eq!(created_at_col.name, "created_at");
218    }
219
220    #[test]
221    fn test_table_ddl_generation() {
222        let table = users::table();
223        let ddl = table.generate_ddl();
224
225        // Verify the DDL contains expected elements
226        assert!(ddl.contains("CREATE TABLE"));
227        assert!(ddl.contains("\"users\""));
228        assert!(ddl.contains("\"id\""));
229        assert!(ddl.contains("\"email\""));
230        assert!(ddl.contains("\"created_at\""));
231        assert!(ddl.contains("PRIMARY KEY"));
232        assert!(ddl.contains("INTEGER"));
233        assert!(ddl.contains("VARCHAR"));
234        assert!(ddl.contains("TIMESTAMPTZ"));
235    }
236
237    #[test]
238    fn test_registered_tables() {
239        // Test that tables are registered in the inventory
240        let tables: Vec<_> = get_registered_tables().collect();
241        assert!(!tables.is_empty());
242
243        // Find our users table
244        let users_table = tables.iter().find(|t| t.0.name == "users");
245        assert!(users_table.is_some());
246
247        if let Some(table) = users_table {
248            assert_eq!(table.0.object_type(), "table");
249            assert!(table.0.ddl.contains("CREATE TABLE"));
250        }
251    }
252}