-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgresDatabaseClient.swift
More file actions
93 lines (84 loc) · 2.83 KB
/
PostgresDatabaseClient.swift
File metadata and controls
93 lines (84 loc) · 2.83 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
//
// PostgresDatabaseClient.swift
// feather-postgres-database
//
// Created by Tibor Bödecs on 2026. 01. 10..
//
import FeatherDatabase
import Logging
import PostgresNIO
/// Make Postgres transaction errors conform to `DatabaseTransactionError`.
///
/// This allows Postgres errors to flow through `DatabaseError`.
extension PostgresTransactionError: @retroactive DatabaseTransactionError {}
/// A Postgres-backed database client.
///
/// Use this client to execute queries and manage transactions on Postgres.
public struct PostgresDatabaseClient: DatabaseClient {
var client: 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: 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.
/// - Parameters:
/// - isolation: The actor isolation for the operation.
/// - 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 connection<T>(
isolation: isolated (any Actor)? = #isolation,
_ closure: (PostgresConnection) async throws -> sending T,
) async throws(DatabaseError) -> sending T {
do {
return try await client.withConnection(closure)
}
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.
/// - Parameters:
/// - isolation: The actor isolation for the operation.
/// - 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 transaction<T>(
isolation: isolated (any Actor)? = #isolation,
_ closure: ((PostgresConnection) async throws -> sending T),
) async throws(DatabaseError) -> sending T {
do {
return try await client.withTransaction(
logger: logger,
isolation: isolation,
closure
)
}
catch let error as PostgresTransactionError {
throw .transaction(error)
}
catch {
throw .connection(error)
}
}
}