Skip to content

Commit ac9d2b6

Browse files
committed
Int type tolerance and better SQLDataType conversion error message
1 parent 81b97d9 commit ac9d2b6

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

Sources/SwiftSQL/SQLDataType.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import SQLite3
1212
public protocol SQLDataType {
1313
func sqlBind(statement: OpaquePointer, index: Int32)
1414
static func sqlColumn(statement: OpaquePointer, index: Int32) -> Self
15+
static func convert(from value: Any) -> Self?
1516
}
1617

1718
public extension SQLDataType {
@@ -26,6 +27,11 @@ extension Int: SQLDataType {
2627
public static func sqlColumn(statement: OpaquePointer, index: Int32) -> Int {
2728
Int(sqlite3_column_int64(statement, index))
2829
}
30+
31+
public static func convert(from value: Any) -> Int? {
32+
guard let int64 = value as? Int64 else { return nil }
33+
return Int(int64)
34+
}
2935
}
3036

3137
extension Int32: SQLDataType {

Sources/SwiftSQLExt/SwiftSQLExt.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,11 @@ public struct SQLRow {
7171
///
7272
/// - parameter index: The leftmost column of the result set has the index 0.
7373
public subscript<T: SQLDataType>(index: Int) -> T {
74-
T.convert(from: values[index]!)!
74+
let value = values[index]!
75+
guard let convertedValue = T.convert(from: value) else {
76+
fatalError("Could not convert \(type(of: value)). Make sure target type (\(T.self)) correctly implements convert(from:).")
77+
}
78+
return convertedValue
7579
}
7680

7781
/// Returns a single column of the current result row of a query. If the

Tests/SwiftSQLExtTests/SwiftSQLExtTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,9 @@ private extension SQLConnection {
170170

171171
private struct User: Hashable, SQLRowDecodable {
172172
let name: String
173-
let level: Int64
173+
let level: Int
174174

175-
init(name: String, level: Int64) {
175+
init(name: String, level: Int) {
176176
self.name = name
177177
self.level = level
178178
}

0 commit comments

Comments
 (0)