footing 0.1.21

Feature-gated foundations for Rust backend services
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Redacted PostgreSQL errors and operational diagnostics.

use std::{fmt, time::Duration};

use sqlx::migrate::MigrateError;
use thiserror::Error;

use crate::{
    db::MigrationFailureKind,
    result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};

use super::identity::database_name;

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling PostgreSQL pool.
pub enum PostgresPoolError {
    #[error("PostgreSQL operation failed")]
    /// Indicates SQLx.
    Sqlx(#[from] sqlx::Error),
}

impl fmt::Debug for PostgresPoolError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresPoolError")
            .field("error_code", &self.error_code())
            .field("source", &"[REDACTED]")
            .finish()
    }
}

impl ClassifyError for PostgresPoolError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Dependency
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("postgres_unavailable")
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling PostgreSQL bootstrap.
pub enum PostgresBootstrapError {
    #[error("migrate_on_startup requires a SQLx migrator")]
    /// The required migrator is missing.
    MissingMigrator,
    #[error("failed to ensure PostgreSQL database exists: {diagnosis}")]
    /// Indicates ensure database.
    EnsureDatabase {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<sqlx::Error>,
    },
    #[error("failed to connect to PostgreSQL: {diagnosis}")]
    /// Indicates connect.
    Connect {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<PostgresPoolError>,
    },
    #[error("failed to run PostgreSQL migrations: {diagnosis}")]
    /// Indicates migration.
    Migration {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        /// The kind value.
        kind: MigrationFailureKind,
        #[source]
        /// The source value.
        source: Box<MigrateError>,
    },
    #[error("failed to acquire PostgreSQL schema-maintenance lock for migrations: {diagnosis}")]
    /// Indicates migration lock.
    MigrationLock {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<sqlx::Error>,
    },
    #[error("timed out waiting for the PostgreSQL schema-maintenance lock: {diagnosis}")]
    /// The migration lock remained busy beyond the configured deadline.
    MigrationLockTimeout {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        /// Configured lock wait deadline.
        timeout: Duration,
    },
    #[error("timed out while running PostgreSQL migrations: {diagnosis}")]
    /// Migration execution exceeded the configured deadline.
    MigrationTimeout {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        /// Configured migration execution deadline.
        timeout: Duration,
    },
}

impl fmt::Debug for PostgresBootstrapError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresBootstrapError")
            .field("error_code", &self.error_code())
            .field("diagnosis", &self.diagnosis())
            .field("source", &"[REDACTED]")
            .finish()
    }
}

impl ClassifyError for PostgresBootstrapError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingMigrator => ErrorKind::Validation,
            Self::MigrationLockTimeout { .. } | Self::MigrationTimeout { .. } => ErrorKind::Timeout,
            Self::EnsureDatabase { .. }
            | Self::Connect { .. }
            | Self::Migration { .. }
            | Self::MigrationLock { .. } => ErrorKind::Dependency,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::MissingMigrator => "postgres_migrator_required",
            Self::EnsureDatabase { .. } => "postgres_ensure_database_failed",
            Self::Connect { .. } => "postgres_connect_failed",
            Self::Migration { .. } => "postgres_migration_failed",
            Self::MigrationLock { .. } => "postgres_migration_lock_failed",
            Self::MigrationLockTimeout { .. } => "postgres_migration_lock_timeout",
            Self::MigrationTimeout { .. } => "postgres_migration_timeout",
        })
    }

    fn error_descriptor(&self) -> ErrorDescriptor {
        ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
            .with_retryable(self.diagnosis().is_some_and(PostgresDiagnostic::retryable))
    }
}

