athena_rs 3.6.1

Hyper performant polyglot Database driver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! SqlX error parser for converting database errors into user-friendly ProcessedError responses.
//!
//! This module handles:
//! - PostgreSQL-specific error codes
//! - Connection and pool errors
//! - Query execution errors
//! - Type conversion errors

use super::sql_sanitizer::ExtractedInfo;
use actix_web::http::StatusCode;
use serde_json::{Map, json};
use sqlx::error::DatabaseError;
use sqlx::postgres::{PgDatabaseError, PgErrorPosition};

use super::hints;
use super::sql_sanitizer::{extract_metadata, sanitize_error_message};
use super::{ErrorCategory, ProcessedError, generate_trace_id};

/// Converts a sqlx::Error into a ProcessedError with sanitized messages and metadata.
///
/// This function:
/// - Categorizes the error type
/// - Extracts safe metadata (constraint names, SQL state codes)
/// - Sanitizes error messages to remove SQL queries
/// - Generates user-friendly messages and hints
/// - Assigns appropriate HTTP status codes
pub fn process_sqlx_error(err: &sqlx::Error) -> ProcessedError {
    process_sqlx_error_with_context_and_columns(err, None, None)
}

/// Converts a sqlx::Error with additional context into a ProcessedError.
///
/// The context parameter can provide table names or other safe identifiers
/// that help make the error message more specific.
pub fn process_sqlx_error_with_context(err: &sqlx::Error, context: Option<&str>) -> ProcessedError {
    process_sqlx_error_with_context_and_columns(err, context, None)
}

/// Converts a sqlx::Error with optional context and known table columns.
pub fn process_sqlx_error_with_context_and_columns(
    err: &sqlx::Error,
    context: Option<&str>,
    available_columns: Option<&[String]>,
) -> ProcessedError {
    let trace_id: String = generate_trace_id();

    match err {
        sqlx::Error::Database(db_err) => {
            process_database_error(db_err.as_ref(), &trace_id, context, available_columns)
        }
        sqlx::Error::PoolTimedOut => create_connection_error(
            "pool_timeout",
            "Database connection pool timed out",
            hints::POOL_TIMEOUT,
            &trace_id,
        ),
        sqlx::Error::PoolClosed => create_connection_error(
            "pool_closed",
            "Database connection pool is closed",
            hints::POOL_CLOSED,
            &trace_id,
        ),
        sqlx::Error::WorkerCrashed => create_internal_error(
            "worker_crashed",
            "Database worker thread crashed",
            &trace_id,
        ),
        sqlx::Error::Io(io_err) => create_connection_error(
            "io_error",
            "Database I/O error",
            &format!("Network or I/O issue occurred: {}", io_err.kind()),
            &trace_id,
        ),
        sqlx::Error::Tls(tls_err) => create_connection_error(
            "tls_error",
            "Database TLS connection error",
            &format!(
                "Secure connection failed: {}",
                sanitize_error_message(&tls_err.to_string())
            ),
            &trace_id,
        ),
        sqlx::Error::ColumnNotFound(column) => {
            let mut error: ProcessedError = ProcessedError::new(
                ErrorCategory::QuerySyntax,
                StatusCode::INTERNAL_SERVER_ERROR,
                "column_not_found",
                format!("Column '{}' not found in query results", column),
                trace_id,
            )
            .with_hint(hints::COLUMN_NOT_FOUND)
            .with_metadata("column", json!(column));

            if let Some(ctx) = context {
                error = error.with_metadata("context", json!(ctx));
            }

            error
        }
        sqlx::Error::ColumnIndexOutOfBounds { index, len } => ProcessedError::new(
            ErrorCategory::Internal,
            StatusCode::INTERNAL_SERVER_ERROR,
            "column_index_out_of_bounds",
            format!(
                "Column index {} is out of bounds (total columns: {})",
                index, len
            ),
            trace_id,
        )
        .with_metadata("index", json!(index))
        .with_metadata("column_count", json!(len)),
        sqlx::Error::TypeNotFound { type_name } => ProcessedError::new(
            ErrorCategory::Internal,
            StatusCode::INTERNAL_SERVER_ERROR,
            "type_not_found",
            format!("Database type '{}' not recognized", type_name),
            trace_id,
        )
        .with_metadata("type_name", json!(type_name)),
        sqlx::Error::ColumnDecode { index, source } => {
            let sanitized_msg: String = sanitize_error_message(&source.to_string());
            ProcessedError::new(
                ErrorCategory::Internal,
                StatusCode::INTERNAL_SERVER_ERROR,
                "column_decode_error",
                format!(
                    "Failed to decode column at index {}: {}",
                    index, sanitized_msg
                ),
                trace_id,
            )
            .with_metadata("column_index", json!(index))
        }
        sqlx::Error::RowNotFound => ProcessedError::new(
            ErrorCategory::NotFound,
            StatusCode::NOT_FOUND,
            "row_not_found",
            "The requested record was not found",
            trace_id,
        )
        .with_hint(hints::ROW_NOT_FOUND),
        sqlx::Error::Migrate(_) => ProcessedError::new(
            ErrorCategory::Internal,
            StatusCode::INTERNAL_SERVER_ERROR,
            "migration_error",
            "Database migration error",
            trace_id,
        ),
        sqlx::Error::Configuration(config_err) => {
            let sanitized_msg = sanitize_error_message(&config_err.to_string());
            ProcessedError::new(
                ErrorCategory::Internal,
                StatusCode::INTERNAL_SERVER_ERROR,
                "configuration_error",
                format!("Database configuration error: {}", sanitized_msg),
                trace_id,
            )
        }
        _ => {
            // Fallback for any unhandled error types
            let sanitized_msg: String = sanitize_error_message(&err.to_string());
            ProcessedError::new(
                ErrorCategory::Internal,
                StatusCode::INTERNAL_SERVER_ERROR,
                "database_error",
                format!("Database operation failed: {}", sanitized_msg),
                trace_id,
            )
        }
    }
}

