Skip to main content

prax_query/
error.rs

1//! Comprehensive error types for query operations with actionable messages.
2//!
3//! This module provides detailed error types that include:
4//! - Error codes for programmatic handling
5//! - Actionable suggestions for fixing issues
6//! - Context about what operation failed
7//! - Help text and documentation links
8//!
9//! # Error Codes
10//!
11//! Error codes follow a pattern: P{category}{number}
12//! - 1xxx: Query errors (not found, invalid filter, etc.)
13//! - 2xxx: Constraint violations (unique, foreign key, etc.)
14//! - 3xxx: Connection errors (timeout, pool, auth)
15//! - 4xxx: Transaction errors (deadlock, serialization)
16//! - 5xxx: Execution errors (timeout, syntax, params)
17//! - 6xxx: Data errors (type, serialization)
18//! - 7xxx: Configuration errors
19//! - 8xxx: Migration errors
20//! - 9xxx: Tenant errors
21//!
22//! ```rust
23//! use prax_query::ErrorCode;
24//!
25//! // Error codes have string representations
26//! let code = ErrorCode::RecordNotFound;
27//! let code = ErrorCode::UniqueConstraint;
28//! let code = ErrorCode::ConnectionFailed;
29//! ```
30//!
31//! # Creating Errors
32//!
33//! ```rust
34//! use prax_query::{QueryError, ErrorCode};
35//!
36//! // Not found error
37//! let err = QueryError::not_found("User");
38//! assert_eq!(err.code, ErrorCode::RecordNotFound);
39//!
40//! // Generic error with code
41//! let err = QueryError::new(ErrorCode::UniqueConstraint, "Email already exists");
42//! assert_eq!(err.code, ErrorCode::UniqueConstraint);
43//! ```
44//!
45//! # Error Properties
46//!
47//! ```rust
48//! use prax_query::{QueryError, ErrorCode};
49//!
50//! let err = QueryError::not_found("User");
51//!
52//! // Access error code (public field)
53//! assert_eq!(err.code, ErrorCode::RecordNotFound);
54//!
55//! // Access error message
56//! let message = err.to_string();
57//! assert!(message.contains("User"));
58//! ```
59
60use std::fmt;
61use thiserror::Error;
62
63/// Result type for query operations.
64pub type QueryResult<T> = Result<T, QueryError>;
65
66/// Error codes for programmatic error handling.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub enum ErrorCode {
69    // Query errors (1xxx)
70    /// Record not found (P1001).
71    RecordNotFound = 1001,
72    /// Multiple records found when expecting one (P1002).
73    NotUnique = 1002,
74    /// Invalid filter or where clause (P1003).
75    InvalidFilter = 1003,
76    /// Invalid select or include (P1004).
77    InvalidSelect = 1004,
78    /// Required field missing (P1005).
79    RequiredFieldMissing = 1005,
80
81    // Constraint errors (2xxx)
82    /// Unique constraint violation (P2001).
83    UniqueConstraint = 2001,
84    /// Foreign key constraint violation (P2002).
85    ForeignKeyConstraint = 2002,
86    /// Check constraint violation (P2003).
87    CheckConstraint = 2003,
88    /// Not null constraint violation (P2004).
89    NotNullConstraint = 2004,
90
91    // Connection errors (3xxx)
92    /// Database connection failed (P3001).
93    ConnectionFailed = 3001,
94    /// Connection pool exhausted (P3002).
95    PoolExhausted = 3002,
96    /// Connection timeout (P3003).
97    ConnectionTimeout = 3003,
98    /// Authentication failed (P3004).
99    AuthenticationFailed = 3004,
100    /// SSL/TLS error (P3005).
101    SslError = 3005,
102
103    // Transaction errors (4xxx)
104    /// Transaction failed (P4001).
105    TransactionFailed = 4001,
106    /// Deadlock detected (P4002).
107    Deadlock = 4002,
108    /// Serialization failure (P4003).
109    SerializationFailure = 4003,
110    /// Transaction already committed/rolled back (P4004).
111    TransactionClosed = 4004,
112
113    // Query execution errors (5xxx)
114    /// Query timeout (P5001).
115    QueryTimeout = 5001,
116    /// SQL syntax error (P5002).
117    SqlSyntax = 5002,
118    /// Invalid parameter (P5003).
119    InvalidParameter = 5003,
120    /// Query too complex (P5004).
121    QueryTooComplex = 5004,
122    /// General database error (P5005).
123    DatabaseError = 5005,
124
125    // Data errors (6xxx)
126    /// Invalid data type (P6001).
127    InvalidDataType = 6001,
128    /// Serialization error (P6002).
129    SerializationError = 6002,
130    /// Deserialization error (P6003).
131    DeserializationError = 6003,
132    /// Data truncation (P6004).
133    DataTruncation = 6004,
134
135    // Configuration errors (7xxx)
136    /// Invalid configuration (P7001).
137    InvalidConfiguration = 7001,
138    /// Missing configuration (P7002).
139    MissingConfiguration = 7002,
140    /// Invalid connection string (P7003).
141    InvalidConnectionString = 7003,
142
143    // Internal errors (9xxx)
144    /// Internal error (P9001).
145    Internal = 9001,
146    /// Unknown error (P9999).
147    Unknown = 9999,
148}
149
150impl ErrorCode {
151    /// Get the error code string (e.g., "P1001").
152    pub fn code(&self) -> String {
153        format!("P{}", *self as u16)
154    }
155
156    /// Get a short description of the error code.
157    pub fn description(&self) -> &'static str {
158        match self {
159            Self::RecordNotFound => "Record not found",
160            Self::NotUnique => "Multiple records found",
161            Self::InvalidFilter => "Invalid filter condition",
162            Self::InvalidSelect => "Invalid select or include",
163            Self::RequiredFieldMissing => "Required field missing",
164            Self::UniqueConstraint => "Unique constraint violation",
165            Self::ForeignKeyConstraint => "Foreign key constraint violation",
166            Self::CheckConstraint => "Check constraint violation",
167            Self::NotNullConstraint => "Not null constraint violation",
168            Self::ConnectionFailed => "Database connection failed",
169            Self::PoolExhausted => "Connection pool exhausted",
170            Self::ConnectionTimeout => "Connection timeout",
171            Self::AuthenticationFailed => "Authentication failed",
172            Self::SslError => "SSL/TLS error",
173            Self::TransactionFailed => "Transaction failed",
174            Self::Deadlock => "Deadlock detected",
175            Self::SerializationFailure => "Serialization failure",
176            Self::TransactionClosed => "Transaction already closed",
177            Self::QueryTimeout => "Query timeout",
178            Self::SqlSyntax => "SQL syntax error",
179            Self::InvalidParameter => "Invalid parameter",
180            Self::QueryTooComplex => "Query too complex",
181            Self::DatabaseError => "Database error",
182            Self::InvalidDataType => "Invalid data type",
183            Self::SerializationError => "Serialization error",
184            Self::DeserializationError => "Deserialization error",
185            Self::DataTruncation => "Data truncation",
186            Self::InvalidConfiguration => "Invalid configuration",
187            Self::MissingConfiguration => "Missing configuration",
188            Self::InvalidConnectionString => "Invalid connection string",
189            Self::Internal => "Internal error",
190            Self::Unknown => "Unknown error",
191        }
192    }
193
194    /// Get the documentation URL for this error.
195    pub fn docs_url(&self) -> String {
196        format!("https://prax.rs/docs/errors/{}", self.code())
197    }
198}
199
200impl fmt::Display for ErrorCode {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        write!(f, "{}", self.code())
203    }
204}
205
206/// Suggestion for fixing an error.
207#[derive(Debug, Clone)]
208pub struct Suggestion {
209    /// The suggestion text.
210    pub text: String,
211    /// Optional code example.
212    pub code: Option<String>,
213}
214
215impl Suggestion {
216    /// Create a new suggestion.
217    pub fn new(text: impl Into<String>) -> Self {
218        Self {
219            text: text.into(),
220            code: None,
221        }
222    }
223
224    /// Add a code example.
225    pub fn with_code(mut self, code: impl Into<String>) -> Self {
226        self.code = Some(code.into());
227        self
228    }
229}
230
231/// Additional context for an error.
232#[derive(Debug, Clone, Default)]
233pub struct ErrorContext {
234    /// The operation that was being performed.
235    pub operation: Option<String>,
236    /// The model involved.
237    pub model: Option<String>,
238    /// The field involved.
239    pub field: Option<String>,
240    /// The SQL query (if available).
241    pub sql: Option<String>,
242    /// Suggestions for fixing the error.
243    pub suggestions: Vec<Suggestion>,
244    /// Help text.
245    pub help: Option<String>,
246    /// Related errors.
247    pub related: Vec<String>,
248}
249
250impl ErrorContext {
251    /// Create new empty context.
252    pub fn new() -> Self {
253        Self::default()
254    }
255
256    /// Set the operation.
257    pub fn operation(mut self, op: impl Into<String>) -> Self {
258        self.operation = Some(op.into());
259        self
260    }
261
262    /// Set the model.
263    pub fn model(mut self, model: impl Into<String>) -> Self {
264        self.model = Some(model.into());
265        self
266    }
267
268    /// Set the field.
269    pub fn field(mut self, field: impl Into<String>) -> Self {
270        self.field = Some(field.into());
271        self
272    }
273
274    /// Set the SQL query.
275    pub fn sql(mut self, sql: impl Into<String>) -> Self {
276        self.sql = Some(sql.into());
277        self
278    }
279
280    /// Add a suggestion.
281    pub fn suggestion(mut self, suggestion: Suggestion) -> Self {
282        self.suggestions.push(suggestion);
283        self
284    }
285
286    /// Add a text suggestion.
287    pub fn suggest(mut self, text: impl Into<String>) -> Self {
288        self.suggestions.push(Suggestion::new(text));
289        self
290    }
291
292    /// Set help text.
293    pub fn help(mut self, help: impl Into<String>) -> Self {
294        self.help = Some(help.into());
295        self
296    }
297}
298
299/// Errors that can occur during query operations.
300#[derive(Error, Debug)]
301pub struct QueryError {
302    /// The error code.
303    pub code: ErrorCode,
304    /// The error message.
305    pub message: String,
306    /// Additional context.
307    pub context: ErrorContext,
308    /// The source error (if any).
309    #[source]
310    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
311    /// The SQLSTATE of the database error behind this one; see
312    /// [`QueryError::sqlstate`].
313    sqlstate: Option<String>,
314}
315
316impl fmt::Display for QueryError {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        write!(f, "[{}] {}", self.code.code(), self.message)
319    }
320}
321
322impl QueryError {
323    /// Create a new error with the given code and message.
324    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
325        Self {
326            code,
327            message: message.into(),
328            context: ErrorContext::default(),
329            source: None,
330            sqlstate: None,
331        }
332    }
333
334    /// The five-character SQLSTATE code of the database error this came
335    /// from (for example `"23505"` unique violation or `"55P03"` lock not
336    /// available), when the driver reported one.
337    ///
338    /// Set by `prax-postgres` and by `prax-sqlx` for PostgreSQL errors.
339    /// `None` for errors that did not come from the server (timeouts,
340    /// pool errors, client-side validation) and for drivers that do not
341    /// report a SQLSTATE.
342    pub fn sqlstate(&self) -> Option<&str> {
343        self.sqlstate.as_deref()
344    }
345
346    /// Record the SQLSTATE of the database error behind this one (see
347    /// [`sqlstate`](Self::sqlstate)).
348    pub fn with_sqlstate(mut self, sqlstate: impl Into<String>) -> Self {
349        self.sqlstate = Some(sqlstate.into());
350        self
351    }
352
353    /// Add context about the operation.
354    pub fn with_context(mut self, operation: impl Into<String>) -> Self {
355        self.context.operation = Some(operation.into());
356        self
357    }
358
359    /// Add a suggestion for fixing the error.
360    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
361        self.context.suggestions.push(Suggestion::new(suggestion));
362        self
363    }
364
365    /// Add a code suggestion.
366    pub fn with_code_suggestion(
367        mut self,
368        text: impl Into<String>,
369        code: impl Into<String>,
370    ) -> Self {
371        self.context
372            .suggestions
373            .push(Suggestion::new(text).with_code(code));
374        self
375    }
376
377    /// Add help text.
378    pub fn with_help(mut self, help: impl Into<String>) -> Self {
379        self.context.help = Some(help.into());
380        self
381    }
382
383    /// Set the model.
384    pub fn with_model(mut self, model: impl Into<String>) -> Self {
385        self.context.model = Some(model.into());
386        self
387    }
388
389    /// Set the field.
390    pub fn with_field(mut self, field: impl Into<String>) -> Self {
391        self.context.field = Some(field.into());
392        self
393    }
394
395    /// Set the SQL query.
396    pub fn with_sql(mut self, sql: impl Into<String>) -> Self {
397        self.context.sql = Some(sql.into());
398        self
399    }
400
401    /// Set the source error.
402    pub fn with_source<E: std::error::Error + Send + Sync + 'static>(mut self, source: E) -> Self {
403        self.source = Some(Box::new(source));
404        self
405    }
406
407    // ============== Constructor Functions ==============
408
409    /// Create a not found error.
410    pub fn not_found(model: impl Into<String>) -> Self {
411        let model = model.into();
412        Self::new(
413            ErrorCode::RecordNotFound,
414            format!("No {} record found matching the query", model),
415        )
416        .with_model(&model)
417        .with_suggestion(format!("Verify the {} exists before querying", model))
418        .with_code_suggestion(
419            "Use findFirst() instead to get None instead of an error",
420            format!(
421                "client.{}().find_first().r#where(...).exec().await",
422                model.to_lowercase()
423            ),
424        )
425    }
426
427    /// Create a not unique error.
428    pub fn not_unique(model: impl Into<String>) -> Self {
429        let model = model.into();
430        Self::new(
431            ErrorCode::NotUnique,
432            format!("Expected unique {} record but found multiple", model),
433        )
434        .with_model(&model)
435        .with_suggestion("Add more specific filters to narrow down to a single record")
436        .with_suggestion("Use find_many() if you expect multiple results")
437    }
438
439    /// Create a constraint violation error.
440    pub fn constraint_violation(model: impl Into<String>, message: impl Into<String>) -> Self {
441        let model = model.into();
442        let message = message.into();
443        Self::new(
444            ErrorCode::UniqueConstraint,
445            format!("Constraint violation on {}: {}", model, message),
446        )
447        .with_model(&model)
448    }
449
450    /// Create a unique constraint violation error.
451    pub fn unique_violation(model: impl Into<String>, field: impl Into<String>) -> Self {
452        let model = model.into();
453        let field = field.into();
454        Self::new(
455            ErrorCode::UniqueConstraint,
456            format!("Unique constraint violated on {}.{}", model, field),
457        )
458        .with_model(&model)
459        .with_field(&field)
460        .with_suggestion(format!("A record with this {} already exists", field))
461        .with_code_suggestion(
462            "Use upsert() to update if exists, create if not",
463            format!(
464                "client.{}().upsert()\n  .r#where({}::{}::equals(value))\n  .create(...)\n  .update(...)\n  .exec().await",
465                model.to_lowercase(), model.to_lowercase(), field
466            ),
467        )
468    }
469
470    /// Create a foreign key violation error.
471    pub fn foreign_key_violation(model: impl Into<String>, relation: impl Into<String>) -> Self {
472        let model = model.into();
473        let relation = relation.into();
474        Self::new(
475            ErrorCode::ForeignKeyConstraint,
476            format!("Foreign key constraint violated: {} -> {}", model, relation),
477        )
478        .with_model(&model)
479        .with_field(&relation)
480        .with_suggestion(format!(
481            "Ensure the related {} record exists before creating this {}",
482            relation, model
483        ))
484        .with_suggestion("Check for typos in the relation ID")
485    }
486
487    /// Create a not null violation error.
488    pub fn not_null_violation(model: impl Into<String>, field: impl Into<String>) -> Self {
489        let model = model.into();
490        let field = field.into();
491        Self::new(
492            ErrorCode::NotNullConstraint,
493            format!("Cannot set {}.{} to null - field is required", model, field),
494        )
495        .with_model(&model)
496        .with_field(&field)
497        .with_suggestion(format!("Provide a value for the {} field", field))
498        .with_help("Make the field optional in your schema if null should be allowed")
499    }
500
501    /// Create an invalid input error.
502    pub fn invalid_input(field: impl Into<String>, message: impl Into<String>) -> Self {
503        let field = field.into();
504        let message = message.into();
505        Self::new(
506            ErrorCode::InvalidParameter,
507            format!("Invalid input for {}: {}", field, message),
508        )
509        .with_field(&field)
510    }
511
512    /// Create a connection error.
513    pub fn connection(message: impl Into<String>) -> Self {
514        let message = message.into();
515        Self::new(
516            ErrorCode::ConnectionFailed,
517            format!("Connection error: {}", message),
518        )
519        .with_suggestion("Check that the database server is running")
520        .with_suggestion("Verify the connection URL is correct")
521        .with_suggestion("Check firewall settings allow the connection")
522    }
523
524    /// Create a connection timeout error.
525    pub fn connection_timeout(duration_ms: u64) -> Self {
526        Self::new(
527            ErrorCode::ConnectionTimeout,
528            format!("Connection timed out after {}ms", duration_ms),
529        )
530        .with_suggestion("Increase the connect_timeout in your connection string")
531        .with_suggestion("Check network connectivity to the database server")
532        .with_code_suggestion(
533            "Add connect_timeout to your connection URL",
534            "postgres://user:pass@host/db?connect_timeout=30",
535        )
536    }
537
538    /// Create a pool exhausted error.
539    pub fn pool_exhausted(max_connections: u32) -> Self {
540        Self::new(
541            ErrorCode::PoolExhausted,
542            format!("Connection pool exhausted (max {} connections)", max_connections),
543        )
544        .with_suggestion("Increase max_connections in pool configuration")
545        .with_suggestion("Ensure connections are being released properly")
546        .with_suggestion("Check for connection leaks in your application")
547        .with_help("Consider using connection pooling middleware like PgBouncer for high-traffic applications")
548    }
549
550    /// Create an authentication error.
551    pub fn authentication_failed(message: impl Into<String>) -> Self {
552        let message = message.into();
553        Self::new(
554            ErrorCode::AuthenticationFailed,
555            format!("Authentication failed: {}", message),
556        )
557        .with_suggestion("Check username and password in connection string")
558        .with_suggestion("Verify the user has permission to access the database")
559        .with_suggestion("Check pg_hba.conf (PostgreSQL) or user privileges (MySQL)")
560    }
561
562    /// Create a timeout error.
563    pub fn timeout(duration_ms: u64) -> Self {
564        Self::new(
565            ErrorCode::QueryTimeout,
566            format!("Query timed out after {}ms", duration_ms),
567        )
568        .with_suggestion("Optimize the query to run faster")
569        .with_suggestion("Add indexes to improve query performance")
570        .with_suggestion("Increase the query timeout if the query is expected to be slow")
571        .with_help("Consider paginating large result sets")
572    }
573
574    /// Create a transaction error.
575    pub fn transaction(message: impl Into<String>) -> Self {
576        let message = message.into();
577        Self::new(
578            ErrorCode::TransactionFailed,
579            format!("Transaction error: {}", message),
580        )
581    }
582
583    /// Create a deadlock error.
584    pub fn deadlock() -> Self {
585        Self::new(
586            ErrorCode::Deadlock,
587            "Deadlock detected - transaction was rolled back".to_string(),
588        )
589        .with_suggestion("Retry the transaction")
590        .with_suggestion("Access tables in a consistent order across transactions")
591        .with_suggestion("Keep transactions short to reduce lock contention")
592        .with_help("Deadlocks occur when two transactions wait for each other's locks")
593    }
594
595    /// Create a stale-cached-plan error.
596    ///
597    /// PostgreSQL raises `0A000 "cached plan must not change result type"`
598    /// when a server-side prepared statement is reused after DDL has altered
599    /// the result columns of the tables it references (for example, a pooled
600    /// connection that prepared a statement before an `ALTER TABLE … ADD
601    /// COLUMN`). The condition is transient: discarding the stale plan and
602    /// re-preparing against the current schema resolves it, so this maps to
603    /// the retryable [`ErrorCode::SerializationFailure`] class rather than the
604    /// terminal generic [`ErrorCode::DatabaseError`]. That lets the retry
605    /// middleware re-run the query transparently on a fresh statement instead
606    /// of surfacing an opaque `P5005` to the caller.
607    pub fn stale_plan(message: impl Into<String>) -> Self {
608        Self::new(ErrorCode::SerializationFailure, message.into())
609            .with_suggestion("Retry the query; the cached plan will be re-prepared")
610            .with_help(
611                "A prepared statement was reused after DDL changed a referenced table's result \
612                 columns. This is transient and clears on re-prepare.",
613            )
614    }
615
616    /// Create an SQL syntax error.
617    pub fn sql_syntax(message: impl Into<String>, sql: impl Into<String>) -> Self {
618        let message = message.into();
619        let sql = sql.into();
620        Self::new(
621            ErrorCode::SqlSyntax,
622            format!("SQL syntax error: {}", message),
623        )
624        .with_sql(&sql)
625        .with_suggestion("Check the generated SQL for errors")
626        .with_help("This is likely a bug in Prax - please report it")
627    }
628
629    /// Create a serialization error.
630    pub fn serialization(message: impl Into<String>) -> Self {
631        Self::new(ErrorCode::SerializationError, message.into())
632    }
633
634    /// Create a deserialization error.
635    pub fn deserialization(message: impl Into<String>) -> Self {
636        let message = message.into();
637        Self::new(
638            ErrorCode::DeserializationError,
639            format!("Failed to deserialize result: {}", message),
640        )
641        .with_suggestion("Check that the model matches the database schema")
642        .with_suggestion("Ensure data types are compatible")
643    }
644
645    /// Create a general database error.
646    pub fn database(message: impl Into<String>) -> Self {
647        let message = message.into();
648        Self::new(ErrorCode::DatabaseError, message)
649            .with_suggestion("Check the database logs for more details")
650    }
651
652    /// Create an internal error.
653    pub fn internal(message: impl Into<String>) -> Self {
654        let message = message.into();
655        Self::new(ErrorCode::Internal, format!("Internal error: {}", message))
656            .with_help("This is likely a bug in Prax ORM - please report it at https://github.com/quinnjr/prax/issues")
657    }
658
659    /// Create an unsupported operation error.
660    pub fn unsupported(message: impl Into<String>) -> Self {
661        let message = message.into();
662        Self::new(
663            ErrorCode::InvalidConfiguration,
664            format!("Unsupported: {}", message),
665        )
666        .with_help("This operation is not supported by the current database driver")
667    }
668
669    // ============== Error Checks ==============
670
671    /// Check if this is a not found error.
672    pub fn is_not_found(&self) -> bool {
673        self.code == ErrorCode::RecordNotFound
674    }
675
676    /// Check if this is a constraint violation.
677    pub fn is_constraint_violation(&self) -> bool {
678        matches!(
679            self.code,
680            ErrorCode::UniqueConstraint
681                | ErrorCode::ForeignKeyConstraint
682                | ErrorCode::CheckConstraint
683                | ErrorCode::NotNullConstraint
684        )
685    }
686
687    /// Check if this is a timeout error.
688    pub fn is_timeout(&self) -> bool {
689        matches!(
690            self.code,
691            ErrorCode::QueryTimeout | ErrorCode::ConnectionTimeout
692        )
693    }
694
695    /// Check if this is a connection error.
696    pub fn is_connection_error(&self) -> bool {
697        matches!(
698            self.code,
699            ErrorCode::ConnectionFailed
700                | ErrorCode::PoolExhausted
701                | ErrorCode::ConnectionTimeout
702                | ErrorCode::AuthenticationFailed
703                | ErrorCode::SslError
704        )
705    }
706
707    /// Check if this error is retryable.
708    pub fn is_retryable(&self) -> bool {
709        matches!(
710            self.code,
711            ErrorCode::ConnectionTimeout
712                | ErrorCode::PoolExhausted
713                | ErrorCode::QueryTimeout
714                | ErrorCode::Deadlock
715                | ErrorCode::SerializationFailure
716        )
717    }
718
719    // ============== Display Functions ==============
720
721    /// Get the error code.
722    pub fn error_code(&self) -> &ErrorCode {
723        &self.code
724    }
725
726    /// Get the documentation URL for this error.
727    pub fn docs_url(&self) -> String {
728        self.code.docs_url()
729    }
730
731    /// Display the full error with all context and suggestions.
732    pub fn display_full(&self) -> String {
733        let mut output = String::new();
734
735        // Error header
736        output.push_str(&format!("Error [{}]: {}\n", self.code.code(), self.message));
737
738        // Context
739        if let Some(ref op) = self.context.operation {
740            output.push_str(&format!("  → While: {}\n", op));
741        }
742        if let Some(ref model) = self.context.model {
743            output.push_str(&format!("  → Model: {}\n", model));
744        }
745        if let Some(ref field) = self.context.field {
746            output.push_str(&format!("  → Field: {}\n", field));
747        }
748
749        // SQL (truncated if too long)
750        if let Some(ref sql) = self.context.sql {
751            let sql_display = if sql.len() > 200 {
752                format!("{}...", &sql[..200])
753            } else {
754                sql.clone()
755            };
756            output.push_str(&format!("  → SQL: {}\n", sql_display));
757        }
758
759        // Suggestions
760        if !self.context.suggestions.is_empty() {
761            output.push_str("\nSuggestions:\n");
762            for (i, suggestion) in self.context.suggestions.iter().enumerate() {
763                output.push_str(&format!("  {}. {}\n", i + 1, suggestion.text));
764                if let Some(ref code) = suggestion.code {
765                    output.push_str(&format!(
766                        "     ```\n     {}\n     ```\n",
767                        code.replace('\n', "\n     ")
768                    ));
769                }
770            }
771        }
772
773        // Help
774        if let Some(ref help) = self.context.help {
775            output.push_str(&format!("\nHelp: {}\n", help));
776        }
777
778        // Documentation link
779        output.push_str(&format!("\nMore info: {}\n", self.docs_url()));
780
781        output
782    }
783
784    /// Display error with ANSI colors for terminal output.
785    pub fn display_colored(&self) -> String {
786        let mut output = String::new();
787
788        // Error header (red)
789        output.push_str(&format!(
790            "\x1b[1;31mError [{}]\x1b[0m: \x1b[1m{}\x1b[0m\n",
791            self.code.code(),
792            self.message
793        ));
794
795        // Context (dim)
796        if let Some(ref op) = self.context.operation {
797            output.push_str(&format!("  \x1b[2m→ While:\x1b[0m {}\n", op));
798        }
799        if let Some(ref model) = self.context.model {
800            output.push_str(&format!("  \x1b[2m→ Model:\x1b[0m {}\n", model));
801        }
802        if let Some(ref field) = self.context.field {
803            output.push_str(&format!("  \x1b[2m→ Field:\x1b[0m {}\n", field));
804        }
805
806        // Suggestions (yellow)
807        if !self.context.suggestions.is_empty() {
808            output.push_str("\n\x1b[1;33mSuggestions:\x1b[0m\n");
809            for (i, suggestion) in self.context.suggestions.iter().enumerate() {
810                output.push_str(&format!(
811                    "  \x1b[33m{}.\x1b[0m {}\n",
812                    i + 1,
813                    suggestion.text
814                ));
815                if let Some(ref code) = suggestion.code {
816                    output.push_str(&format!(
817                        "     \x1b[2m```\x1b[0m\n     \x1b[36m{}\x1b[0m\n     \x1b[2m```\x1b[0m\n",
818                        code.replace('\n', "\n     ")
819                    ));
820                }
821            }
822        }
823
824        // Help (cyan)
825        if let Some(ref help) = self.context.help {
826            output.push_str(&format!("\n\x1b[1;36mHelp:\x1b[0m {}\n", help));
827        }
828
829        // Documentation link (blue)
830        output.push_str(&format!(
831            "\n\x1b[2mMore info:\x1b[0m \x1b[4;34m{}\x1b[0m\n",
832            self.docs_url()
833        ));
834
835        output
836    }
837}
838
839/// Extension trait for converting errors to QueryError.
840pub trait IntoQueryError {
841    /// Convert to a QueryError.
842    fn into_query_error(self) -> QueryError;
843}
844
845impl<E: std::error::Error + Send + Sync + 'static> IntoQueryError for E {
846    fn into_query_error(self) -> QueryError {
847        QueryError::internal(self.to_string()).with_source(self)
848    }
849}
850
851/// Helper for creating errors with context.
852#[macro_export]
853macro_rules! query_error {
854    ($code:expr, $msg:expr) => {
855        $crate::error::QueryError::new($code, $msg)
856    };
857    ($code:expr, $msg:expr, $($key:ident = $value:expr),+ $(,)?) => {{
858        let mut err = $crate::error::QueryError::new($code, $msg);
859        $(
860            err = err.$key($value);
861        )+
862        err
863    }};
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    #[test]
871    fn sqlstate_is_none_unless_set() {
872        assert_eq!(QueryError::database("boom").sqlstate(), None);
873        let err = QueryError::database("could not obtain lock").with_sqlstate("55P03");
874        assert_eq!(err.sqlstate(), Some("55P03"));
875        // The classification and message are untouched.
876        assert_eq!(err.code, ErrorCode::DatabaseError);
877        assert!(
878            err.to_string().ends_with("] could not obtain lock"),
879            "{err}"
880        );
881    }
882
883    #[test]
884    fn test_error_code_format() {
885        assert_eq!(ErrorCode::RecordNotFound.code(), "P1001");
886        assert_eq!(ErrorCode::UniqueConstraint.code(), "P2001");
887        assert_eq!(ErrorCode::ConnectionFailed.code(), "P3001");
888    }
889
890    #[test]
891    fn test_not_found_error() {
892        let err = QueryError::not_found("User");
893        assert!(err.is_not_found());
894        assert!(err.message.contains("User"));
895        assert!(!err.context.suggestions.is_empty());
896    }
897
898    #[test]
899    fn test_unique_violation_error() {
900        let err = QueryError::unique_violation("User", "email");
901        assert!(err.is_constraint_violation());
902        assert_eq!(err.context.model, Some("User".to_string()));
903        assert_eq!(err.context.field, Some("email".to_string()));
904    }
905
906    #[test]
907    fn test_timeout_error() {
908        let err = QueryError::timeout(5000);
909        assert!(err.is_timeout());
910        assert!(err.message.contains("5000"));
911    }
912
913    #[test]
914    fn test_error_with_context() {
915        let err = QueryError::not_found("User")
916            .with_context("Finding user by email")
917            .with_suggestion("Use a different query method");
918
919        assert_eq!(
920            err.context.operation,
921            Some("Finding user by email".to_string())
922        );
923        assert!(err.context.suggestions.len() >= 2); // Original + new one
924    }
925
926    #[test]
927    fn test_retryable_errors() {
928        assert!(QueryError::timeout(1000).is_retryable());
929        assert!(QueryError::deadlock().is_retryable());
930        assert!(QueryError::pool_exhausted(10).is_retryable());
931        assert!(!QueryError::not_found("User").is_retryable());
932    }
933
934    #[test]
935    fn test_stale_plan_is_retryable() {
936        // A stale cached-plan error (Postgres 0A000) is transient: it must be
937        // classified retryable so the retry middleware re-prepares rather than
938        // surfacing a terminal generic database error.
939        let err = QueryError::stale_plan("cached plan must not change result type");
940        assert_eq!(err.code, ErrorCode::SerializationFailure);
941        assert!(err.is_retryable());
942    }
943
944    #[test]
945    fn test_connection_errors() {
946        assert!(QueryError::connection("failed").is_connection_error());
947        assert!(QueryError::authentication_failed("bad password").is_connection_error());
948        assert!(QueryError::pool_exhausted(10).is_connection_error());
949    }
950
951    #[test]
952    fn test_display_full() {
953        let err = QueryError::unique_violation("User", "email").with_context("Creating new user");
954
955        let output = err.display_full();
956        assert!(output.contains("P2001"));
957        assert!(output.contains("User"));
958        assert!(output.contains("email"));
959        assert!(output.contains("Suggestions"));
960    }
961
962    #[test]
963    fn test_docs_url() {
964        let err = QueryError::not_found("User");
965        assert!(err.docs_url().contains("P1001"));
966    }
967
968    #[test]
969    fn test_error_macro() {
970        let err = query_error!(
971            ErrorCode::InvalidParameter,
972            "Invalid email format",
973            with_field = "email",
974            with_suggestion = "Use a valid email address"
975        );
976
977        assert_eq!(err.code, ErrorCode::InvalidParameter);
978        assert_eq!(err.context.field, Some("email".to_string()));
979    }
980
981    #[test]
982    fn test_suggestion_with_code() {
983        let err = QueryError::not_found("User")
984            .with_code_suggestion("Try this instead", "client.user().find_first()");
985
986        let suggestion = err.context.suggestions.last().unwrap();
987        assert!(suggestion.code.is_some());
988    }
989
990    #[test]
991    fn with_source_populates_std_error_source_chain() {
992        use std::error::Error;
993        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionAborted, "boom");
994        let q = QueryError::connection("could not connect").with_source(io_err);
995        let src = q
996            .source()
997            .expect("source() should return the chained error");
998        assert!(src.to_string().contains("boom"));
999    }
1000}