impl PostgresBootstrapError {
    #[must_use]
    /// Returns the diagnosis.
    pub const fn diagnosis(&self) -> Option<&PostgresDiagnostic> {
        match self {
            Self::EnsureDatabase { diagnosis, .. }
            | Self::Connect { diagnosis, .. }
            | Self::Migration { diagnosis, .. }
            | Self::MigrationLock { diagnosis, .. }
            | Self::MigrationLockTimeout { diagnosis, .. }
            | Self::MigrationTimeout { diagnosis, .. } => Some(diagnosis),
            Self::MissingMigrator => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported PostgreSQL operation values.
pub enum PostgresOperation {
    /// Indicates ensure database.
    EnsureDatabase,
    /// Indicates connect.
    Connect,
    /// Indicates migrate.
    Migrate,
    /// Indicates migration lock.
    MigrationLock,
    /// Indicates reset schema.
    ResetSchema,
}

impl PostgresOperation {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::EnsureDatabase => "ensure_database",
            Self::Connect => "connect",
            Self::Migrate => "migrate",
            Self::MigrationLock => "migration_lock",
            Self::ResetSchema => "reset_schema",
        }
    }
}

impl std::fmt::Display for PostgresOperation {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Classification of PostgreSQL diagnostic.
pub enum PostgresDiagnosticKind {
    /// The configuration is invalid.
    InvalidConfiguration,
    /// Indicates database missing.
    DatabaseMissing,
    /// Indicates authentication failed.
    AuthenticationFailed,
    /// Indicates permission denied.
    PermissionDenied,
    /// Indicates connection unavailable.
    ConnectionUnavailable,
    /// Indicates too many connections.
    TooManyConnections,
    /// Indicates migration source invalid.
    MigrationSourceInvalid,
    /// Indicates migration missing.
    MigrationMissing,
    /// Indicates migration checksum mismatch.
    MigrationChecksumMismatch,
    /// Indicates migration dirty.
    MigrationDirty,
    /// Indicates migration version conflict.
    MigrationVersionConflict,
    /// Indicates migration execution failed.
    MigrationExecutionFailed,
    /// Indicates migration lock unavailable.
    MigrationLockUnavailable,
    /// Indicates an operation exceeded its configured deadline.
    OperationTimeout,
    /// The value is unknown.
    Unknown,
}

impl PostgresDiagnosticKind {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidConfiguration => "invalid_configuration",
            Self::DatabaseMissing => "database_missing",
            Self::AuthenticationFailed => "authentication_failed",
            Self::PermissionDenied => "permission_denied",
            Self::ConnectionUnavailable => "connection_unavailable",
            Self::TooManyConnections => "too_many_connections",
            Self::MigrationSourceInvalid => "migration_source_invalid",
            Self::MigrationMissing => "migration_missing",
            Self::MigrationChecksumMismatch => "migration_checksum_mismatch",
            Self::MigrationDirty => "migration_dirty",
            Self::MigrationVersionConflict => "migration_version_conflict",
            Self::MigrationExecutionFailed => "migration_execution_failed",
            Self::MigrationLockUnavailable => "migration_lock_unavailable",
            Self::OperationTimeout => "operation_timeout",
            Self::Unknown => "unknown",
        }
    }
}

impl From<PostgresDiagnosticKind> for DiagnosticKind {
    fn from(value: PostgresDiagnosticKind) -> Self {
        match value {
            PostgresDiagnosticKind::InvalidConfiguration => Self::InvalidConfiguration,
            PostgresDiagnosticKind::DatabaseMissing | PostgresDiagnosticKind::MigrationMissing => {
                Self::ResourceMissing
            }
            PostgresDiagnosticKind::AuthenticationFailed => Self::AuthenticationFailed,
            PostgresDiagnosticKind::PermissionDenied => Self::PermissionDenied,
            PostgresDiagnosticKind::ConnectionUnavailable
            | PostgresDiagnosticKind::MigrationLockUnavailable
            | PostgresDiagnosticKind::OperationTimeout => Self::Unavailable,
            PostgresDiagnosticKind::TooManyConnections => Self::CapacityExhausted,
            PostgresDiagnosticKind::MigrationChecksumMismatch
            | PostgresDiagnosticKind::MigrationDirty
            | PostgresDiagnosticKind::MigrationVersionConflict => Self::StateMismatch,
            PostgresDiagnosticKind::MigrationSourceInvalid
            | PostgresDiagnosticKind::MigrationExecutionFailed => Self::ExecutionFailed,
            PostgresDiagnosticKind::Unknown => Self::Unknown,
        }
    }
}