/// Processes database-specific errors (PostgreSQL errors with codes).
fn process_database_error(
    db_err: &dyn DatabaseError,
    trace_id: &str,
    context: Option<&str>,
    available_columns: Option<&[String]>,
) -> ProcessedError {
    let code: Option<String> = db_err.code().map(|c| c.to_string());
    let message: &str = db_err.message();
    let constraint: Option<&str> = db_err.constraint();
    let pg_err: Option<&PgDatabaseError> = db_err.try_downcast_ref::<PgDatabaseError>();

    // Extract metadata from the error message
    let extracted: ExtractedInfo = extract_metadata(message);
    let mut metadata: Map<String, serde_json::Value> = Map::new();

    if let Some(sql_code) = &code {
        metadata.insert("sql_state".to_string(), json!(sql_code));
    }

    if let Some(constraint_name) = constraint.or(extracted.constraint_name.as_deref()) {
        metadata.insert("constraint".to_string(), json!(constraint_name));
    }

    if let Some(column_name) = pg_err
        .and_then(PgDatabaseError::column)
        .or(extracted.column_name.as_deref())
    {
        metadata.insert("column".to_string(), json!(column_name));
    }

    if let Some(table_name) = pg_err
        .and_then(PgDatabaseError::table)
        .or(db_err.table())
        .or(extracted.table_name.as_deref())
    {
        metadata.insert("table".to_string(), json!(table_name));
    }

    if let Some(schema_name) = pg_err.and_then(PgDatabaseError::schema) {
        metadata.insert("schema".to_string(), json!(schema_name));
    }

    if let Some(detail) = pg_err
        .and_then(PgDatabaseError::detail)
        .map(sanitize_error_message)
    {
        metadata.insert("detail".to_string(), json!(detail));
    }

    if let Some(position) = pg_err.and_then(PgDatabaseError::position) {
        match position {
            PgErrorPosition::Original(position) => {
                metadata.insert("position".to_string(), json!(position));
            }
            PgErrorPosition::Internal { position, .. } => {
                metadata.insert("position".to_string(), json!(position));
            }
        }
    }

    if let Some(ctx) = context {
        metadata.insert("context".to_string(), json!(ctx));
    }

    if let Some(columns) = available_columns {
        metadata.insert("available_columns".to_string(), json!(columns));
    }

    // Map SQL state codes to user-friendly errors
    match code.as_deref() {
        // Unique violation
        Some("23505") => ProcessedError::new(
            ErrorCategory::DatabaseConstraint,
            StatusCode::CONFLICT,
            "unique_violation",
            "A record with this value already exists",
            trace_id,
        )
        .with_hint(hints::UNIQUE_VIOLATION)
        .with_metadata_map(metadata),

        // Foreign key violation
        Some("23503") => ProcessedError::new(
            ErrorCategory::DatabaseConstraint,
            StatusCode::UNPROCESSABLE_ENTITY,
            "foreign_key_violation",
            "The operation references a non-existent or inaccessible resource",
            trace_id,
        )
        .with_hint(hints::FOREIGN_KEY_VIOLATION)
        .with_metadata_map(metadata),

        // Not null violation
        Some("23502") => ProcessedError::new(
            ErrorCategory::Validation,
            StatusCode::BAD_REQUEST,
            "not_null_violation",
            "A required field is missing",
            trace_id,
        )
        .with_hint(hints::NOT_NULL_VIOLATION)
        .with_metadata_map(metadata),

        // Check constraint violation
        Some("23514") => ProcessedError::new(
            ErrorCategory::DatabaseConstraint,
            StatusCode::BAD_REQUEST,
            "check_constraint_violation",
            "The provided value does not meet the required constraints",
            trace_id,
        )
        .with_hint(hints::CHECK_CONSTRAINT_VIOLATION)
        .with_metadata_map(metadata),

        // Invalid text encoding (for example, non-UTF-8 payload bytes)
        Some("22021") => ProcessedError::new(
            ErrorCategory::Validation,
            StatusCode::BAD_REQUEST,
            "invalid_text_encoding",
            "The request contains text that is not valid UTF-8.",
            trace_id,
        )
        .with_hint(hints::INVALID_TEXT_ENCODING)
        .with_metadata_map(metadata),

        // Undefined column
        Some("42703") => ProcessedError::new(
            ErrorCategory::QuerySyntax,
            StatusCode::BAD_REQUEST,
            "undefined_column",
            undefined_column_message(
                metadata.get("column").and_then(|v| v.as_str()),
                available_columns,
            ),
            trace_id,
        )
        .with_hint(hints::UNDEFINED_COLUMN)
        .with_metadata_map(metadata),

        // Undefined table
        Some("42P01") => {
            let (message, hint) = hints::undefined_table(extracted.table_name.as_deref());
            ProcessedError::new(
                ErrorCategory::QuerySyntax,
                StatusCode::BAD_REQUEST,
                "undefined_table",
                message,
                trace_id,
            )
            .with_hint(hint)
            .with_metadata_map(metadata)
        }

        // Syntax error
        Some("42601") => ProcessedError::new(
            ErrorCategory::QuerySyntax,
            StatusCode::BAD_REQUEST,
            "syntax_error",
            syntax_error_message(message),
            trace_id,
        )
        .with_hint(
            pg_err
                .and_then(PgDatabaseError::hint)
                .map(sanitize_error_message)
                .unwrap_or_else(|| hints::SYNTAX_ERROR.to_string()),
        )
        .with_metadata_map(metadata),

        // Insufficient privilege
        Some("42501") => ProcessedError::new(
            ErrorCategory::Authorization,
            StatusCode::FORBIDDEN,
            "insufficient_privilege",
            "You do not have permission to perform this operation",
            trace_id,
        )
        .with_hint(hints::INSUFFICIENT_PRIVILEGE)
        .with_metadata_map(metadata),

        // Connection exceptions (08xxx)
        Some(code) if code.starts_with("08") => ProcessedError::new(
            ErrorCategory::DatabaseConnection,
            StatusCode::SERVICE_UNAVAILABLE,
            "connection_error",
            "Database connection issue",
            trace_id,
        )
        .with_hint(hints::CONNECTION_ERROR)
        .with_metadata_map(metadata),

        // Undefined function / operator mismatch
        Some("42883") => {
            if let Some(parts) = parse_operator_mismatch(message) {
                let (lhs_type, operator, rhs_type) = parts;
                metadata.insert("lhs_type".to_string(), json!(lhs_type));
                metadata.insert("rhs_type".to_string(), json!(rhs_type));
                metadata.insert("operator".to_string(), json!(operator));

                // Preserve the historical UUID-specific code so existing
                // clients / dashboards keep working, while still reporting
                // structured lhs/rhs/operator metadata.
                let is_text_uuid: bool = (lhs_type == "text" && rhs_type == "uuid")
                    || (lhs_type == "uuid" && rhs_type == "text");
                let (code, user_message, hint): (&str, String, &str) = if is_text_uuid {
                    (
                        "text_uuid_operator_mismatch",
                        "A text value was compared to a UUID value without a compatible cast."
                            .to_string(),
                        hints::TEXT_UUID_OPERATOR_MISMATCH,
                    )
                } else {
                    (
                        "type_operator_mismatch",
                        format!(
                            "Cannot compare a column of type `{lhs}` to a value of type `{rhs}` using `{op}`. The value could not be coerced to the column's type.",
                            lhs = lhs_type,
                            rhs = rhs_type,
                            op = operator,
                        ),
                        hints::TYPE_OPERATOR_MISMATCH,
                    )
                };

                return ProcessedError::new(
                    ErrorCategory::Validation,
                    StatusCode::BAD_REQUEST,
                    code,
                    user_message,
                    trace_id,
                )
                .with_hint(hint)
                .with_metadata_map(metadata);
            }

            let sanitized_msg: String = sanitize_error_message(message);
            ProcessedError::new(
                ErrorCategory::Validation,
                StatusCode::BAD_REQUEST,
                "undefined_function",
                format!("Database operation failed: {}", sanitized_msg),
                trace_id,
            )
            .with_hint(hints::TYPE_OPERATOR_MISMATCH)
            .with_metadata_map(metadata)
        }

        // Fallback for other database errors
        _ => {
            if message.contains("invalid byte sequence for encoding \"UTF8\"") {
                return ProcessedError::new(
                    ErrorCategory::Validation,
                    StatusCode::BAD_REQUEST,
                    "invalid_text_encoding",
                    "The request contains text that is not valid UTF-8.",
                    trace_id,
                )
                .with_hint(hints::INVALID_TEXT_ENCODING)
                .with_metadata_map(metadata);
            }

            let sanitized_msg: String = sanitize_error_message(message);
            ProcessedError::new(
                ErrorCategory::Internal,
                StatusCode::INTERNAL_SERVER_ERROR,
                "database_error",
                format!("Database operation failed: {}", sanitized_msg),
                trace_id,
            )
            .with_metadata_map(metadata)
        }
    }
}

