-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseRowSQLite.swift
More file actions
120 lines (108 loc) · 3.53 KB
/
DatabaseRowSQLite.swift
File metadata and controls
120 lines (108 loc) · 3.53 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//
// DatabaseRowSQLite.swift
// feather-database-sqlite
//
// Created by Tibor Bödecs on 2026. 01. 10.
//
import FeatherDatabase
import SQLiteNIO
public struct DatabaseRowSQLite: DatabaseRow {
var row: SQLiteRow
struct SingleValueDecoder: Decoder, SingleValueDecodingContainer {
var codingPath: [any CodingKey] { [] }
var userInfo: [CodingUserInfoKey: Any] { [:] }
let data: SQLiteData
func container<Key: CodingKey>(
keyedBy: Key.Type
) throws(DecodingError) -> KeyedDecodingContainer<Key> {
throw DecodingError.typeMismatch(
KeyedDecodingContainer<Key>.self,
.init(
codingPath: codingPath,
debugDescription: "Keyed decoding is not supported."
)
)
}
func unkeyedContainer() throws(DecodingError)
-> any UnkeyedDecodingContainer
{
throw DecodingError.typeMismatch(
(any UnkeyedDecodingContainer).self,
.init(
codingPath: codingPath,
debugDescription: "Unkeyed decoding is not supported."
)
)
}
func singleValueContainer() throws(DecodingError)
-> any SingleValueDecodingContainer
{
self
}
func decodeNil() -> Bool {
data.isNull
}
func decode<T: Decodable>(
_ type: T.Type
) throws(DecodingError) -> T {
if let convertible = type as? any SQLiteDataConvertible.Type {
guard let value = convertible.init(sqliteData: data) else {
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: codingPath,
debugDescription:
"Could not convert data to \(T.self): \(data)."
)
)
}
return value as! T
}
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: codingPath,
debugDescription:
"Data is not convertible to \(T.self): \(data)."
)
)
}
}
/// Decode a column value as the given type.
///
/// This uses SQLite data conversion 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 {
guard let data = row.column(column) else {
throw .dataCorrupted(
.init(
codingPath: [],
debugDescription: "Missing data for column \(column)."
)
)
}
do {
return try T(from: SingleValueDecoder(data: data))
}
catch let error as DecodingError {
throw error
}
catch {
throw DecodingError.typeMismatch(
T.self,
.init(
codingPath: [],
debugDescription:
"Data is not convertible to \(T.self): \(data)."
)
)
}
}
}