impl std::fmt::Display for PostgresDiagnosticKind {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents PostgreSQL diagnostic.
pub struct PostgresDiagnostic {
    operation: PostgresOperation,
    database: Option<String>,
    kind: PostgresDiagnosticKind,
    message: String,
    hint: String,
    retryable: bool,
}

impl fmt::Debug for PostgresDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresDiagnostic")
            .field("operation", &self.operation)
            .field("database", &self.database)
            .field("kind", &self.kind)
            .field("message", &"[REDACTED]")
            .field("hint", &"[REDACTED]")
            .field("retryable", &self.retryable)
            .finish()
    }
}

impl PostgresDiagnostic {
    #[must_use]
    /// Creates a new instance.
    pub fn new(
        operation: PostgresOperation,
        database: Option<String>,
        kind: PostgresDiagnosticKind,
        message: impl Into<String>,
        hint: impl Into<String>,
        retryable: bool,
    ) -> Self {
        Self {
            operation,
            database,
            kind,
            message: message.into(),
            hint: hint.into(),
            retryable,
        }
    }

    #[must_use]
    /// Returns the operation.
    pub const fn operation(&self) -> PostgresOperation {
        self.operation
    }

    #[must_use]
    /// Returns the database.
    pub fn database(&self) -> Option<&str> {
        self.database.as_deref()
    }

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> PostgresDiagnosticKind {
        self.kind
    }

    #[must_use]
    /// Returns the message.
    pub fn message(&self) -> &str {
        &self.message
    }

    #[must_use]
    /// Returns the hint.
    pub fn hint(&self) -> &str {
        &self.hint
    }

    #[must_use]
    /// Returns the retryable.
    pub const fn retryable(&self) -> bool {
        self.retryable
    }

    #[must_use]
    /// Converts this value to diagnostic.
    pub fn to_diagnostic(&self) -> Diagnostic {
        self.clone().into()
    }
}

impl std::fmt::Display for PostgresDiagnostic {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{} during {}", self.kind, self.operation)?;
        if let Some(database) = &self.database {
            write!(formatter, " for database '{database}'")?;
        }
        write!(formatter, ": {}", self.message)?;
        if !self.hint.is_empty() {
            write!(formatter, "; hint: {}", self.hint)?;
        }
        Ok(())
    }
}

impl From<PostgresDiagnostic> for Diagnostic {
    fn from(value: PostgresDiagnostic) -> Self {
        let mut diagnostic = Self::new(
            "postgres",
            value.operation.as_str(),
            DiagnosticKind::from(value.kind),
            value.message,
        )
        .with_retryable(value.retryable);
        if let Some(database) = value.database {
            diagnostic = diagnostic.with_resource(database);
        }
        if !value.hint.is_empty() {
            diagnostic = diagnostic.with_remediation(value.hint);
        }
        diagnostic
    }
}

impl From<&PostgresDiagnostic> for Diagnostic {
    fn from(value: &PostgresDiagnostic) -> Self {
        value.to_diagnostic()
    }
}

#[must_use]
/// Converts an SQLx error into a redacted operational diagnosis.
pub fn diagnose_sqlx_error(
    operation: PostgresOperation,
    database_url: &str,
    error: &sqlx::Error,
) -> PostgresDiagnostic {
    let database = database_name(database_url);
    let (kind, message, hint, retryable) = match error {
        sqlx::Error::Database(error) => classify_database_error(error.as_ref()),
        sqlx::Error::Configuration(_) => (
            PostgresDiagnosticKind::InvalidConfiguration,
            "PostgreSQL connection configuration is invalid",
            "verify database_url syntax and SQLx PostgreSQL connection options",
            false,
        ),
        sqlx::Error::Io(error) => {
            let (kind, hint, retryable) = classify_io_error(error.kind());
            (
                kind,
                "PostgreSQL network connection failed",
                hint,
                retryable,
            )
        }
        sqlx::Error::PoolTimedOut => (
            PostgresDiagnosticKind::TooManyConnections,
            "timed out while acquiring a PostgreSQL connection",
            "increase acquire_timeout, reduce load or increase PostgreSQL/pool capacity",
            true,
        ),
        sqlx::Error::PoolClosed => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "PostgreSQL pool is closed",
            "check application shutdown and pool ownership",
            false,
        ),
        sqlx::Error::Tls(_) => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "PostgreSQL TLS negotiation failed",
            "check PostgreSQL TLS mode, server certificate and trusted CA configuration",
            false,
        ),
        _ => (
            PostgresDiagnosticKind::Unknown,
            "PostgreSQL operation failed with an unclassified error",
            "inspect PostgreSQL and application logs for the underlying SQLx error",
            false,
        ),
    };

    PostgresDiagnostic::new(operation, database, kind, message, hint, retryable)
}