/// Parses `operator does not exist: <LHS_TYPE> <OP> <RHS_TYPE>` messages emitted
/// by PostgreSQL SQLSTATE `42883`. Returns `(lhs_type, operator, rhs_type)`
/// when the message matches, or `None` for the non-operator variants of
/// `42883` (undefined function call).
///
/// Handles multi-word type names (`double precision`, `timestamp with time zone`,
/// `character varying`) by treating the operator token as any run of
/// non-alphanumeric/non-whitespace characters (e.g. `=`, `<=`, `<>`, `@>`).
fn parse_operator_mismatch(message: &str) -> Option<(String, String, String)> {
    const PREFIX: &str = "operator does not exist: ";
    let start: usize = message.find(PREFIX)?;
    let remainder: &str = &message[start + PREFIX.len()..];
    let end: usize = remainder
        .find('\n')
        .unwrap_or_else(|| remainder.find('.').unwrap_or(remainder.len()));
    let body: &str = remainder[..end].trim();

    let op_start: usize = body
        .char_indices()
        .find(|(_, c)| !c.is_ascii_alphanumeric() && !c.is_whitespace() && *c != '_')?
        .0;
    let op_end_rel: usize = body[op_start..]
        .char_indices()
        .find(|(_, c)| c.is_ascii_alphanumeric() || c.is_whitespace() || *c == '_')
        .map(|(i, _)| i)
        .unwrap_or(body.len() - op_start);
    let op_end: usize = op_start + op_end_rel;

    let lhs: &str = body[..op_start].trim();
    let operator: &str = body[op_start..op_end].trim();
    let rhs: &str = body[op_end..].trim();

    if lhs.is_empty() || operator.is_empty() || rhs.is_empty() {
        return None;
    }

    Some((lhs.to_string(), operator.to_string(), rhs.to_string()))
}

