-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseRowPostgres.swift
More file actions
71 lines (66 loc) · 2.05 KB
/
DatabaseRowPostgres.swift
File metadata and controls
71 lines (66 loc) · 2.05 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
//
// DatabaseRowPostgres.swift
// feather-database-postgres
//
// Created by Tibor Bödecs on 2026. 01. 10.
//
import FeatherDatabase
import PostgresNIO
public struct DatabaseRowPostgres: DatabaseRow {
var row: PostgresRow
/// Decode a column value as the given type.
///
/// This uses Postgres decoding rules for `Decodable` types.
/// - Parameters:
/// - column: The column name to decode.
/// - type: The expected type to decode as.
/// - Throws: A `DecodingError` if the value cannot be decoded.
/// - Returns: The decoded value.
public func decode<T: Decodable>(
column: String,
as type: T.Type
) throws(DecodingError) -> T {
let row = row.makeRandomAccess()
guard row.contains(column) else {
throw .dataCorrupted(
.init(
codingPath: [],
debugDescription: "Missing data for column \(column)."
)
)
}
let cell = row[column]
if let type = type as? any PostgresDecodable.Type {
do {
guard let value = try cell.decode(type, context: .default) as? T
else {
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: [],
debugDescription:
"Could not convert data to \(T.self)."
)
)
}
return value
}
catch {
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: [],
debugDescription: "\(error)"
)
)
}
}
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: [],
debugDescription: "Data is not convertible to \(type)."
)
)
}
}