-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnectionPostgres.swift
More file actions
79 lines (68 loc) · 2.22 KB
/
DatabaseConnectionPostgres.swift
File metadata and controls
79 lines (68 loc) · 2.22 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
//
// DatabaseConnectionPostgres.swift
// feather-database-postgres
//
// Created by Tibor Bödecs on 2026. 01. 10.
//
import FeatherDatabase
import PostgresNIO
extension DatabaseQuery {
fileprivate func toPostgresQuery() -> PostgresQuery {
var postgresUnsafeSQL = sql
var postgresBindings: PostgresBindings = .init()
for binding in bindings {
/// postgres binding index starts with 1
let idx = binding.index + 1
postgresUnsafeSQL =
postgresUnsafeSQL
.replacing("{{\(idx)}}", with: "$\(idx)")
switch binding.binding {
case .bool(let value):
postgresBindings.append(value)
case .int(let value):
postgresBindings.append(value)
case .double(let value):
postgresBindings.append(value)
case .string(let value):
postgresBindings.append(value)
}
}
return .init(
unsafeSQL: postgresUnsafeSQL,
binds: postgresBindings
)
}
}
public struct DatabaseConnectionPostgres: DatabaseConnection {
public typealias RowSequence = DatabaseRowSequencePostgres
var connection: PostgresConnection
public var logger: Logger
/// Execute a Postgres query on this connection.
///
/// This wraps `PostgresNIO` query execution and maps errors.
/// - Parameters:
/// - query: The Postgres query to execute.
/// - handler: A closure that receives the RowSequence result.
/// - Throws: A `DatabaseError` if the query fails.
/// - Returns: A query result containing the returned rows.
@discardableResult
public func run<T: Sendable>(
query: DatabaseQuery,
_ handler: (RowSequence) async throws -> T = { $0 }
) async throws(DatabaseError) -> T {
do {
let sequence = try await connection.query(
query.toPostgresQuery(),
logger: logger
)
return try await handler(
DatabaseRowSequencePostgres(
backingSequence: sequence
)
)
}
catch {
throw .query(error)
}
}
}