fn syntax_error_message(message: &str) -> String {
    let sanitized: String = sanitize_error_message(message).trim().to_string();
    if sanitized.is_empty() || sanitized.eq_ignore_ascii_case("syntax error") {
        "The query contains a syntax error".to_string()
    } else {
        sanitized
    }
}

fn undefined_column_message(
    tried_column: Option<&str>,
    available_columns: Option<&[String]>,
) -> String {
    let prefix = match tried_column {
        Some(column) => format!("The specified column '{}' does not exist", column),
        None => "The specified column does not exist".to_string(),
    };

    match available_columns {
        Some(columns) if !columns.is_empty() => {
            format!("{}. Available columns: {}", prefix, columns.join(", "))
        }
        _ => prefix,
    }
}

/// Creates a connection error ProcessedError.
fn create_connection_error(
    code: &'static str,
    message: &str,
    hint: &str,
    trace_id: &str,
) -> ProcessedError {
    ProcessedError::new(
        ErrorCategory::DatabaseConnection,
        StatusCode::SERVICE_UNAVAILABLE,
        code,
        message,
        trace_id,
    )
    .with_hint(hint)
}

/// Creates an internal error ProcessedError.
fn create_internal_error(code: &'static str, message: &str, trace_id: &str) -> ProcessedError {
    ProcessedError::new(
        ErrorCategory::Internal,
        StatusCode::INTERNAL_SERVER_ERROR,
        code,
        message,
        trace_id,
    )
    .with_hint(hints::INTERNAL_ERROR)
}

