2026-07-11 09:15:58 +00:00
import HummingbirdFluent
import SQLKit
/// A readiness probe reporting whether the database behind a `Fluent` service is reachable.
///
2026-07-30 06:33:57 +00:00
/// Built once around the application's `Fluent` service and called as a function whenever a fresh answer is needed — typically from a readiness endpoint:
/// `let ready = await probe()`.
2026-07-11 09:15:58 +00:00
public struct Probe : Sendable {
// MARK: Properties
/// The `Fluent` service whose default database is probed.
private let fluent : Fluent
// MARK: Initializers
/// Creates a probe for the default database of the given `Fluent` service.
/// - Parameter fluent: the `Fluent` service whose default database is probed.
public init (
fluent : Fluent
) {
self . fluent = fluent
}
// MARK: Methods
/// Reports whether the database behind the `Fluent` service is reachable.
///
2026-07-30 06:33:57 +00:00
/// Runs a trivial `SELECT 1` against the default database — the cheapest statement both the MySQL/MariaDB and SQLite backends understand — so
/// a readiness check does not depend on any particular schema or model. Any failure (connection refused, authentication error, pool exhausted) is
/// reported as not reachable rather than thrown, so callers can map it straight onto a readiness response. A default database that is not an SQL
/// database is likewise reported as not reachable.
2026-07-11 09:15:58 +00:00
/// - Returns: `true` when the database answers the probe, `false` otherwise.
public func callAsFunction () async -> Bool {
guard let database = fluent . db () as ? any SQLDatabase else {
return false
}
do {
try await database . raw ( "SELECT 1" ). run ()
return true
} catch {
return false
}
}
}