fn classify_database_error(
    error: &dyn sqlx::error::DatabaseError,
) -> (PostgresDiagnosticKind, &'static str, &'static str, bool) {
    let code = error.code();
    match code.as_deref() {
        Some("3D000") => (
            PostgresDiagnosticKind::DatabaseMissing,
            "PostgreSQL database does not exist",
            "create the database first or enable create_on_startup",
            false,
        ),
        Some("28P01" | "28000") => (
            PostgresDiagnosticKind::AuthenticationFailed,
            "PostgreSQL authentication failed",
            "check the PostgreSQL username, password and pg_hba.conf authentication rules",
            false,
        ),
        Some("42501") => (
            PostgresDiagnosticKind::PermissionDenied,
            "PostgreSQL operation was denied",
            "grant the configured PostgreSQL role permission for this operation",
            false,
        ),
        Some("53300" | "53400") => (
            PostgresDiagnosticKind::TooManyConnections,
            "PostgreSQL connection capacity is exhausted",
            "reduce pool size or increase PostgreSQL connection limits",
            true,
        ),
        Some("57P01" | "57P02" | "57P03") => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "PostgreSQL is shutting down, recovering or not ready for connections",
            "wait for PostgreSQL to become ready and retry the operation",
            true,
        ),
        Some(code) if code.starts_with("08") => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "PostgreSQL connection was interrupted",
            "check PostgreSQL availability, host, port and network policy",
            true,
        ),
        _ => (
            PostgresDiagnosticKind::Unknown,
            "PostgreSQL returned an unclassified database error",
            "inspect the PostgreSQL SQLSTATE and server logs",
            false,
        ),
    }
}

fn classify_io_error(kind: std::io::ErrorKind) -> (PostgresDiagnosticKind, &'static str, bool) {
    match kind {
        std::io::ErrorKind::ConnectionRefused => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "start PostgreSQL or check the configured host and port",
            true,
        ),
        std::io::ErrorKind::TimedOut => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "check network latency, firewall rules and PostgreSQL readiness",
            true,
        ),
        std::io::ErrorKind::PermissionDenied => (
            PostgresDiagnosticKind::PermissionDenied,
            "check local socket permissions or network policy",
            false,
        ),
        _ => (
            PostgresDiagnosticKind::ConnectionUnavailable,
            "check PostgreSQL availability and network connectivity",
            true,
        ),
    }
}

#[must_use]
/// Converts a pool error into a redacted operational diagnosis.
pub fn diagnose_pool_error(
    operation: PostgresOperation,
    database_url: &str,
    error: &PostgresPoolError,
) -> PostgresDiagnostic {
    match error {
        PostgresPoolError::Sqlx(source) => diagnose_sqlx_error(operation, database_url, source),
    }
}

#[must_use]
/// Builds a redacted diagnosis for an advisory-lock wait deadline.
pub fn diagnose_migration_lock_timeout(
    database_url: &str,
    timeout: Duration,
) -> PostgresDiagnostic {
    PostgresDiagnostic::new(
        PostgresOperation::MigrationLock,
        database_name(database_url),
        PostgresDiagnosticKind::MigrationLockUnavailable,
        format!(
            "PostgreSQL schema-maintenance lock was unavailable for {} ms",
            timeout.as_millis()
        ),
        "wait for active schema maintenance to finish or choose a longer migration_lock_timeout",
        true,
    )
}

