elif_orm/
error.rs

1//! Error types for the ORM system
2//!
3//! Provides comprehensive error handling for database operations,
4//! model validation, and query building.
5
6use std::fmt;
7
8/// Result type alias for model operations
9pub type ModelResult<T> = Result<T, ModelError>;
10
11/// Error types for ORM operations
12#[derive(Debug, Clone)]
13pub enum ModelError {
14    /// Database connection or query error
15    Database(String),
16    /// Model not found in database
17    NotFound(String),
18    /// Model validation failed
19    Validation(String),
20    /// Primary key is missing or invalid
21    MissingPrimaryKey,
22    /// Relationship loading failed
23    Relationship(String),
24    /// Serialization/deserialization error
25    Serialization(String),
26    /// Migration error
27    Migration(String),
28    /// Connection pool error
29    Connection(String),
30    /// Transaction error
31    Transaction(String),
32    /// Schema error
33    Schema(String),
34    /// Query building error
35    Query(String),
36    /// Event system error
37    Event(String),
38}
39
40impl fmt::Display for ModelError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            ModelError::Database(msg) => write!(f, "Database error: {}", msg),
44            ModelError::NotFound(table) => write!(f, "Record not found in table '{}'", table),
45            ModelError::Validation(msg) => write!(f, "Validation error: {}", msg),
46            ModelError::MissingPrimaryKey => write!(f, "Primary key is missing or invalid"),
47            ModelError::Relationship(msg) => write!(f, "Relationship error: {}", msg),
48            ModelError::Serialization(msg) => write!(f, "Serialization error: {}", msg),
49            ModelError::Migration(msg) => write!(f, "Migration error: {}", msg),
50            ModelError::Connection(msg) => write!(f, "Connection error: {}", msg),
51            ModelError::Transaction(msg) => write!(f, "Transaction error: {}", msg),
52            ModelError::Schema(msg) => write!(f, "Schema error: {}", msg),
53            ModelError::Query(msg) => write!(f, "Query error: {}", msg),
54            ModelError::Event(msg) => write!(f, "Event error: {}", msg),
55        }
56    }
57}
58
59impl std::error::Error for ModelError {}
60
61// Convert from sqlx errors
62impl From<sqlx::Error> for ModelError {
63    fn from(err: sqlx::Error) -> Self {
64        ModelError::Database(err.to_string())
65    }
66}
67
68// Convert from serde_json errors
69impl From<serde_json::Error> for ModelError {
70    fn from(err: serde_json::Error) -> Self {
71        ModelError::Serialization(err.to_string())
72    }
73}
74
75// Convert from anyhow errors
76impl From<anyhow::Error> for ModelError {
77    fn from(err: anyhow::Error) -> Self {
78        ModelError::Database(err.to_string())
79    }
80}
81
82/// Error types for query builder operations
83#[derive(Debug, Clone)]
84pub enum QueryError {
85    /// Invalid SQL syntax
86    InvalidSql(String),
87    /// Missing required fields
88    MissingFields(String),
89    /// Invalid parameter binding
90    InvalidParameter(String),
91    /// Unsupported operation
92    UnsupportedOperation(String),
93}
94
95impl fmt::Display for QueryError {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            QueryError::InvalidSql(msg) => write!(f, "Invalid SQL: {}", msg),
99            QueryError::MissingFields(msg) => write!(f, "Missing fields: {}", msg),
100            QueryError::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg),
101            QueryError::UnsupportedOperation(msg) => write!(f, "Unsupported operation: {}", msg),
102        }
103    }
104}
105
106impl std::error::Error for QueryError {}
107
108impl From<QueryError> for ModelError {
109    fn from(err: QueryError) -> Self {
110        ModelError::Query(err.to_string())
111    }
112}
113
114/// Error types for relationship operations
115#[derive(Debug, Clone)]
116pub enum RelationshipError {
117    /// Relationship not found
118    NotFound(String),
119    /// Invalid relationship configuration
120    InvalidConfiguration(String),
121    /// Circular dependency in relationships
122    CircularDependency(String),
123    /// Foreign key constraint violation
124    ForeignKeyViolation(String),
125}
126
127impl fmt::Display for RelationshipError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        match self {
130            RelationshipError::NotFound(msg) => write!(f, "Relationship not found: {}", msg),
131            RelationshipError::InvalidConfiguration(msg) => write!(f, "Invalid relationship configuration: {}", msg),
132            RelationshipError::CircularDependency(msg) => write!(f, "Circular dependency: {}", msg),
133            RelationshipError::ForeignKeyViolation(msg) => write!(f, "Foreign key violation: {}", msg),
134        }
135    }
136}
137
138impl std::error::Error for RelationshipError {}
139
140impl From<RelationshipError> for ModelError {
141    fn from(err: RelationshipError) -> Self {
142        ModelError::Relationship(err.to_string())
143    }
144}
145
146/// Error types for migration operations
147#[derive(Debug, Clone)]
148pub enum MigrationError {
149    /// Migration file not found
150    FileNotFound(String),
151    /// Invalid migration syntax
152    InvalidSyntax(String),
153    /// Migration already applied
154    AlreadyApplied(String),
155    /// Migration rollback failed
156    RollbackFailed(String),
157    /// Version conflict
158    VersionConflict(String),
159}
160
161impl fmt::Display for MigrationError {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            MigrationError::FileNotFound(msg) => write!(f, "Migration file not found: {}", msg),
165            MigrationError::InvalidSyntax(msg) => write!(f, "Invalid migration syntax: {}", msg),
166            MigrationError::AlreadyApplied(msg) => write!(f, "Migration already applied: {}", msg),
167            MigrationError::RollbackFailed(msg) => write!(f, "Migration rollback failed: {}", msg),
168            MigrationError::VersionConflict(msg) => write!(f, "Version conflict: {}", msg),
169        }
170    }
171}
172
173impl std::error::Error for MigrationError {}
174
175impl From<MigrationError> for ModelError {
176    fn from(err: MigrationError) -> Self {
177        ModelError::Migration(err.to_string())
178    }
179}
180
181/// Error types for event system operations
182#[derive(Debug, Clone)]
183pub enum EventError {
184    /// Event handler failed
185    HandlerFailed(String),
186    /// Event propagation stopped
187    PropagationStopped(String),
188    /// Invalid event configuration
189    InvalidConfiguration(String),
190}
191
192impl fmt::Display for EventError {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        match self {
195            EventError::HandlerFailed(msg) => write!(f, "Event handler failed: {}", msg),
196            EventError::PropagationStopped(msg) => write!(f, "Event propagation stopped: {}", msg),
197            EventError::InvalidConfiguration(msg) => write!(f, "Invalid event configuration: {}", msg),
198        }
199    }
200}
201
202impl std::error::Error for EventError {}
203
204impl From<EventError> for ModelError {
205    fn from(err: EventError) -> Self {
206        ModelError::Event(err.to_string())
207    }
208}