#[cfg(test)]
mod tests {
    use super::{parse_operator_mismatch, syntax_error_message, undefined_column_message};
    use crate::error::sql_sanitizer::extract_metadata;

    #[test]
    fn syntax_error_message_preserves_useful_postgres_text() {
        assert_eq!(
            syntax_error_message("syntax error at or near \";\""),
            "syntax error at or near \";\""
        );
    }

    #[test]
    fn syntax_error_message_falls_back_for_generic_messages() {
        assert_eq!(
            syntax_error_message("syntax error"),
            "The query contains a syntax error"
        );
    }

    #[test]
    fn undefined_column_message_includes_column_and_available_columns() {
        let available = vec![
            "id".to_string(),
            "email".to_string(),
            "created_at".to_string(),
        ];
        assert_eq!(
            undefined_column_message(Some("emali"), Some(&available)),
            "The specified column 'emali' does not exist. Available columns: id, email, created_at"
        );
    }

    #[test]
    fn undefined_column_message_without_known_columns_uses_fallback() {
        assert_eq!(
            undefined_column_message(Some("emali"), None),
            "The specified column 'emali' does not exist"
        );
    }

    #[test]
    fn parse_operator_mismatch_extracts_lhs_rhs_and_operator() {
        let (lhs, op, rhs) =
            parse_operator_mismatch("operator does not exist: double precision = text")
                .expect("should parse");
        assert_eq!(lhs, "double precision");
        assert_eq!(op, "=");
        assert_eq!(rhs, "text");
    }

    #[test]
    fn parse_operator_mismatch_handles_bigint_and_boolean_and_multiword_types() {
        let (lhs, op, rhs) = parse_operator_mismatch("operator does not exist: bigint = text")
            .expect("should parse");
        assert_eq!(lhs, "bigint");
        assert_eq!(op, "=");
        assert_eq!(rhs, "text");

        let (lhs, op, rhs) = parse_operator_mismatch("operator does not exist: boolean = text")
            .expect("should parse");
        assert_eq!(lhs, "boolean");
        assert_eq!(op, "=");
        assert_eq!(rhs, "text");

        let (lhs, op, rhs) = parse_operator_mismatch(
            "operator does not exist: timestamp with time zone = text",
        )
        .expect("should parse");
        assert_eq!(lhs, "timestamp with time zone");
        assert_eq!(op, "=");
        assert_eq!(rhs, "text");
    }

    #[test]
    fn parse_operator_mismatch_handles_non_eq_operators() {
        let (lhs, op, rhs) = parse_operator_mismatch("operator does not exist: jsonb @> text")
            .expect("should parse");
        assert_eq!(lhs, "jsonb");
        assert_eq!(op, "@>");
        assert_eq!(rhs, "text");
    }

    #[test]
    fn parse_operator_mismatch_returns_none_for_non_operator_42883_messages() {
        assert!(parse_operator_mismatch("function foo(text) does not exist").is_none());
    }

    /// Regression: the metadata extractor used to capture `t` as the column
    /// name from messages like `column "t"."cache_hit_ratio"`, leaking the
    /// internal table alias. The tightened regex skips alias captures.
    #[test]
    fn sanitizer_does_not_report_single_letter_alias_as_column() {
        let info = extract_metadata(
            "column \"t\".\"cache_hit_ratio\" does not exist (this is the real message)",
        );
        assert_ne!(info.column_name.as_deref(), Some("t"));
    }

    #[test]
    fn sanitizer_still_reports_real_column_names() {
        let info = extract_metadata("column \"cache_hit_ratio\" does not exist");
        assert_eq!(info.column_name.as_deref(), Some("cache_hit_ratio"));
    }
}