import Foundation import Logging import PostgresNIO /// The one door to Postgres. Wraps `PostgresClient` so handlers read rows by /// column name and can build queries with optional filters. struct Database: Sendable { let client: PostgresClient let logger: Logger init(client: PostgresClient, logger: Logger) { self.client = client self.logger = logger } /// Runs a query and collects every row. func rows(_ query: PostgresQuery) async throws -> [DBRow] { var result: [DBRow] = [] let sequence = try await client.query(query, logger: logger) for try await row in sequence { result.append(DBRow(row.makeRandomAccess())) } return result } /// Runs a query that returns at most one row. func first(_ query: PostgresQuery) async throws -> DBRow? { try await rows(query).first } /// Runs a statement and discards any rows. func execute(_ query: PostgresQuery) async throws { let sequence = try await client.query(query, logger: logger) for try await _ in sequence {} } /// Runs a statement and returns the first column of the first row as an /// integer, which is how counts and `RETURNING id` are read. func scalar(_ query: PostgresQuery) async throws -> Int { guard let row = try await first(query) else { return 0 } return try row.int(at: 0) } func withTransaction(_ body: @Sendable (PostgresConnection) async throws -> T) async throws -> T { try await client.withTransaction(logger: logger) { connection in try await body(connection) } } /// Whether the database answers within `timeout`. The health routes call /// this, and a health check that waits a minute for a database that has /// stopped answering is worse than one that says so. func ping(timeout: Duration = .seconds(3)) async -> Bool { do { let answered = try await withDeadline(timeout) { _ = try await self.rows("SELECT 1") return true } if answered == nil { logger.warning("database ping timed out", metadata: ["after": "\(timeout)"]) } return answered ?? false } catch { logger.warning("database ping failed", metadata: ["error": "\(ErrorSummary.describe(error))"]) return false } } } /// A row with typed, by-name column access. Decoding errors say which column /// failed instead of crashing. struct DBRow: Sendable { private let row: PostgresRandomAccessRow init(_ row: PostgresRandomAccessRow) { self.row = row } func string(_ column: String) throws -> String { try cell(column).decode(String.self) } func optionalString(_ column: String) throws -> String? { try cell(column).decode(String?.self) } /// Reads a text column, treating NULL and empty strings as nil. func nonEmptyString(_ column: String) throws -> String? { let value = try optionalString(column) return value.flatMap { $0.isEmpty ? nil : $0 } } func int(_ column: String) throws -> Int { try cell(column).decode(Int.self) } func int(at index: Int) throws -> Int { guard index >= row.startIndex, index < row.endIndex else { throw DBRowError.missingColumn("#\(index)") } return try row[index].decode(Int.self) } func optionalInt(_ column: String) throws -> Int? { try cell(column).decode(Int?.self) } func int64(_ column: String) throws -> Int64 { try cell(column).decode(Int64.self) } func optionalInt64(_ column: String) throws -> Int64? { try cell(column).decode(Int64?.self) } func bool(_ column: String) throws -> Bool { try cell(column).decode(Bool.self) } func date(_ column: String) throws -> Date { try cell(column).decode(Date.self) } func optionalDate(_ column: String) throws -> Date? { try cell(column).decode(Date?.self) } private func cell(_ column: String) throws -> PostgresCell { guard row.contains(column) else { throw DBRowError.missingColumn(column) } return row[column] } } enum DBRowError: Error, Sendable { case missingColumn(String) } /// Builds a query from fragments, numbering the parameters as they are added. /// For the handlers whose WHERE clause depends on which query parameters the /// caller sent. struct SQLBuilder { private(set) var sql = "" private var binds = PostgresBindings() private var count = 0 init(_ sql: String = "") { self.sql = sql } mutating func append(_ fragment: String) { sql += fragment } /// Appends a fragment with one bound value where `?` appears. mutating func append(_ fragment: String, _ value: Value) { count += 1 binds.append(value) sql += fragment.replacingOccurrences(of: "?", with: "$\(count)") } var query: PostgresQuery { PostgresQuery(unsafeSQL: sql, binds: binds) } }