#[must_use]
/// Builds a redacted diagnosis for an operation execution deadline.
pub fn diagnose_operation_timeout(
    operation: PostgresOperation,
    database_url: &str,
    timeout: Duration,
) -> PostgresDiagnostic {
    PostgresDiagnostic::new(
        operation,
        database_name(database_url),
        PostgresDiagnosticKind::OperationTimeout,
        format!(
            "PostgreSQL {operation} operation exceeded its {} ms deadline",
            timeout.as_millis()
        ),
        "inspect database load and the operation before increasing its configured timeout",
        true,
    )
}

#[must_use]
/// Converts a migration error into a redacted operational diagnosis.
pub fn diagnose_migration_error(database_url: &str, error: &MigrateError) -> PostgresDiagnostic {
    let database = database_name(database_url);
    match error {
        MigrateError::Execute(source) => {
            let diagnosis = diagnose_sqlx_error(PostgresOperation::Migrate, database_url, source);
            if !matches!(diagnosis.kind(), PostgresDiagnosticKind::Unknown) {
                return diagnosis;
            }
        }
        MigrateError::ExecuteMigration(source, version) => {
            let diagnosis = diagnose_sqlx_error(PostgresOperation::Migrate, database_url, source);
            if !matches!(diagnosis.kind(), PostgresDiagnosticKind::Unknown) {
                return migration_execution_diagnosis_with_version(diagnosis, *version);
            }
        }
        _ => {}
    }

    match MigrationFailureKind::from_error(error) {
        MigrationFailureKind::Source => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationSourceInvalid,
            "failed to load PostgreSQL migration sources",
            "verify that migration files are packaged and readable",
            false,
        ),
        MigrationFailureKind::VersionMissing { version }
        | MigrationFailureKind::VersionNotPresent { version } => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationMissing,
            format!("migration version {version} is missing from resolved migrations"),
            "restore the migration file or reset the database after confirming the target",
            false,
        ),
        MigrationFailureKind::VersionMismatch { version } => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationChecksumMismatch,
            format!("migration version {version} checksum differs from the applied migration"),
            "do not edit applied migrations; create a follow-up migration or reset only in development",
            false,
        ),
        MigrationFailureKind::Dirty { version } => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationDirty,
            format!("migration version {version} is marked dirty"),
            "inspect the failed migration, repair database state, then clear the dirty marker deliberately",
            false,
        ),
        MigrationFailureKind::VersionTooOld { version, latest } => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationVersionConflict,
            format!("migration version {version} is older than latest applied version {latest}"),
            "ensure migration files are ordered and the deployed binary matches the database state",
            false,
        ),
        MigrationFailureKind::VersionTooNew { version, latest } => PostgresDiagnostic::new(
            PostgresOperation::Migrate,
            database,
            PostgresDiagnosticKind::MigrationVersionConflict,
            format!("migration version {version} is newer than latest resolved version {latest}"),
            "deploy a binary that contains all applied migrations or restore the missing migrations",
            false,
        ),
        MigrationFailureKind::Execute | MigrationFailureKind::ExecuteMigration { .. } => {
            PostgresDiagnostic::new(
                PostgresOperation::Migrate,
                database,
                PostgresDiagnosticKind::MigrationExecutionFailed,
                "PostgreSQL migration execution failed",
                "inspect the failing SQL statement and PostgreSQL server logs",
                false,
            )
        }
        MigrationFailureKind::Unsupported | MigrationFailureKind::Unknown => {
            PostgresDiagnostic::new(
                PostgresOperation::Migrate,
                database,
                PostgresDiagnosticKind::Unknown,
                "PostgreSQL migration failed with an unclassified error",
                "inspect SQLx migration state and PostgreSQL logs",
                false,
            )
        }
    }
}

fn migration_execution_diagnosis_with_version(
    diagnosis: PostgresDiagnostic,
    version: i64,
) -> PostgresDiagnostic {
    PostgresDiagnostic::new(
        PostgresOperation::Migrate,
        diagnosis.database,
        diagnosis.kind,
        format!("migration version {version} failed: {}", diagnosis.message),
        diagnosis.hint,
        diagnosis.retryable,
    )
}