-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgresDatabaseClient.swift
More file actions
97 lines (89 loc) · 2.95 KB
/
PostgresDatabaseClient.swift
File metadata and controls
97 lines (89 loc) · 2.95 KB
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
//
// PostgresDatabaseClient.swift
// feather-postgres-database
//
// Created by Tibor Bödecs on 2026. 01. 10..
//
import FeatherDatabase
import Logging
import PostgresNIO
/// A Postgres-backed database client.
///
/// Use this client to execute queries and manage transactions on Postgres.
public struct PostgresDatabaseClient: DatabaseClient {
public typealias Connection = PostgresDatabaseConnection
var client: PostgresNIO.PostgresClient
var logger: Logger
/// Create a Postgres database client.
///
/// Use this initializer to provide an existing Postgres client.
/// - Parameters:
/// - client: The underlying Postgres client.
/// - logger: The logger for database operations.
public init(
client: PostgresNIO.PostgresClient,
logger: Logger
) {
self.client = client
self.logger = logger
}
// MARK: - database api
/// Execute work using a managed Postgres connection.
///
/// The closure receives a Postgres connection for the duration of the call.
/// - Parameter: closure: A closure that receives the connection.
/// - Throws: A `DatabaseError` if connection handling fails.
/// - Returns: The query result produced by the closure.
@discardableResult
public func withConnection<T>(
_ closure: (Connection) async throws -> T,
) async throws(DatabaseError) -> T {
do {
return try await client.withConnection { connection in
let databaseConnection = PostgresDatabaseConnection(
connection: connection,
logger: logger
)
return try await closure(databaseConnection)
}
}
catch let error as DatabaseError {
throw error
}
catch {
throw .connection(error)
}
}
/// Execute work inside a Postgres transaction.
///
/// The closure is wrapped in a transactional scope.
/// - Parameter: closure: A closure that receives the connection.
/// - Throws: A `DatabaseError` if the transaction fails.
/// - Returns: The query result produced by the closure.
@discardableResult
public func withTransaction<T>(
_ closure: (Connection) async throws -> T,
) async throws(DatabaseError) -> T {
do {
return try await client.withTransaction(
logger: logger
) { connection in
let databaseConnection = PostgresDatabaseConnection(
connection: connection,
logger: logger
)
return try await closure(databaseConnection)
}
}
catch let error as PostgresTransactionError {
throw .transaction(
PostgresDatabaseTransactionError(
underlyingError: error
)
)
}
catch {
throw .connection(error)
}
}
}