reinhardt_db/lib.rs
1//! # Reinhardt Database
2//!
3//! Django-style database layer for Reinhardt framework.
4//!
5//! This crate provides a unified database abstraction that combines:
6//! - **Database Backends**: Low-level database operations
7//! - **Connection Pooling**: Advanced connection pool management
8//! - **ORM**: Django-style ORM for database queries
9//! - **Migrations**: Database schema migration system
10//! - **Hybrid Types**: Common database type abstractions
11//! - **Associations**: Relationship management between models
12//!
13//! Equivalent to Django's `django.db` package.
14//!
15//! ## Features
16//!
17//! ### Database Backends (`backends` module)
18//!
19//! - **Schema Editor Abstraction**: Unified `BaseDatabaseSchemaEditor` trait
20//! - **Database-Specific Implementations**: PostgreSQL, MySQL, SQLite support
21//! - **DDL Operations**: CREATE TABLE, ALTER TABLE, CREATE INDEX, etc.
22//! - **Query Builder**: Type-safe query construction
23//!
24//! ### Connection Pooling (`pool` module)
25//!
26//! - **Advanced Pooling**: SQLAlchemy-inspired connection pool management
27//! - **Dependency Injection**: Integration with Reinhardt DI system
28//! - **Event Listeners**: Connection lifecycle hooks
29//! - **Pool Configuration**: Fine-grained control over pool behavior
30//!
31//! ### ORM (`orm` module)
32//!
33//! - **Django-style Models**: Define database models with structs
34//! - **QuerySet API**: Chainable query builder
35//! - **Field Types**: Rich set of field types with validation
36//! - **Relationships**: ForeignKey, ManyToMany, OneToOne
37//!
38//! ### Migrations (`migrations` module)
39//!
40//! - **Schema Migrations**: Track and apply database schema changes
41//! - **Auto-detection**: Automatically detect model changes
42//! - **Migration Files**: Generate migration files from model changes
43//! - **Rollback Support**: Reverse migrations when needed
44//! - **MigrationStateLoader**: Django-style approach for building `ProjectState`
45//! - Replays applied migrations to reconstruct schema state
46//! - Enables accurate change detection without database introspection
47//! - Used internally by `makemigrations` command
48//!
49//! ## Available Database Backends
50//!
51//! The backends crate provides multiple database backend implementations:
52//! - **PostgreSQL**: Full support with connection pooling
53//! - **MySQL**: Full support with connection pooling
54//! - **SQLite**: Full support with connection pooling
55//! - **CockroachDB**: Distributed transaction support
56//!
57//! ## Optimization Features ✅
58//!
59//! - **Connection Pool Optimization**: Idle timeout, dynamic sizing, health checks
60//! - **Query Caching**: LRU cache with TTL for prepared statements and results
61//! - **Batch Operations**: Efficient bulk insert, update, and delete operations
62//!
63//! ## Enhanced Migration Tools ✅
64//!
65//! - **Schema Diff Detection**: Automatic detection of schema changes between DB and models
66//! - **Auto-Migration Generation**: Generate migration files from detected differences
67//! - **Migration Validation**: Pre-execution validation with data loss warnings
68//! - **Rollback Script Generation**: Automatic rollback operations for safe migrations
69//!
70//! ## Quick Start
71//!
72//! ### Using Schema Editor
73//!
74//! ```rust,no_run
75//! # use sqlx::PgPool;
76//! use reinhardt_db::backends::schema::factory::{SchemaEditorFactory, DatabaseType};
77//! use reinhardt_query::prelude::{PostgresQueryBuilder, QueryStatementBuilder};
78//!
79//! # async fn example() -> Result<(), sqlx::Error> {
80//! # let pool = PgPool::connect("postgresql://localhost/mydb").await?;
81//! let factory = SchemaEditorFactory::new_postgres(pool);
82//! let editor = factory.create_for_database(DatabaseType::PostgreSQL);
83//!
84//! let stmt = editor.create_table_statement("users", &[
85//! ("id", "INTEGER PRIMARY KEY"),
86//! ("name", "VARCHAR(100)"),
87//! ]);
88//! let sql = stmt.to_string(PostgresQueryBuilder);
89//! # Ok(())
90//! # }
91//! ```
92//!
93//! ### Using Connection Pool
94//!
95//! ```rust,no_run
96//! use reinhardt_db::pool::{ConnectionPool, PoolConfig};
97//!
98//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
99//! let pool = ConnectionPool::new_postgres("postgres://localhost/mydb", PoolConfig::default()).await?;
100//! let conn = pool.acquire().await?;
101//! # Ok(())
102//! # }
103//! ```
104//!
105//! ## Feature Flags
106//!
107//! - `backends` (default): Database backend abstractions
108//! - `pool` (default): Connection pooling support
109//! - `orm` (default): ORM functionality
110//! - `migrations` (default): Migration system
111//! - `hybrid` (default): Hybrid type system
112//! - `associations` (default): Association management
113//! - `postgres` (default): PostgreSQL support
114//! - `sqlite`: SQLite support
115//! - `mysql`: MySQL support
116//! - `all-databases`: Enable all database backends
117
118pub mod associations;
119pub mod backends;
120pub mod backends_pool;
121pub mod contenttypes;
122pub mod hybrid;
123pub mod migrations;
124#[cfg(feature = "nosql")]
125pub mod nosql;
126pub mod orm;
127pub mod pool;
128
129/// Prelude module for convenient imports
130///
131/// Imports commonly used types from all modules.
132#[allow(ambiguous_glob_reexports)]
133pub mod prelude {
134 #[cfg(feature = "backends")]
135 pub use crate::backends::*;
136
137 #[cfg(feature = "pool")]
138 pub use crate::pool::*;
139
140 #[cfg(feature = "orm")]
141 pub use crate::orm::*;
142
143 #[cfg(feature = "migrations")]
144 pub use crate::migrations::*;
145
146 #[cfg(feature = "hybrid")]
147 pub use crate::hybrid::*;
148
149 #[cfg(feature = "associations")]
150 pub use crate::associations::*;
151
152 #[cfg(feature = "contenttypes")]
153 pub use crate::contenttypes::*;
154
155 #[cfg(feature = "nosql")]
156 pub use crate::nosql::*;
157
158 // Re-export types needed by Model derive macro
159 #[cfg(feature = "migrations")]
160 pub use crate::migrations::model_registry::{FieldMetadata, global_registry};
161}
162
163// Re-export top-level commonly used types
164#[cfg(feature = "backends")]
165pub use backends::{DatabaseBackend, DatabaseError};
166
167// Re-export ORM's DatabaseConnection which wraps BackendsConnection
168// This is the type used by Manager and other ORM components
169#[cfg(feature = "orm")]
170pub use orm::DatabaseConnection;
171
172#[cfg(feature = "pool")]
173pub use pool::{ConnectionPool, PoolConfig, PoolError};