diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme
index 237e9f7b3..4fbad19f2 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme
+++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme
@@ -78,8 +78,10 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
-
+
-
+
-
+
-
+
+
+
+
+
diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj
index 167cdd330..85df6e3db 100755
--- a/GRDB.xcodeproj/project.pbxproj
+++ b/GRDB.xcodeproj/project.pbxproj
@@ -267,9 +267,6 @@
564390D52414FC2C00BA61E6 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AAA4DCFE230F1E0600C74B15 /* GRDB.framework */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
- 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
- 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
- 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
@@ -464,6 +461,10 @@
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
+ 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
+ 566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
+ 566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
+ 566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
@@ -980,7 +981,6 @@
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
- AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; };
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; };
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
@@ -1338,7 +1338,6 @@
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = ""; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = ""; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; };
- 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; };
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; };
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; };
@@ -1411,6 +1410,7 @@
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; };
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; };
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; };
+ 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; };
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; };
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; };
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; };
@@ -2281,12 +2281,12 @@
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
- 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
+ 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
@@ -2879,6 +2879,7 @@
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
+ 566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
@@ -2967,7 +2968,6 @@
565490B81D5AE236005622CB /* DatabaseError.swift in Sources */,
56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */,
5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
- 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
56A2FA3C24424F4800E97D23 /* Export.swift in Sources */,
565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */,
563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */,
@@ -3101,7 +3101,6 @@
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */,
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
- 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
@@ -3109,6 +3108,7 @@
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
+ 566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */,
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
@@ -3686,7 +3686,6 @@
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */,
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
- AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */,
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */,
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
@@ -3694,6 +3693,7 @@
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
+ 566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */,
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */,
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */,
@@ -4050,6 +4050,7 @@
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
+ 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
@@ -4063,7 +4064,6 @@
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
- 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift
index f1be5f490..8468ee620 100644
--- a/GRDB/Core/Database.swift
+++ b/GRDB/Core/Database.swift
@@ -449,7 +449,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
- fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
+ fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
}
}
diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift
index c46874706..12d847823 100644
--- a/GRDB/Core/DatabaseFunction.swift
+++ b/GRDB/Core/DatabaseFunction.swift
@@ -130,7 +130,7 @@ public final class DatabaseFunction: Hashable {
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
- fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
+ fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
}
}
@@ -146,7 +146,7 @@ public final class DatabaseFunction: Hashable {
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
- fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
+ fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
}
}
diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift
index 60e75ca47..b6545bcda 100644
--- a/GRDB/Core/DatabaseValue.swift
+++ b/GRDB/Core/DatabaseValue.swift
@@ -115,6 +115,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
}
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
+ @usableFromInline
init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift
deleted file mode 100644
index 0bdbbdf0b..000000000
--- a/GRDB/Core/DatabaseValueConversion.swift
+++ /dev/null
@@ -1,315 +0,0 @@
-// MARK: - Conversion Context and Errors
-
-/// A type that helps the user understanding value conversion errors
-struct ValueConversionContext: Refinable {
- private enum Column {
- case columnIndex(Int)
- case columnName(String)
- }
-
- var row: Row?
- var sql: String?
- var arguments: StatementArguments?
- private var column: Column?
-
- func atColumn(_ columnIndex: Int) -> Self {
- with(\.column, .columnIndex(columnIndex))
- }
-
- func atColumn(_ columnName: String) -> Self {
- with(\.column, .columnName(columnName))
- }
-
- var columnIndex: Int? {
- guard let column = column else { return nil }
- switch column {
- case .columnIndex(let index):
- return index
- case .columnName(let name):
- return row?.index(forColumn: name)
- }
- }
-
- var columnName: String? {
- guard let column = column else { return nil }
- switch column {
- case .columnIndex(let index):
- guard let row = row else { return nil }
- return Array(row.columnNames)[index]
- case .columnName(let name):
- return name
- }
- }
-}
-
-extension ValueConversionContext {
- init(_ statement: SelectStatement) {
- self.init(
- row: Row(statement: statement).copy(),
- sql: statement.sql,
- arguments: statement.arguments,
- column: nil)
- }
-
- init(_ row: Row) {
- if let statement = row.statement {
- self.init(
- row: row.copy(),
- sql: statement.sql,
- arguments: statement.arguments,
- column: nil)
- } else if let sqliteStatement = row.sqliteStatement {
- let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
- self.init(
- row: row.copy(),
- sql: sql,
- arguments: nil,
- column: nil)
- } else {
- self.init(
- row: row.copy(),
- sql: nil,
- arguments: nil,
- column: nil)
- }
- }
-}
-
-/// The canonical conversion error message
-///
-/// - parameter dbValue: nil means "missing column"
-func conversionErrorMessage(
- to: T.Type,
- from dbValue: DatabaseValue?,
- conversionContext: ValueConversionContext?)
--> String
-{
- var message: String
- var extras: [String] = []
-
- if let dbValue = dbValue {
- message = "could not convert database value \(dbValue) to \(T.self)"
- if let columnName = conversionContext?.columnName {
- extras.append("column: `\(columnName)`")
- }
- if let columnIndex = conversionContext?.columnIndex {
- extras.append("column index: \(columnIndex)")
- }
- } else {
- message = "could not read \(T.self) from missing column"
- if let columnName = conversionContext?.columnName {
- message += " `\(columnName)`"
- }
- }
-
- if let row = conversionContext?.row {
- extras.append("row: \(row)")
- }
-
- if let sql = conversionContext?.sql {
- extras.append("sql: `\(sql)`")
- if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
- extras.append("arguments: \(arguments)")
- }
- }
-
- if extras.isEmpty == false {
- message += " (" + extras.joined(separator: ", ") + ")"
- }
- return message
-}
-
-/// The canonical conversion fatal error
-///
-/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
-func fatalConversionError(
- to: T.Type,
- from dbValue: DatabaseValue?,
- conversionContext: ValueConversionContext?,
- file: StaticString = #file,
- line: UInt = #line)
--> Never
-{
- fatalError(
- conversionErrorMessage(
- to: T.self,
- from: dbValue,
- conversionContext: conversionContext),
- file: file,
- line: line)
-}
-
-@usableFromInline
-func fatalConversionError(
- to: T.Type,
- from dbValue: DatabaseValue?,
- in row: Row,
- atColumn columnName: String,
- file: StaticString = #file,
- line: UInt = #line)
--> Never
-{
- fatalConversionError(
- to: T.self,
- from: dbValue,
- conversionContext: ValueConversionContext(row).atColumn(columnName))
-}
-
-@usableFromInline
-func fatalConversionError(
- to: T.Type,
- sqliteStatement: SQLiteStatement,
- index: Int32,
- file: StaticString = #file,
- line: UInt = #line)
--> Never
-{
- let row = Row(sqliteStatement: sqliteStatement)
- fatalConversionError(
- to: T.self,
- from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
- conversionContext: ValueConversionContext(row).atColumn(Int(index)))
-}
-
-@usableFromInline
-func fatalConversionError(
- to: T.Type,
- from dbValue: DatabaseValue?,
- sqliteStatement: SQLiteStatement,
- index: Int32,
- file: StaticString = #file,
- line: UInt = #line)
--> Never
-{
- let row = Row(sqliteStatement: sqliteStatement)
- fatalConversionError(
- to: T.self,
- from: dbValue,
- conversionContext: ValueConversionContext(row).atColumn(Int(index)))
-}
-
-// MARK: - DatabaseValueConvertible
-
-/// Lossless conversions from database values and rows
-extension DatabaseValueConvertible {
- @usableFromInline
- static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
- let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
- if let value = fromDatabaseValue(dbValue) {
- return value
- } else {
- fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
- }
- }
-
- static func decode(
- from dbValue: DatabaseValue,
- conversionContext: @autoclosure () -> ValueConversionContext?)
- -> Self
- {
- if let value = fromDatabaseValue(dbValue) {
- return value
- } else {
- fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
- }
- }
-
- @usableFromInline
- static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
- decode(
- from: row.impl.databaseValue(atUncheckedIndex: index),
- conversionContext: ValueConversionContext(row).atColumn(index))
- }
-
- @usableFromInline
- static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
- let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
- if let value = fromDatabaseValue(dbValue) {
- return value
- } else if dbValue.isNull {
- return nil
- } else {
- fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
- }
- }
-
- static func decodeIfPresent(
- from dbValue: DatabaseValue,
- conversionContext: @autoclosure () -> ValueConversionContext?)
- -> Self?
- {
- // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
- if let value = fromDatabaseValue(dbValue) {
- return value
- } else if dbValue.isNull {
- return nil
- } else {
- fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
- }
- }
-
- @usableFromInline
- static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
- decodeIfPresent(
- from: row.impl.databaseValue(atUncheckedIndex: index),
- conversionContext: ValueConversionContext(row).atColumn(index))
- }
-}
-
-// MARK: - DatabaseValueConvertible & StatementColumnConvertible
-
-/// Lossless conversions from database values and rows
-extension DatabaseValueConvertible where Self: StatementColumnConvertible {
- @inlinable
- static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
- if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
- fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
- }
- return self.init(sqliteStatement: sqliteStatement, index: index)
- }
-
- @inlinable
- static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
- if let sqliteStatement = row.sqliteStatement {
- return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
- }
- return row.fastDecode(Self.self, atUncheckedIndex: index)
- }
-
- @inlinable
- static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
- if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
- return nil
- }
- return self.init(sqliteStatement: sqliteStatement, index: index)
- }
-
- @inlinable
- static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
- if let sqliteStatement = row.sqliteStatement {
- return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
- }
- return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
- }
-}
-
-// Support for @inlinable decoding
-extension Row {
- @usableFromInline
- func fastDecode(
- _ type: Value.Type,
- atUncheckedIndex index: Int)
- -> Value
- {
- impl.fastDecode(type, atUncheckedIndex: index)
- }
-
- @usableFromInline
- func fastDecodeIfPresent(
- _ type: Value.Type,
- atUncheckedIndex index: Int)
- -> Value?
- {
- impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
- }
-}
diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift
index d0089929e..5183169ee 100644
--- a/GRDB/Core/DatabaseValueConvertible.swift
+++ b/GRDB/Core/DatabaseValueConvertible.swift
@@ -28,6 +28,93 @@ extension DatabaseValueConvertible {
}
}
+// MARK: - Conversions
+
+extension DatabaseValueConvertible {
+ static func decode(
+ fromDatabaseValue dbValue: DatabaseValue,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self
+ {
+ if let value = fromDatabaseValue(dbValue) {
+ return value
+ } else {
+ throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
+ }
+ }
+
+ @usableFromInline
+ static func decode(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self
+ {
+ let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
+ return try decode(fromDatabaseValue: dbValue, context: context())
+ }
+
+ @usableFromInline
+ static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
+ if let sqliteStatement = row.sqliteStatement {
+ return try decode(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ return try decode(
+ fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+
+ static func decodeIfPresent(
+ fromDatabaseValue dbValue: DatabaseValue,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self?
+ {
+ // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
+ if let value = fromDatabaseValue(dbValue) {
+ return value
+ } else if dbValue.isNull {
+ return nil
+ } else {
+ throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
+ }
+ }
+
+ @usableFromInline
+ static func decodeIfPresent(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self?
+ {
+ let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
+ if let value = fromDatabaseValue(dbValue) {
+ return value
+ } else if dbValue.isNull {
+ return nil
+ } else {
+ throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
+ }
+ }
+
+ @usableFromInline
+ static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
+ if let sqliteStatement = row.sqliteStatement {
+ return try decodeIfPresent(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ return try decodeIfPresent(
+ fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+}
+
+// MARK: - Cursors
+
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -76,7 +163,11 @@ public final class DatabaseValueCursor: Cursor
_done = true
return nil
case SQLITE_ROW:
- return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
+ // TODO GRDB6: don't crash on decoding errors
+ return try! Value.decode(
+ fromStatement: _sqliteStatement,
+ atUncheckedIndex: _columnIndex,
+ context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
case let code:
try _statement.didFail(withResultCode: code)
}
@@ -131,7 +222,11 @@ public final class NullableDatabaseValueCursor:
_done = true
return nil
case SQLITE_ROW:
- return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
+ // TODO GRDB6: don't crash on decoding errors
+ return try! Value.decodeIfPresent(
+ fromStatement: _sqliteStatement,
+ atUncheckedIndex: _columnIndex,
+ context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
case let code:
try _statement.didFail(withResultCode: code)
}
diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift
index a73f16977..8b098994e 100644
--- a/GRDB/Core/Row.swift
+++ b/GRDB/Core/Row.swift
@@ -166,8 +166,9 @@ extension Row {
/// Fatal errors if index is out of bounds
@inlinable
- func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
+ func checkedIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) -> Int {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
+ return index
}
/// Returns true if and only if one column contains a non-null value, or if
@@ -202,8 +203,7 @@ extension Row {
/// in performance-critical code because it can avoid decoding database
/// values.
public func hasNull(atIndex index: Int) -> Bool {
- _checkIndex(index)
- return impl.hasNull(atUncheckedIndex: index)
+ impl.hasNull(atUncheckedIndex: checkedIndex(index))
}
/// Returns Int64, Double, String, Data or nil, depending on the value
@@ -212,8 +212,7 @@ extension Row {
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
public subscript(_ index: Int) -> DatabaseValueConvertible? {
- _checkIndex(index)
- return impl.databaseValue(atUncheckedIndex: index).storage.value
+ impl.databaseValue(atUncheckedIndex: checkedIndex(index)).storage.value
}
/// Returns the value at given index, converted to the requested type.
@@ -226,8 +225,7 @@ extension Row {
/// fail, a fatal error is raised.
@inlinable
public subscript(_ index: Int) -> Value? {
- _checkIndex(index)
- return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
+ try! decodeIfPresent(Value.self, atIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -244,8 +242,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript(_ index: Int) -> Value? {
- _checkIndex(index)
- return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
+ try! decodeIfPresent(Value.self, atIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -257,8 +254,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript(_ index: Int) -> Value {
- _checkIndex(index)
- return Value.decode(from: self, atUncheckedIndex: index)
+ try! decode(Value.self, atIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -274,8 +270,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript(_ index: Int) -> Value {
- _checkIndex(index)
- return Value.fastDecode(from: self, atUncheckedIndex: index)
+ try! decode(Value.self, atIndex: index)
}
/// Returns Int64, Double, String, Data or nil, depending on the value
@@ -309,10 +304,7 @@ extension Row {
/// `Value`. Should this conversion fail, a fatal error is raised.
@inlinable
public subscript(_ columnName: String) -> Value? {
- guard let index = index(forColumn: columnName) else {
- return nil
- }
- return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
+ try! decodeIfPresent(Value.self, forKey: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -329,10 +321,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript(_ columnName: String) -> Value? {
- guard let index = index(forColumn: columnName) else {
- return nil
- }
- return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
+ try! decodeIfPresent(Value.self, forKey: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -346,11 +335,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript(_ columnName: String) -> Value {
- guard let index = index(forColumn: columnName) else {
- // No such column
- fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
- }
- return Value.decode(from: self, atUncheckedIndex: index)
+ try! decode(Value.self, forKey: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -368,11 +353,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript(_ columnName: String) -> Value {
- guard let index = index(forColumn: columnName) else {
- // No such column
- fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
- }
- return Value.fastDecode(from: self, atUncheckedIndex: index)
+ try! decode(Value.self, forKey: columnName)
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
@@ -397,7 +378,7 @@ extension Row {
/// `Value`. Should this conversion fail, a fatal error is raised.
@inlinable
public subscript(_ column: Column) -> Value? {
- self[column.name]
+ try! decodeIfPresent(Value.self, forKey: column.name)
}
/// Returns the value at given column, converted to the requested type.
@@ -419,7 +400,7 @@ extension Row {
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
- self[column.name]
+ try! decodeIfPresent(Value.self, forKey: column.name)
}
/// Returns the value at given column, converted to the requested type.
@@ -433,7 +414,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript(_ column: Column) -> Value {
- self[column.name]
+ try! decode(Value.self, forKey: column.name)
}
/// Returns the value at given column, converted to the requested type.
@@ -456,7 +437,7 @@ extension Row {
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
- self[column.name]
+ try! decode(Value.self, forKey: column.name)
}
/// Returns the optional Data at given index.
@@ -470,8 +451,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(atIndex index: Int) -> Data? {
- _checkIndex(index)
- return impl.dataNoCopy(atUncheckedIndex: index)
+ try! decodeDataNoCopyIfPresent(atIndex: index)
}
/// Returns the optional Data at given column.
@@ -486,10 +466,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(named columnName: String) -> Data? {
- guard let index = index(forColumn: columnName) else {
- return nil
- }
- return impl.dataNoCopy(atUncheckedIndex: index)
+ try! decodeDataNoCopyIfPresent(forKey: columnName)
}
/// Returns the optional `NSData` at given column.
@@ -504,7 +481,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(_ column: Column) -> Data? {
- dataNoCopy(named: column.name)
+ try! decodeDataNoCopyIfPresent(forKey: column.name)
}
}
@@ -557,20 +534,7 @@ extension Row {
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
public subscript(_ scope: String) -> Record {
- guard let scopedRow = scopesTree[scope] else {
- // Programmer error
- let names = scopesTree.names
- if names.isEmpty {
- fatalError("missing scope `\(scope)` (row: \(self))")
- } else {
- fatalError("missing scope `\(scope)` (row: \(self), available scopes: \(names.sorted()))")
- }
- }
- guard scopedRow.containsNonNullValue else {
- // Programmer error
- fatalError("scope `\(scope)` only contains null values (row: \(self))")
- }
- return Record(row: scopedRow)
+ try! decode(Record.self, forKey: scope)
}
/// Returns the eventual record associated with the given scope.
@@ -605,10 +569,7 @@ extension Row {
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
public subscript(_ scope: String) -> Record? {
- guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
- return nil
- }
- return Record(row: scopedRow)
+ try! decodeIfPresent(Record.self, forKey: scope)
}
/// Returns the records encoded in the given prefetched rows.
@@ -630,21 +591,7 @@ extension Row {
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
- guard let rows = prefetchedRows[key] else {
- // Programmer error
- let keys = prefetchedRows.keys
- if keys.isEmpty {
- fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
- } else {
- fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
- }
- }
- var collection = Collection()
- collection.reserveCapacity(rows.count)
- for row in rows {
- collection.append(Collection.Element(row: row))
- }
- return collection
+ try! decode(Collection.self, forKey: key)
}
/// Returns the set of records encoded in the given prefetched rows.
@@ -661,20 +608,7 @@ extension Row {
/// print(books.first!.title)
/// // Prints "Moby-Dick"
public subscript(_ key: String) -> Set {
- guard let rows = prefetchedRows[key] else {
- // Programmer error
- let keys = prefetchedRows.keys
- if keys.isEmpty {
- fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
- } else {
- fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
- }
- }
- var set = Set(minimumCapacity: rows.count)
- for row in rows {
- set.insert(Record(row: row))
- }
- return set
+ try! decode(Set.self, forKey: key)
}
}
@@ -761,6 +695,492 @@ extension Row {
}
}
+// MARK: - Throwing DatabaseValueConvertible Decoding Methods
+
+extension Row {
+ /// Returns the value at given index, converted to the requested type.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
+ /// value is converted to the requested type `Value`. If the conversion
+ /// fail, a `RowDecodingError` is thrown.
+ @inlinable
+ func decodeIfPresent(
+ _ type: Value.Type = Value.self,
+ atIndex index: Int)
+ throws -> Value?
+ {
+ try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the value at given index, converted to the requested type.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, or if the conversion fails, a
+ /// `RowDecodingError` is thrown.
+ @inlinable
+ func decode(
+ _ type: Value.Type = Value.self,
+ atIndex index: Int)
+ throws -> Value
+ {
+ try Value.decode(fromRow: self, atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the value at given column, converted to the requested type.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the column is missing or if the SQLite value is NULL, the result is
+ /// nil. Otherwise the SQLite value is converted to the requested type
+ /// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
+ @inlinable
+ func decodeIfPresent(
+ _ type: Value.Type = Value.self,
+ forKey columnName: String)
+ throws -> Value?
+ {
+ guard let index = index(forColumn: columnName) else {
+ return nil
+ }
+ return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index)
+ }
+
+ /// Returns the value at given column, converted to the requested type.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the row does not contain the column, or if the SQLite value is NULL,
+ /// or if the SQLite value can not be converted to `Value`, a
+ /// `RowDecodingError` is thrown.
+ @inlinable
+ func decode(
+ _ type: Value.Type = Value.self,
+ forKey columnName: String)
+ throws -> Value
+ {
+ guard let index = index(forColumn: columnName) else {
+ throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
+ }
+ return try Value.decode(fromRow: self, atUncheckedIndex: index)
+ }
+}
+
+// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
+
+extension Row {
+ /// Returns the value at given index, converted to the requested type.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
+ /// value is converted to the requested type `Value`. If the conversion
+ /// fail, a `RowDecodingError` is thrown.
+ ///
+ /// This method exists as an optimization opportunity for types that adopt
+ /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
+ /// (see https://www.sqlite.org/datatype3.html).
+ @inlinable
+ func decodeIfPresent(
+ _ type: Value.Type = Value.self,
+ atIndex index: Int)
+ throws -> Value?
+ {
+ try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the value at given index, converted to the requested type.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, or if the conversion fails, a
+ /// `RowDecodingError` is thrown.
+ ///
+ /// This method exists as an optimization opportunity for types that adopt
+ /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
+ /// (see https://www.sqlite.org/datatype3.html).
+ @inlinable
+ func decode(
+ _ type: Value.Type = Value.self,
+ atIndex index: Int)
+ throws -> Value
+ {
+ try Value.fastDecode(fromRow: self, atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the value at given column, converted to the requested type.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the column is missing or if the SQLite value is NULL, the result is
+ /// nil. Otherwise the SQLite value is converted to the requested type
+ /// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
+ ///
+ /// This method exists as an optimization opportunity for types that adopt
+ /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
+ /// (see https://www.sqlite.org/datatype3.html).
+ @inlinable
+ func decodeIfPresent(
+ _ type: Value.Type = Value.self,
+ forKey columnName: String)
+ throws -> Value?
+ {
+ guard let index = index(forColumn: columnName) else {
+ return nil
+ }
+ return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index)
+ }
+
+ /// Returns the value at given column, converted to the requested type.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the row does not contain the column, or if the SQLite value is NULL,
+ /// or if the SQLite value can not be converted to `Value`, a
+ /// `RowDecodingError` is thrown.
+ ///
+ /// This method exists as an optimization opportunity for types that adopt
+ /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
+ /// (see https://www.sqlite.org/datatype3.html).
+ @inlinable
+ func decode(
+ _ type: Value.Type = Value.self,
+ forKey columnName: String)
+ throws -> Value
+ {
+ guard let index = index(forColumn: columnName) else {
+ throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
+ }
+ return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
+ }
+
+ // Support for fast decoding in scoped rows
+ @usableFromInline
+ func fastDecode(
+ _ type: Value.Type,
+ atUncheckedIndex index: Int)
+ throws -> Value
+ {
+ try impl.fastDecode(type, atUncheckedIndex: index)
+ }
+
+ // Support for fast decoding in scoped rows
+ @usableFromInline
+ func fastDecodeIfPresent(
+ _ type: Value.Type,
+ atUncheckedIndex index: Int)
+ throws -> Value?
+ {
+ try impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
+ }
+}
+
+// MARK: - Throwing Data Decoding Methods
+
+extension Row {
+ /// Returns the optional Data at given index.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, the result is nil. If the SQLite value can
+ /// not be converted to Data, a `RowDecodingError` is thrown.
+ ///
+ /// The returned data does not owns its bytes: it must not be used longer
+ /// than the row's lifetime.
+ func decodeDataNoCopyIfPresent(atIndex index: Int) throws -> Data? {
+ try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the Data at given index.
+ ///
+ /// Indexes span from 0 for the leftmost column to (row.count - 1) for the
+ /// righmost column.
+ ///
+ /// If the SQLite value is NULL, or if the SQLite value can not be converted
+ /// to Data, a `RowDecodingError` is thrown.
+ ///
+ /// The returned data does not owns its bytes: it must not be used longer
+ /// than the row's lifetime.
+ func decodeDataNoCopy(atIndex index: Int) throws -> Data {
+ try impl.fastDecodeDataNoCopy(atUncheckedIndex: checkedIndex(index))
+ }
+
+ /// Returns the optional Data at given column.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the column is missing or if the SQLite value is NULL, the result is
+ /// nil. If the SQLite value can not be converted to Data, a
+ /// `RowDecodingError` is thrown.
+ ///
+ /// The returned data does not owns its bytes: it must not be used longer
+ /// than the row's lifetime.
+ func decodeDataNoCopyIfPresent(forKey columnName: String) throws -> Data? {
+ guard let index = index(forColumn: columnName) else {
+ return nil
+ }
+ return try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
+ }
+
+ /// Returns the Data at given column.
+ ///
+ /// Column name lookup is case-insensitive, and when several columns have
+ /// the same name, the leftmost column is considered.
+ ///
+ /// If the column is missing, or if the SQLite value is NULL, or if the
+ /// SQLite value can not be converted to Data, a
+ /// `RowDecodingError` is thrown.
+ ///
+ /// The returned data does not owns its bytes: it must not be used longer
+ /// than the row's lifetime.
+ func decodeDataNoCopy(forKey columnName: String) throws -> Data {
+ guard let index = index(forColumn: columnName) else {
+ throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
+ }
+ return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index)
+ }
+
+ // Support for fast decoding in scoped rows
+ @usableFromInline
+ func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
+ try impl.fastDecodeDataNoCopy(atUncheckedIndex: index)
+ }
+
+ // Support for fast decoding in scoped rows
+ @usableFromInline
+ func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
+ try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
+ }
+}
+
+// MARK: - Throwing Record Decoding Methods
+
+extension Row {
+ /// Returns the eventual record associated with the given scope.
+ ///
+ /// For example:
+ ///
+ /// let request = Book.including(optional: Book.author)
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Book(row: row).title)
+ /// // Prints "Moby-Dick"
+ ///
+ /// let author: Author? = row["author"]
+ /// print(author.name)
+ /// // Prints "Herman Melville"
+ ///
+ /// Associated records stored in nested associations are available, too:
+ ///
+ /// let request = Book.including(optional: Book.author.including(optional: Author.country))
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Book(row: row).title)
+ /// // Prints "Moby-Dick"
+ ///
+ /// let country: Country? = row["country"]
+ /// print(country.name)
+ /// // Prints "United States"
+ ///
+ /// Nil is returned if the scope is not available, or contains only
+ /// null values.
+ ///
+ /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
+ /// for more information.
+ func decodeIfPresent(
+ _ type: Record.Type = Record.self,
+ forKey scope: String)
+ throws -> Record?
+ {
+ guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
+ return nil
+ }
+ return Record(row: scopedRow)
+ }
+
+ /// Returns the record associated with the given scope.
+ ///
+ /// For example:
+ ///
+ /// let request = Book.including(required: Book.author)
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Book(row: row).title)
+ /// // Prints "Moby-Dick"
+ ///
+ /// let author: Author = row["author"]
+ /// print(author.name)
+ /// // Prints "Herman Melville"
+ ///
+ /// Associated records stored in nested associations are available, too:
+ ///
+ /// let request = Book.including(required: Book.author.including(required: Author.country))
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Book(row: row).title)
+ /// // Prints "Moby-Dick"
+ ///
+ /// let country: Country = row["country"]
+ /// print(country.name)
+ /// // Prints "United States"
+ ///
+ /// A fatal error is raised if the scope is not available, or contains only
+ /// null values.
+ ///
+ /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
+ /// for more information.
+ func decode(
+ _ type: Record.Type = Record.self,
+ forKey scope: String)
+ throws -> Record
+ {
+ guard let scopedRow = scopesTree[scope] else {
+ let availableScopes = scopesTree.names
+ if availableScopes.isEmpty {
+ throw RowDecodingError.keyNotFound(
+ .scope(scope),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ scope not found: \(String(reflecting: scope))
+ """))
+ } else {
+ throw RowDecodingError.keyNotFound(
+ .scope(scope),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ scope not found: \(String(reflecting: scope)) - \
+ available scopes: \(availableScopes.sorted())
+ """))
+ }
+ }
+ guard scopedRow.containsNonNullValue else {
+ throw RowDecodingError.valueMismatch(
+ Record.self,
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self, key: .scope(scope)),
+ debugDescription: """
+ scope \(String(reflecting: scope)) only contains null values
+ """))
+ }
+ return Record(row: scopedRow)
+ }
+}
+
+// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
+
+extension Row {
+ /// Returns the records encoded in the given prefetched rows.
+ ///
+ /// For example:
+ ///
+ /// let request = Author.including(all: Author.books)
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Author(row: row).name)
+ /// // Prints "Herman Melville"
+ ///
+ /// let books: [Book] = row["books"]
+ /// print(books[0].title)
+ /// // Prints "Moby-Dick"
+ func decode(
+ _ type: Collection.Type = Collection.self,
+ forKey key: String)
+ throws -> Collection
+ where
+ Collection: RangeReplaceableCollection,
+ Collection.Element: FetchableRecord
+ {
+ guard let rows = prefetchedRows[key] else {
+ let availableKeys = prefetchedRows.keys
+ if availableKeys.isEmpty {
+ throw RowDecodingError.keyNotFound(
+ .prefetchKey(key),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ key for prefetched rows not found: \(String(reflecting: key))
+ """))
+ } else {
+ throw RowDecodingError.keyNotFound(
+ .prefetchKey(key),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ key for prefetched rows not found: \(String(reflecting: key)) \
+ - available keys: \(availableKeys.sorted())
+ """))
+ }
+ }
+
+ var collection = Collection()
+ collection.reserveCapacity(rows.count)
+ for row in rows {
+ collection.append(Collection.Element(row: row))
+ }
+ return collection
+ }
+
+ /// Returns the set of records encoded in the given prefetched rows.
+ ///
+ /// For example:
+ ///
+ /// let request = Author.including(all: Author.books)
+ /// let row = try Row.fetchOne(db, request)!
+ ///
+ /// print(Author(row: row).name)
+ /// // Prints "Herman Melville"
+ ///
+ /// let books: Set = row["books"]
+ /// print(books.first!.title)
+ /// // Prints "Moby-Dick"
+ func decode(
+ _ type: Set.Type = Set.self,
+ forKey key: String)
+ throws -> Set
+ {
+ guard let rows = prefetchedRows[key] else {
+ let availableKeys = prefetchedRows.keys
+ if availableKeys.isEmpty {
+ throw RowDecodingError.keyNotFound(
+ .prefetchKey(key),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ key for prefetched rows not found: \(String(reflecting: key))
+ """))
+ } else {
+ throw RowDecodingError.keyNotFound(
+ .prefetchKey(key),
+ RowDecodingError.Context(
+ decodingContext: RowDecodingContext(row: self),
+ debugDescription: """
+ key for prefetched rows not found: \(String(reflecting: key)) \
+ - available keys: \(availableKeys.sorted())
+ """))
+ }
+ }
+ var set = Set(minimumCapacity: rows.count)
+ for row in rows {
+ set.insert(Record(row: row))
+ }
+ return set
+ }
+}
+
// MARK: - RowCursor
/// A cursor of database rows. For example:
@@ -1218,8 +1638,7 @@ extension Row {
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
- let index = position.index
- _checkIndex(index)
+ let index = checkedIndex(position.index)
return (
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
@@ -1647,15 +2066,20 @@ protocol RowImpl {
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index: Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
+
func fastDecode(
_ type: Value.Type,
atUncheckedIndex index: Int)
- -> Value
+ throws -> Value
+
func fastDecodeIfPresent(
_ type: Value.Type,
atUncheckedIndex index: Int)
- -> Value?
- func dataNoCopy(atUncheckedIndex index: Int) -> Data?
+ throws -> Value?
+
+ func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data
+
+ func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data?
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(forColumn name: String) -> Int?
@@ -1694,29 +2118,38 @@ extension RowImpl {
func fastDecode(
_ type: Value.Type,
- atUncheckedIndex index: Int) -> Value
+ atUncheckedIndex index: Int)
+ throws -> Value
{
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
- return Value.decode(
- from: databaseValue(atUncheckedIndex: index),
- conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
+ return try Value.decode(
+ fromDatabaseValue: databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
}
func fastDecodeIfPresent(
_ type: Value.Type,
- atUncheckedIndex index: Int) -> Value?
+ atUncheckedIndex index: Int)
+ throws -> Value?
{
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
- return Value.decodeIfPresent(
- from: databaseValue(atUncheckedIndex: index),
- conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
+ return try Value.decodeIfPresent(
+ fromDatabaseValue: databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
}
- func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
+ func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
- return Data.decodeIfPresent(
- from: databaseValue(atUncheckedIndex: index),
- conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
+ return try Data.decode(
+ fromDatabaseValue: databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
+ }
+
+ func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
+ // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
+ return try Data.decodeIfPresent(
+ fromDatabaseValue: databaseValue(atUncheckedIndex: index),
+ context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
}
}
@@ -1820,9 +2253,35 @@ private struct StatementRowImpl: RowImpl {
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
}
- func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
+ func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
+ DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
+ }
+
+ func fastDecode(
+ _ type: Value.Type,
+ atUncheckedIndex index: Int)
+ throws -> Value
+ {
+ try Value.fastDecode(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(statement: statement, index: index))
+ }
+
+ func fastDecodeIfPresent(
+ _ type: Value.Type,
+ atUncheckedIndex index: Int)
+ throws -> Value?
+ {
+ try Value.fastDecodeIfPresent(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(statement: statement, index: index))
+ }
+
+ func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
- return nil
+ throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index)
}
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
return Data()
@@ -1831,22 +2290,15 @@ private struct StatementRowImpl: RowImpl {
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
- func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
- DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
- }
-
- func fastDecode(
- _ type: Value.Type,
- atUncheckedIndex index: Int) -> Value
- {
- Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
- }
-
- func fastDecodeIfPresent(
- _ type: Value.Type,
- atUncheckedIndex index: Int) -> Value?
- {
- Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
+ func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
+ guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
+ return nil
+ }
+ guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
+ return Data()
+ }
+ let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
+ return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
func columnName(atUncheckedIndex index: Int) -> String {
@@ -1879,17 +2331,6 @@ private struct SQLiteStatementRowImpl: RowImpl {
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
- func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
- guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
- return nil
- }
- guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
- return Data()
- }
- let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
- return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
- }
-
func index(forColumn name: String) -> Int? {
let name = name.lowercased()
for index in 0..(
_ type: Value.Type,
- atUncheckedIndex index: Int) -> Value
+ atUncheckedIndex index: Int)
+ throws -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
- return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
+ return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
}
func fastDecodeIfPresent(
_ type: Value.Type,
- atUncheckedIndex index: Int) -> Value?
+ atUncheckedIndex index: Int)
+ throws -> Value?
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
- return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
+ return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex)
}
- func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
+ func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
- return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
+ return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
+ }
+
+ func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
+ let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
+ return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
}
func columnName(atUncheckedIndex index: Int) -> String {
diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift
new file mode 100644
index 000000000..6392886ec
--- /dev/null
+++ b/GRDB/Core/RowDecodingError.swift
@@ -0,0 +1,205 @@
+/// A key that is used to decode a value in a row
+@usableFromInline
+enum RowKey: Hashable {
+ /// A column name
+ case columnName(String)
+
+ /// A column index
+ case columnIndex(Int)
+
+ /// A scope
+ case scope(String)
+
+ /// A key of prefetched rows
+ case prefetchKey(String)
+}
+
+/// A decoding error
+@usableFromInline
+enum RowDecodingError: Error {
+ @usableFromInline
+ struct Context: CustomDebugStringConvertible {
+ /// A description of what went wrong, for debugging purposes.
+ @usableFromInline
+ let debugDescription: String
+
+ /// The row that could not be decoded
+ let row: Row
+
+ /// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
+ let key: RowKey?
+
+ /// The SQL query
+ let sql: String?
+
+ /// The SQL query arguments
+ let statementArguments: StatementArguments?
+
+ @usableFromInline
+ init(decodingContext: RowDecodingContext, debugDescription: String) {
+ self.debugDescription = debugDescription
+ self.row = decodingContext.row
+ self.key = decodingContext.key
+ self.sql = decodingContext.sql
+ self.statementArguments = decodingContext.statementArguments
+ }
+ }
+
+ case keyNotFound(RowKey, Context)
+ case valueMismatch(Any.Type, Context)
+
+ var context: Context {
+ switch self {
+ case .keyNotFound(_, let context),
+ .valueMismatch(_, let context):
+ return context
+ }
+ }
+
+ /// Convenience method that builds the
+ /// `could not decode from database value ` error message.
+ static func valueMismatch(
+ _ type: Any.Type,
+ context: RowDecodingContext,
+ databaseValue: DatabaseValue)
+ -> Self
+ {
+ valueMismatch(
+ type,
+ RowDecodingError.Context(decodingContext: context, debugDescription: """
+ could not decode \(type) from database value \(databaseValue)
+ """))
+ }
+
+ /// Convenience method that builds the
+ /// `could not decode from database value ` error message.
+ @usableFromInline
+ static func valueMismatch(
+ _ type: Any.Type,
+ sqliteStatement: SQLiteStatement,
+ index: Int32,
+ context: RowDecodingContext)
+ -> Self
+ {
+ valueMismatch(
+ type,
+ context: context,
+ databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
+ }
+
+ /// Convenience method that builds the
+ /// `could not decode from database value ` error message.
+ @usableFromInline
+ static func valueMismatch(
+ _ type: Any.Type,
+ statement: SelectStatement,
+ index: Int)
+ -> Self
+ {
+ valueMismatch(
+ type,
+ context: RowDecodingContext(statement: statement, index: index),
+ databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index)))
+ }
+
+ /// Convenience method that builds the `column not found: `
+ /// error message.
+ @usableFromInline
+ static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
+ keyNotFound(
+ .columnName(columnName),
+ RowDecodingError.Context(decodingContext: context, debugDescription: """
+ column not found: \(String(reflecting: columnName))
+ """))
+ }
+}
+
+@usableFromInline
+struct RowDecodingContext {
+ /// The row that is decoded
+ let row: Row
+
+ let key: RowKey?
+
+ /// The SQL query
+ let sql: String?
+
+ /// The SQL query arguments
+ let statementArguments: StatementArguments?
+
+ @usableFromInline
+ init(row: Row, key: RowKey? = nil) {
+ if let statement = row.statement {
+ self.key = key
+ self.row = row.copy()
+ self.sql = statement.sql
+ self.statementArguments = statement.arguments
+ } else if let sqliteStatement = row.sqliteStatement {
+ self.key = key
+ self.row = row.copy()
+ self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
+ self.statementArguments = nil // Can't rebuild them
+ } else {
+ self.key = key
+ self.row = row.copy()
+ self.sql = nil
+ self.statementArguments = nil
+ }
+ }
+
+ /// Convenience initializer
+ @usableFromInline
+ init(statement: SelectStatement, index: Int) {
+ self.key = .columnIndex(index)
+ self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement)
+ self.sql = statement.sql
+ self.statementArguments = statement.arguments
+ }
+}
+
+extension RowDecodingError: CustomStringConvertible {
+ @usableFromInline
+ var description: String {
+ let context = self.context
+ let row = context.row
+ var chunks: [String] = []
+
+ if let key = context.key {
+ switch key {
+ case let .columnIndex(columnIndex):
+ let rowIndex = row.index(row.startIndex, offsetBy: columnIndex)
+ let columnName = row.columnNames[rowIndex]
+ chunks.append("column: \(String(reflecting: columnName))")
+ chunks.append("column index: \(columnIndex)")
+
+ case let .columnName(columnName):
+ if let columnIndex = row.index(forColumn: columnName) {
+ chunks.append("column: \(String(reflecting: columnName))")
+ chunks.append("column index: \(columnIndex)")
+ } else {
+ // column name is already mentionned in context.debugDescription
+ }
+
+ case .prefetchKey:
+ // key is already mentionned in context.debugDescription
+ break
+
+ case .scope:
+ // scope is already mentionned in context.debugDescription
+ break
+ }
+ }
+
+ chunks.append("row: \(row.description)")
+
+ if let sql = context.sql {
+ chunks.append("sql: `\(sql)`")
+ }
+
+ if let statementArguments = context.statementArguments {
+ chunks.append("arguments: \(statementArguments)")
+ }
+
+ return "\(context.debugDescription) - \(chunks.joined(separator: ", "))"
+ }
+}
diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift
index 6e8304333..258b57cc3 100644
--- a/GRDB/Core/Statement.swift
+++ b/GRDB/Core/Statement.swift
@@ -244,7 +244,7 @@ public class Statement {
// It looks like sqlite3_bind_xxx() functions do not access the file system.
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
guard code == SQLITE_OK else {
- fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
+ fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
}
}
@@ -255,7 +255,7 @@ public class Statement {
// no point throwing any error.
let code = sqlite3_clear_bindings(sqliteStatement)
guard code == SQLITE_OK else {
- fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
+ fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
}
}
diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift
index 4889d58bb..50a2d6835 100644
--- a/GRDB/Core/StatementColumnConvertible.swift
+++ b/GRDB/Core/StatementColumnConvertible.swift
@@ -18,32 +18,107 @@
/// score = row["score"] // there
/// }
/// }
-///
-/// `StatementColumnConvertible` is already adopted by all Swift integer types,
-/// `Float`, `Double`, `String`, and `Bool`.
public protocol StatementColumnConvertible {
- /// Initializes a value from a raw SQLite statement pointer.
+ /// Initializes a value from a raw SQLite statement pointer, if possible.
///
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
/// extension Int64: StatementColumnConvertible {
- /// init(sqliteStatement: SQLiteStatement, index: Int32) {
+ /// init?(sqliteStatement: SQLiteStatement, index: Int32) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
///
- /// This initializer is never called for NULL database values: don't perform
- /// any extra check.
+ /// This initializer is never called for NULL database values. Just return
+ /// `nil` for failed conversions: GRDB will interpret a nil result as a
+ /// decoding failure.
///
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
- init(sqliteStatement: SQLiteStatement, index: Int32)
+ init?(sqliteStatement: SQLiteStatement, index: Int32)
}
+// MARK: - Conversions
+
+extension DatabaseValueConvertible where Self: StatementColumnConvertible {
+ @inlinable
+ static func fastDecode(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self
+ {
+ guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL,
+ let value = self.init(sqliteStatement: sqliteStatement, index: index)
+ else {
+ throw RowDecodingError.valueMismatch(
+ Self.self,
+ sqliteStatement: sqliteStatement,
+ index: index,
+ context: context())
+ }
+ return value
+ }
+
+ @inlinable
+ static func fastDecode(
+ fromRow row: Row,
+ atUncheckedIndex index: Int)
+ throws -> Self
+ {
+ if let sqliteStatement = row.sqliteStatement {
+ return try fastDecode(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ // Support for fast decoding from adapted rows
+ return try row.fastDecode(Self.self, atUncheckedIndex: index)
+ }
+
+ @inlinable
+ static func fastDecodeIfPresent(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Self?
+ {
+ if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
+ return nil
+ }
+ guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else {
+ throw RowDecodingError.valueMismatch(
+ Self.self,
+ sqliteStatement: sqliteStatement,
+ index: index,
+ context: context())
+ }
+ return value
+ }
+
+ @inlinable
+ static func fastDecodeIfPresent(
+ fromRow row: Row,
+ atUncheckedIndex index: Int)
+ throws -> Self?
+ {
+ if let sqliteStatement = row.sqliteStatement {
+ return try fastDecodeIfPresent(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ // Support for fast decoding from adapted rows
+ return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
+ }
+}
+
+// MARK: - Cursors
+
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -92,7 +167,11 @@ public final class FastDatabaseValueCursor RowDecodingContext)
+ throws -> Data
+ {
+ guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
+ throw RowDecodingError.valueMismatch(
+ Data.self,
+ sqliteStatement: sqliteStatement,
+ index: index,
+ context: context())
+ }
+ guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
+ return Data()
+ }
+ let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
+ return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
+ }
+
+ @inlinable
+ static func fastDecodeNoCopy(
+ fromRow row: Row,
+ atUncheckedIndex index: Int)
+ throws -> Data
+ {
+ if let sqliteStatement = row.sqliteStatement {
+ return try fastDecodeNoCopy(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ // Support for fast decoding from adapted rows
+ return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
+ }
+
+ @inlinable
+ static func fastDecodeNoCopyIfPresent(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ -> Data?
+ {
+ guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
+ return nil
+ }
+ guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
+ return Data()
+ }
+ let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
+ return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
+ }
+
+ @inlinable
+ static func fastDecodeNoCopyIfPresent(
+ fromRow row: Row,
+ atUncheckedIndex index: Int)
+ throws -> Data?
+ {
+ if let sqliteStatement = row.sqliteStatement {
+ return fastDecodeNoCopyIfPresent(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
+ }
+ // Support for fast decoding from adapted rows
+ return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
+ }
+}
diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift
index ffae7667a..57f930d94 100644
--- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift
+++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift
@@ -69,9 +69,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
- fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let optionalComponents = cString.withMemoryRebound(
@@ -80,7 +80,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
SQLiteDateParser().components(cString: cString, length: length)
}
guard let components = optionalComponents else {
- fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
self.dateComponents = components.dateComponents
self.format = components.format
diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift
index 8f0b3c1d2..929302d3a 100644
--- a/GRDB/Core/Support/Foundation/Date.swift
+++ b/GRDB/Core/Support/Foundation/Date.swift
@@ -119,18 +119,19 @@ extension Date: StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
- let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
- guard let date = Date(databaseDateComponents: databaseDateComponents) else {
- fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
+ guard let components = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index),
+ let date = Date(databaseDateComponents: components)
+ else {
+ return nil
}
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
default:
- fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
}
}
diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift
index 195e3d641..1dac7425e 100644
--- a/GRDB/Core/Support/Foundation/UUID.swift
+++ b/GRDB/Core/Support/Foundation/UUID.swift
@@ -50,23 +50,23 @@ extension UUID: DatabaseValueConvertible {
extension UUID: StatementColumnConvertible {
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
guard let uuid = UUID(uuidString: string) else {
- fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
- fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
default:
- fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
+ return nil
}
}
}
diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
index ce7dddb99..a6d0e5a10 100644
--- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
+++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
@@ -96,13 +96,10 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = Int(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: Int.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = Int(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -125,13 +122,10 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = Int8(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: Int8.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = Int8(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -154,13 +148,10 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = Int16(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: Int16.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = Int16(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -183,13 +174,10 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = Int32(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: Int32.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = Int32(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -245,13 +233,10 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = UInt(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: UInt.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = UInt(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -274,13 +259,10 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = UInt8(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: UInt8.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = UInt8(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -303,13 +285,10 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = UInt16(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: UInt16.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = UInt16(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -332,13 +311,10 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = UInt32(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: UInt32.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = UInt32(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
@@ -361,13 +337,10 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
- public init(sqliteStatement: SQLiteStatement, index: Int32) {
+ public init?(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
- if let v = UInt64(exactly: int64) {
- self = v
- } else {
- fatalConversionError(to: UInt64.self, sqliteStatement: sqliteStatement, index: index)
- }
+ guard let v = UInt64(exactly: int64) else { return nil }
+ self = v
}
/// Returns a value that can be stored in the database.
diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift
index 54f777dc3..6caf8814b 100644
--- a/GRDB/FTS/FTS5CustomTokenizer.swift
+++ b/GRDB/FTS/FTS5CustomTokenizer.swift
@@ -161,7 +161,7 @@ extension Database {
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
- fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
+ fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
}
}
}
diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift
index 373379a30..bdfd96c45 100644
--- a/GRDB/Record/FetchableRecord+Decodable.swift
+++ b/GRDB/Record/FetchableRecord+Decodable.swift
@@ -57,7 +57,7 @@ private struct _RowDecoder: Decoder {
// Don't use DecodingError.keyNotFound:
// We need to specifically recognize missing columns in order to
// provide correct feedback.
- throw MissingColumnError(column: key.stringValue)
+ throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row))
}
// TODO: test
// See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
@@ -96,20 +96,22 @@ private struct _RowDecoder: Decoder {
}
// swiftlint:disable comma
- func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.row[key.stringValue] }
- func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.row[key.stringValue] }
- func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.row[key.stringValue] }
- func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.row[key.stringValue] }
- func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.row[key.stringValue] }
- func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.row[key.stringValue] }
- func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.row[key.stringValue] }
- func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.row[key.stringValue] }
- func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.row[key.stringValue] }
- func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.row[key.stringValue] }
- func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.row[key.stringValue] }
- func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.row[key.stringValue] }
- func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.row[key.stringValue] }
- func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.row[key.stringValue] }
+ // swiftlint:disable line_length
+ func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: key.stringValue) }
+ func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: key.stringValue) }
+ // swiftlint:enable line_length
// swiftlint:enable comma
func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable {
@@ -121,11 +123,13 @@ private struct _RowDecoder: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
- return R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T?
+ return try R.databaseDateDecodingStrategy.decodeIfPresent(
+ fromRow: row,
+ atUncheckedIndex: index) as! T?
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
- return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T?
+ return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
} else if let type = T.self as? DatabaseValueConvertible.Type {
- return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T?
+ return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
} else if row.impl.hasNull(atUncheckedIndex: index) {
return nil
} else {
@@ -151,11 +155,11 @@ private struct _RowDecoder: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
- return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T
+ return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
- return type.fastDecode(from: row, atUncheckedIndex: index) as! T
+ return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? DatabaseValueConvertible.Type {
- return type.decode(from: row, atUncheckedIndex: index) as! T
+ return try type.decode(fromRow: row, atUncheckedIndex: index) as! T
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
}
@@ -246,16 +250,8 @@ private struct _RowDecoder: Decoder {
// Prefer FetchableRecord decoding over Decodable.
return type.init(row: row) as! T
} else {
- do {
- let decoder = _RowDecoder(row: row, codingPath: codingPath)
- return try T(from: decoder)
- } catch let error as MissingColumnError {
- // Support for DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
- fatalConversionError(
- to: type,
- from: nil,
- conversionContext: ValueConversionContext(row).atColumn(error.column))
- }
+ let decoder = _RowDecoder(row: row, codingPath: codingPath)
+ return try T(from: decoder)
}
}
@@ -280,12 +276,7 @@ private struct _RowDecoder: Decoder {
return try T(from: columnDecoder)
} catch is JSONRequiredError {
// Decode from JSON
- guard let data = row.dataNoCopy(atIndex: index) else {
- fatalConversionError(
- to: T.self,
- from: row[index],
- conversionContext: ValueConversionContext(row).atColumn(index))
- }
+ let data = try row.decodeDataNoCopy(atIndex: index)
return try R
.databaseJSONDecoder(for: key.stringValue)
.decode(type.self, from: data)
@@ -375,30 +366,30 @@ extension ColumnDecoder: SingleValueDecodingContainer {
row.hasNull(atIndex: columnIndex)
}
- func decode(_ type: Bool.Type ) throws -> Bool { row[columnIndex] }
- func decode(_ type: Int.Type ) throws -> Int { row[columnIndex] }
- func decode(_ type: Int8.Type ) throws -> Int8 { row[columnIndex] }
- func decode(_ type: Int16.Type ) throws -> Int16 { row[columnIndex] }
- func decode(_ type: Int32.Type ) throws -> Int32 { row[columnIndex] }
- func decode(_ type: Int64.Type ) throws -> Int64 { row[columnIndex] }
- func decode(_ type: UInt.Type ) throws -> UInt { row[columnIndex] }
- func decode(_ type: UInt8.Type ) throws -> UInt8 { row[columnIndex] }
- func decode(_ type: UInt16.Type) throws -> UInt16 { row[columnIndex] }
- func decode(_ type: UInt32.Type) throws -> UInt32 { row[columnIndex] }
- func decode(_ type: UInt64.Type) throws -> UInt64 { row[columnIndex] }
- func decode(_ type: Float.Type ) throws -> Float { row[columnIndex] }
- func decode(_ type: Double.Type) throws -> Double { row[columnIndex] }
- func decode(_ type: String.Type) throws -> String { row[columnIndex] }
+ func decode(_ type: Bool.Type ) throws -> Bool { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Int.Type ) throws -> Int { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Int8.Type ) throws -> Int8 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Int16.Type ) throws -> Int16 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Int32.Type ) throws -> Int32 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Int64.Type ) throws -> Int64 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: UInt.Type ) throws -> UInt { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: UInt8.Type ) throws -> UInt8 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: UInt16.Type) throws -> UInt16 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: UInt32.Type) throws -> UInt32 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: UInt64.Type) throws -> UInt64 { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Float.Type ) throws -> Float { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: Double.Type) throws -> Double { try row.decode(atIndex: columnIndex) }
+ func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) }
func decode(_ type: T.Type) throws -> T where T: Decodable {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
- return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T
+ return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
- return type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T
+ return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? DatabaseValueConvertible.Type {
- return type.decode(from: row, atUncheckedIndex: columnIndex) as! T
+ return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else {
return try T(from: self)
}
@@ -408,11 +399,6 @@ extension ColumnDecoder: SingleValueDecodingContainer {
/// The error that triggers JSON decoding
private struct JSONRequiredError: Error { }
-/// The error for missing columns
-private struct MissingColumnError: Error {
- var column: String
-}
-
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
private var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -422,36 +408,49 @@ private var iso8601Formatter: ISO8601DateFormatter = {
extension DatabaseDateDecodingStrategy {
@inline(__always)
- fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? {
+ fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? {
if let sqliteStatement = row.sqliteStatement {
- return decodeIfPresent(
- sqliteStatement: sqliteStatement,
- index: Int32(index))
+ return try decodeIfPresent(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
- return decodeIfPresent(
- from: row[index],
- conversionContext: ValueConversionContext(row).atColumn(index))
+ return try decodeIfPresent(
+ fromDatabaseValue: row[index],
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
@inline(__always)
- fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date {
+ fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date {
if let sqliteStatement = row.sqliteStatement {
- return decode(
- sqliteStatement: sqliteStatement,
- index: Int32(index))
+ return try decode(
+ fromStatement: sqliteStatement,
+ atUncheckedIndex: Int32(index),
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
- return decode(
- from: row[index],
- conversionContext: ValueConversionContext(row).atColumn(index))
+ return try decode(
+ fromDatabaseValue: row[index],
+ context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
@inline(__always)
- fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date {
+ fileprivate func decode(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Date
+ {
switch self {
case .deferredToDate:
- return Date(sqliteStatement: sqliteStatement, index: index)
+ guard let date = Date(sqliteStatement: sqliteStatement, index: index) else {
+ throw RowDecodingError.valueMismatch(
+ Date.self,
+ context: context(),
+ databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
+ }
+ return date
case .timeIntervalSinceReferenceDate:
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
return Date(timeIntervalSinceReferenceDate: timeInterval)
@@ -465,7 +464,10 @@ extension DatabaseDateDecodingStrategy {
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let date = iso8601Formatter.date(from: string) else {
- fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
+ throw RowDecodingError.valueMismatch(
+ Date.self,
+ context: context(),
+ databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
}
return date
} else {
@@ -474,51 +476,62 @@ extension DatabaseDateDecodingStrategy {
case .formatted(let formatter):
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let date = formatter.date(from: string) else {
- fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
+ throw RowDecodingError.valueMismatch(
+ Date.self,
+ context: context(),
+ databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
}
return date
case .custom(let format):
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
guard let date = format(dbValue) else {
- fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
+ throw RowDecodingError.valueMismatch(
+ Date.self,
+ context: context(),
+ databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
}
return date
}
}
@inline(__always)
- fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? {
+ fileprivate func decodeIfPresent(
+ fromStatement sqliteStatement: SQLiteStatement,
+ atUncheckedIndex index: Int32,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Date?
+ {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
- return decode(sqliteStatement: sqliteStatement, index: index)
+ return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
@inline(__always)
fileprivate func decode(
- from dbValue: DatabaseValue,
- conversionContext: @autoclosure () -> ValueConversionContext?)
- -> Date
+ fromDatabaseValue dbValue: DatabaseValue,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Date
{
if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
- fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
+ throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
}
}
@inline(__always)
fileprivate func decodeIfPresent(
- from dbValue: DatabaseValue,
- conversionContext: @autoclosure () -> ValueConversionContext?)
- -> Date?
+ fromDatabaseValue dbValue: DatabaseValue,
+ context: @autoclosure () -> RowDecodingContext)
+ throws -> Date?
{
if dbValue.isNull {
return nil
} else if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
- fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
+ throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
}
}
diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift
index 64ecfd58b..25eeb027e 100644
--- a/GRDB/Utils/Utils.swift
+++ b/GRDB/Utils/Utils.swift
@@ -52,6 +52,11 @@ func GRDBPrecondition(
}
}
+@inlinable
+func fatalError(_ error: Error) -> Never {
+ try! { throw error }()
+}
+
// Workaround Swift inconvenience around factory methods of non-final classes
func cast(_ value: T) -> U? {
value as? U
diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj
index 64ebc63df..fe3bea6c9 100755
--- a/GRDBCustom.xcodeproj/project.pbxproj
+++ b/GRDBCustom.xcodeproj/project.pbxproj
@@ -56,6 +56,8 @@
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
+ 56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; };
+ 56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; };
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
@@ -152,8 +154,6 @@
56419C9B24A51D7F004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A8124A51614004967E1 /* PublisherExpectation.swift */; };
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
- 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; };
- 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; };
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
@@ -792,6 +792,7 @@
561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; };
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; };
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; };
+ 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; };
@@ -854,7 +855,6 @@
56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = ""; };
56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = ""; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; };
- 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; };
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; };
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; };
@@ -1762,12 +1762,12 @@
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
- 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
+ 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
@@ -2288,6 +2288,7 @@
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
+ 56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */,
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */,
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
@@ -2324,7 +2325,6 @@
568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */,
5657AB141D10899D006283EF /* URL.swift in Sources */,
56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */,
- 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */,
56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */,
F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */,
5656A8782295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
@@ -2646,6 +2646,7 @@
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
+ 56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */,
5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */,
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
@@ -2682,7 +2683,6 @@
568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */,
5657AB111D10899D006283EF /* URL.swift in Sources */,
56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */,
- 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */,
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */,
F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */,
5656A8772295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift
index 45166302f..b0bd21231 100644
--- a/Tests/GRDBTests/CompilationProtocolTests.swift
+++ b/Tests/GRDBTests/CompilationProtocolTests.swift
@@ -114,10 +114,18 @@ private class UserFetchableRecord2 : FetchableRecord {
// MARK: - StatementColumnConvertible
private struct UserStatementColumnConvertible1 : StatementColumnConvertible {
+ init?(sqliteStatement: SQLiteStatement, index: Int32) { }
+}
+
+private struct UserStatementColumnConvertible2 : StatementColumnConvertible {
init(sqliteStatement: SQLiteStatement, index: Int32) { }
}
-private class UserStatementColumnConvertible2 : StatementColumnConvertible {
+private class UserStatementColumnConvertible3 : StatementColumnConvertible {
+ required init?(sqliteStatement: SQLiteStatement, index: Int32) { }
+}
+
+private class UserStatementColumnConvertible4 : StatementColumnConvertible {
required init(sqliteStatement: SQLiteStatement, index: Int32) { }
}
diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift
index 3e98ce2e6..159a48a36 100644
--- a/Tests/GRDBTests/DataMemoryTests.swift
+++ b/Tests/GRDBTests/DataMemoryTests.swift
@@ -11,55 +11,85 @@ class DataMemoryTests: GRDBTestCase {
// https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue
let data = Data(repeating: 0xaa, count: 15)
- let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
- while let row = try rows.next() {
- let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
-
- do {
- // This data should be copied:
- let copiedData: Data = row[0]
- XCTAssertEqual(copiedData, data)
- copiedData.withUnsafeBytes {
- XCTAssertNotEqual($0.baseAddress, blobPointer)
- }
- }
-
- do {
- // This data should not be copied
- let nonCopiedData = row.dataNoCopy(atIndex: 0)!
- XCTAssertEqual(nonCopiedData, data)
- nonCopiedData.withUnsafeBytes {
- XCTAssertEqual($0.baseAddress, blobPointer)
- }
- }
- }
-
- let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
- let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
- switch dbValue.storage {
- case .blob(let data):
- data.withUnsafeBytes { buffer in
+ do {
+ let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
+ while let row = try rows.next() {
+ let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
+
do {
- // This data should not be copied:
- let nonCopiedData: Data = row[0]
- XCTAssertEqual(nonCopiedData, data)
- nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
- XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress
- )
+ // This data should be copied:
+ let copiedData: Data = row[0]
+ XCTAssertEqual(copiedData, data)
+ copiedData.withUnsafeBytes {
+ XCTAssertNotEqual($0.baseAddress, blobPointer)
}
}
do {
- // This data should not be copied:
+ // This data should not be copied
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
XCTAssertEqual(nonCopiedData, data)
- nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
- XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
+ nonCopiedData.withUnsafeBytes {
+ XCTAssertEqual($0.baseAddress, blobPointer)
}
}
}
- default:
- XCTFail("Not a blob")
+ }
+
+ do {
+ let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)])
+ let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data], adapter: adapter)
+ while let row = try rows.next() {
+ let blobPointer = sqlite3_column_blob(row.unadapted.sqliteStatement, 0)
+ let nestedRow = row.scopes["nested"]!
+
+ do {
+ // This data should be copied:
+ let copiedData: Data = nestedRow[0]
+ XCTAssertEqual(copiedData, data)
+ copiedData.withUnsafeBytes {
+ XCTAssertNotEqual($0.baseAddress, blobPointer)
+ }
+ }
+
+ do {
+ // This data should not be copied
+ let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)!
+ XCTAssertEqual(nonCopiedData, data)
+ nonCopiedData.withUnsafeBytes {
+ XCTAssertEqual($0.baseAddress, blobPointer)
+ }
+ }
+ }
+ }
+
+ do {
+ let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
+ let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
+ switch dbValue.storage {
+ case .blob(let data):
+ data.withUnsafeBytes { buffer in
+ do {
+ // This data should not be copied:
+ let nonCopiedData: Data = row[0]
+ XCTAssertEqual(nonCopiedData, data)
+ nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
+ XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
+ }
+ }
+
+ do {
+ // This data should not be copied:
+ let nonCopiedData = row.dataNoCopy(atIndex: 0)!
+ XCTAssertEqual(nonCopiedData, data)
+ nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
+ XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
+ }
+ }
+ }
+ default:
+ XCTFail("Not a blob")
+ }
}
}
}
diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift
index 30ccd6d47..b390ee7b7 100644
--- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift
+++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift
@@ -39,7 +39,10 @@ private enum StrategyFormatted: StrategyProvider {
}
private enum StrategyCustom: StrategyProvider {
- static let strategy: DatabaseDateDecodingStrategy = .custom { _ in
+ static let strategy: DatabaseDateDecodingStrategy = .custom { dbValue in
+ if dbValue == "invalid".databaseValue {
+ return nil
+ }
return Date(timeIntervalSinceReferenceDate: 123456)
}
}
@@ -187,6 +190,28 @@ extension DatabaseDateDecodingStrategyTests {
XCTAssertEqual(calendar.component(.second, from: date), 3)
XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal.
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "Yesterday") { date in
+// XCTFail("Unexpected Date")
+// }
+// } catch let error as RowDecodingError {
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"], \
+// sql: `SELECT ? AS date`, \
+// arguments: ["Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -208,6 +233,30 @@ extension DatabaseDateDecodingStrategyTests {
try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 123.456) { date in
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456))
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: "Yesterday") { date in
+// // Decoding from SQLite statement works:
+// // "Yesterday" is decoded as 0.
+// XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0))
+// }
+// } catch let error as RowDecodingError {
+// // Decoding from DatabaseValue does not work:
+// // "Yesterday" is not decoded as 0.
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -229,6 +278,30 @@ extension DatabaseDateDecodingStrategyTests {
try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 123.456) { date in
XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456))
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: "Yesterday") { date in
+// // Decoding from SQLite statement works:
+// // "Yesterday" is decoded as 0.
+// XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
+// }
+// } catch let error as RowDecodingError {
+// // Decoding from DatabaseValue does not work:
+// // "Yesterday" is not decoded as 0.
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -260,6 +333,30 @@ extension DatabaseDateDecodingStrategyTests {
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456.789) { date in
XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000))
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: "Yesterday") { date in
+// // Decoding from SQLite statement works:
+// // "Yesterday" is decoded as 0.
+// XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
+// }
+// } catch let error as RowDecodingError {
+// // Decoding from DatabaseValue does not work:
+// // "Yesterday" is not decoded as 0.
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -287,6 +384,28 @@ extension DatabaseDateDecodingStrategyTests {
XCTAssertEqual(calendar.component(.second, from: date), 7)
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyIso8601.self, databaseValue: "Yesterday") { date in
+// XCTFail("Unexpected Date")
+// }
+// } catch let error as RowDecodingError {
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"], \
+// sql: `SELECT ? AS date`, \
+// arguments: ["Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -313,6 +432,28 @@ extension DatabaseDateDecodingStrategyTests {
XCTAssertEqual(calendar.component(.second, from: date), 55)
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyFormatted.self, databaseValue: "Yesterday") { date in
+// XCTFail("Unexpected Date")
+// }
+// } catch let error as RowDecodingError {
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "Yesterday" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"Yesterday"], \
+// sql: `SELECT ? AS date`, \
+// arguments: ["Yesterday"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
@@ -326,9 +467,31 @@ extension DatabaseDateDecodingStrategyTests {
try testNullDecoding(db, strategy: StrategyCustom.self)
// Date
- try test(db, strategy: StrategyCustom.self, databaseValue: "whatever") { date in
+ try test(db, strategy: StrategyCustom.self, databaseValue: "valid") { date in
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456))
}
+
+ // TODO GRDB6: uncomment test
+// // error
+// do {
+// try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { date in
+// XCTFail("Unexpected Date")
+// }
+// } catch let error as RowDecodingError {
+// switch error {
+// case .valueMismatch:
+// XCTAssertEqual(error.description, """
+// could not decode Date from database value "invalid" - \
+// column: "date", \
+// column index: 0, \
+// row: [date:"invalid"], \
+// sql: `SELECT ? AS date`, \
+// arguments: ["invalid"]
+// """)
+// default:
+// XCTFail("Unexpected Error")
+// }
+// }
}
}
}
diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift
index 4fcb85eaa..aede3116f 100644
--- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift
+++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift
@@ -1,15 +1,13 @@
import XCTest
@testable import GRDB
-// Those tests are tightly coupled to GRDB decoding code.
-// Each test comes with the (commented) crashing code snippets that trigger it.
class DatabaseValueConversionErrorTests: GRDBTestCase {
func testFetchableRecord1() throws {
- struct Record: FetchableRecord {
+ struct Record /* TODO GRDB6: FetchableRecord */ {
var name: String
-
- init(row: Row) {
- name = row["name"]
+
+ init(row: Row) throws {
+ name = try row.decode(forKey: "name")
}
}
@@ -19,25 +17,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS name")
statement.arguments = [nil]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try Record(row: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL], sql: `SELECT ? AS name`, arguments: [NULL])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Record(row: $0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil])
+ XCTAssertEqual(context.sql, "SELECT ? AS name")
+ XCTAssertEqual(context.statementArguments, [nil])
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL], \
+ sql: `SELECT ? AS name`, \
+ arguments: [NULL]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
@@ -45,38 +71,65 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not read String from missing column `name` (row: [unused:\"ignored\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try Record(row: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("name"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ column not found: "name" - \
+ row: [unused:"ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not read String from missing column `name` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Record(row: $0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("name"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, "SELECT ? AS unused")
+ XCTAssertEqual(context.statementArguments, ["ignored"])
+ XCTAssertEqual(error.description, """
+ column not found: "name" - \
+ row: [unused:"ignored"], \
+ sql: `SELECT ? AS unused`, \
+ arguments: ["ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
}
func testFetchableRecord2() throws {
- enum Value: String, DatabaseValueConvertible, Decodable {
+ enum Value: String, DatabaseValueConvertible {
case valid
}
- struct Record: FetchableRecord {
+ struct Record /* TODO GRDB6: FetchableRecord */ {
var value: Value
-
- init(row: Row) {
- value = row["value"]
+
+ init(row: Row) throws {
+ value = try row.decode(forKey: "value")
}
}
@@ -86,24 +139,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT 1, ? AS value")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [1:1 value:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try Record(row: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(1))
+ XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "value", \
+ column index: 1, \
+ row: [1:1 value:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [1:1 value:\"invalid\"], sql: `SELECT 1, ? AS value`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Record(row: $0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(1))
+ XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT 1, ? AS value")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "value", \
+ column index: 1, \
+ row: [1:1 value:"invalid"], \
+ sql: `SELECT 1, ? AS value`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
@@ -111,28 +193,55 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try Record(row: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Record(row: $0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, "SELECT ? AS unused")
+ XCTAssertEqual(context.statementArguments, ["ignored"])
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"], \
+ sql: `SELECT ? AS unused`, \
+ arguments: ["ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
}
-
+
func testDecodableFetchableRecord1() throws {
struct Record: Decodable, FetchableRecord {
var name: String
@@ -145,25 +254,55 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS team`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
@@ -171,24 +310,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
- let row = try Row.fetchOne(statement)!
-
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not read String from missing column `name` (row: [unused:\"ignored\"])")
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not read String from missing column `name` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("name"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ column not found: "name" - \
+ row: [unused:"ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
+
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("name"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, "SELECT ? AS unused")
+ XCTAssertEqual(context.statementArguments, ["ignored"])
+ XCTAssertEqual(error.description, """
+ column not found: "name" - \
+ row: [unused:"ignored"], \
+ sql: `SELECT ? AS unused`, \
+ arguments: ["ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
}
@@ -201,31 +369,62 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
struct Record: Decodable, FetchableRecord {
var value: Value
}
-
+
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(1))
+ XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "value", \
+ column index: 1, \
+ row: [name:NULL value:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"], sql: `SELECT NULL AS name, ? AS value`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(1))
+ XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS value")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "value", \
+ column index: 1, \
+ row: [name:NULL value:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS value`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
@@ -233,24 +432,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
- let row = try Row.fetchOne(statement)!
-
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])")
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
+
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, "SELECT ? AS unused")
+ XCTAssertEqual(context.statementArguments, ["ignored"])
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"], \
+ sql: `SELECT ? AS unused`, \
+ arguments: ["ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
}
@@ -270,26 +498,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as DecodingError {
+ switch error {
+ case .dataCorrupted:
+ break
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"], sql: `SELECT NULL AS name, ? AS value`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS team`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ } catch let error as DecodingError {
+ switch error {
+ case .dataCorrupted:
+ break
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
@@ -297,111 +552,234 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
- let row = try Row.fetchOne(statement)!
-
- // _ = Record(row: row)
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])")
- // _ = try Record.fetchOne(statement)
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["value"],
- conversionContext: ValueConversionContext(row).atColumn("value")),
- "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ // TODO GRDB6: _ = try Record(row: row)
+ _ = try RowDecoder().decode(Record.self, from: row)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
+
+ do {
+ // TODO GRDB6: _ = try Record.fetchOne(statement)
+ let rows = try Row.fetchCursor(statement)
+ while let row = try rows.next() {
+ _ = try RowDecoder().decode(Record.self, from: row)
+ }
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("value"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["unused": "ignored"])
+ XCTAssertEqual(context.sql, "SELECT ? AS unused")
+ XCTAssertEqual(context.statementArguments, ["ignored"])
+ XCTAssertEqual(error.description, """
+ column not found: "value" - \
+ row: [unused:"ignored"], \
+ sql: `SELECT ? AS unused`, \
+ arguments: ["ignored"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
}
}
func testStatementColumnConvertible1() throws {
- // Those tests are tightly coupled to GRDB decoding code.
- // Each test comes with one or several commented crashing code snippets that trigger it.
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b
- // _ = try String.fetchAll(statement)
- try statement.makeCursor().forEach {
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: .null,
- conversionContext: ValueConversionContext(statement).atColumn(0)),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try String.fetchAll(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try String.fastDecode(fromRow: $0, atUncheckedIndex: 0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS team`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
- // _ = row["name"] as String
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(String.self, forKey: "name")
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = row[0] as String
- XCTAssertEqual(
- conversionErrorMessage(
- to: String.self,
- from: row[0],
- conversionContext: ValueConversionContext(row).atColumn(0)),
- "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(String.self, atIndex: 0)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode String from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
}
}
func testStatementColumnConvertible2() throws {
- // Those tests are tightly coupled to GRDB decoding code.
- // Each test comes with one or several commented crashing code snippets that trigger it.
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT ? AS foo")
statement.arguments = [1000]
- let row = try Row.fetchOne(statement)!
- // _ = try Row.fetchCursor(statement).map { $0["missing"] as Int8 }.next()
- try Row.fetchCursor(statement).forEach { row in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Int8.self,
- from: nil,
- conversionContext: ValueConversionContext(row).atColumn("missing")),
- "could not read Int8 from missing column `missing` (row: [foo:1000], sql: `SELECT ? AS foo`, arguments: [1000])")
+ do {
+ _ = try Row.fetchCursor(statement)
+ .map { try $0.decode(Int8.self, forKey: "missing") }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .keyNotFound(key, context):
+ XCTAssertEqual(key, .columnName("missing"))
+ XCTAssertEqual(context.key, nil)
+ XCTAssertEqual(context.row, ["foo": 1000])
+ XCTAssertEqual(context.sql, "SELECT ? AS foo")
+ XCTAssertEqual(context.statementArguments, [1000])
+ XCTAssertEqual(error.description, """
+ column not found: "missing" - \
+ row: [foo:1000], \
+ sql: `SELECT ? AS foo`, \
+ arguments: [1000]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
- // _ = try Int8.fetchAll(statement)
- try statement.makeCursor().forEach {
- let sqliteStatement = statement.sqliteStatement
- XCTAssertEqual(
- conversionErrorMessage(
- to: Int8.self,
- from: DatabaseValue(sqliteStatement: sqliteStatement, index: 0),
- conversionContext: ValueConversionContext(Row(sqliteStatement: sqliteStatement)).atColumn(0)),
- "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000], sql: `SELECT ? AS foo`)")
+ do {
+ // TODO GRDB6: _ = try Int8.fetchAll(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Int8.fastDecode(fromRow: $0, atUncheckedIndex: 0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["foo": 1000])
+ XCTAssertEqual(context.sql, "SELECT ? AS foo")
+ XCTAssertEqual(context.statementArguments, [1000])
+ XCTAssertEqual(error.description, """
+ could not decode Int8 from database value 1000 - \
+ column: "foo", \
+ column index: 0, \
+ row: [foo:1000], \
+ sql: `SELECT ? AS foo`, \
+ arguments: [1000]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
- // _ = row["foo"] as Int8
- XCTAssertEqual(
- conversionErrorMessage(
- to: Int8.self,
- from: row["foo"],
- conversionContext: ValueConversionContext(row).atColumn("foo")),
- "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(Int8.self, forKey: "foo")
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["foo": 1000])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode Int8 from database value 1000 - \
+ column: "foo", \
+ column index: 0, \
+ row: [foo:1000]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = row[0] as Int8
- XCTAssertEqual(
- conversionErrorMessage(
- to: Int8.self,
- from: row[0],
- conversionContext: ValueConversionContext(row).atColumn(0)),
- "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(Int8.self, atIndex: 0)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["foo": 1000])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode Int8 from database value 1000 - \
+ column: "foo", \
+ column index: 0, \
+ row: [foo:1000]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
}
}
@@ -410,51 +788,128 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
case valid
}
- // Those tests are tightly coupled to GRDB decoding code.
- // Each test comes with one or several commented crashing code snippets that trigger it.
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
- let row = try Row.fetchOne(statement)!
- // _ = try Value.fetchAll(statement)
- try statement.makeCursor().forEach {
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0),
- conversionContext: ValueConversionContext(statement).atColumn(0)),
- "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Value.fetchAll(statement)
+ _ = try Row.fetchCursor(statement)
+ .map { try Value.decode(fromRow: $0, atUncheckedIndex: 0) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS team`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
- // _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))
- let adapter = SuffixRowAdapter(fromIndex: 1)
- let columnIndex = try adapter.baseColumnIndex(atIndex: 0, layout: statement)
- try statement.makeCursor().forEach { _ in
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(columnIndex)),
- conversionContext: ValueConversionContext(statement).atColumn(columnIndex)),
- "could not convert database value \"invalid\" to \(Value.self) (column: `team`, column index: 1, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])")
+ do {
+ // TODO GRDB6: _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))
+ _ = try Row.fetchCursor(statement)
+ .map { try Value.decode(fromRow: $0, atUncheckedIndex: 1) }
+ .next()
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(1))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
+ XCTAssertEqual(context.statementArguments, ["invalid"])
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "team", \
+ column index: 1, \
+ row: [name:NULL team:"invalid"], \
+ sql: `SELECT NULL AS name, ? AS team`, \
+ arguments: ["invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
}
- // _ = row["name"] as Value
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row["name"],
- conversionContext: ValueConversionContext(row).atColumn("name")),
- "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(Value.self, forKey: "name")
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
- // _ = row[0] as Value
- XCTAssertEqual(
- conversionErrorMessage(
- to: Value.self,
- from: row[0],
- conversionContext: ValueConversionContext(row).atColumn(0)),
- "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])")
+ do {
+ let row = try Row.fetchOne(statement)!
+ _ = try row.decode(Value.self, atIndex: 0)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value NULL - \
+ column: "name", \
+ column index: 0, \
+ row: [name:NULL team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
+
+ do {
+ let row = try Row.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))!
+ _ = try row.decode(Value.self, atIndex: 0)
+ XCTFail("Expected error")
+ } catch let error as RowDecodingError {
+ switch error {
+ case let .valueMismatch(_, context):
+ XCTAssertEqual(context.key, .columnIndex(0))
+ XCTAssertEqual(context.row, ["team": "invalid"])
+ XCTAssertEqual(context.sql, nil)
+ XCTAssertEqual(context.statementArguments, nil)
+ XCTAssertEqual(error.description, """
+ could not decode \(Value.self) from database value "invalid" - \
+ column: "team", \
+ column index: 0, \
+ row: [team:"invalid"]
+ """)
+ default:
+ XCTFail("Unexpected Error")
+ }
+ }
}
}
}
diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift
index c105cd726..2555a1c44 100644
--- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift
+++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift
@@ -1,6 +1,7 @@
import XCTest
import GRDB
+#warning("TODO: test decoding error")
// A type that adopts DatabaseValueConvertible and StatementColumnConvertible
private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Hashable {
let int: Int
@@ -67,6 +68,42 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
}
+
+ func testScopedRowExtraction() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.inDatabase { db in
+ let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)])
+ var rows = try Row.fetchCursor(db, sql: "SELECT NULL", adapter: adapter)
+ while let row = try rows.next() {
+ let one: Fetched? = row.scopes["nested"]![0]
+ XCTAssertTrue(one == nil)
+ }
+ rows = try Row.fetchCursor(db, sql: "SELECT 1", adapter: adapter)
+ while let row = try rows.next() {
+ let one: Fetched? = row.scopes["nested"]![0]
+ XCTAssertEqual(one!.int, 1)
+ XCTAssertEqual(one!.fast, true)
+ }
+ rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int", adapter: adapter)
+ while let row = try rows.next() {
+ let one: Fetched? = row.scopes["nested"]!["int"]
+ XCTAssertEqual(one!.int, 1)
+ XCTAssertEqual(one!.fast, true)
+ }
+ rows = try Row.fetchCursor(db, sql: "SELECT 1", adapter: adapter)
+ while let row = try rows.next() {
+ let one: Fetched = row.scopes["nested"]![0]
+ XCTAssertEqual(one.int, 1)
+ XCTAssertEqual(one.fast, true)
+ }
+ rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int", adapter: adapter)
+ while let row = try rows.next() {
+ let one: Fetched = row.scopes["nested"]!["int"]
+ XCTAssertEqual(one.int, 1)
+ XCTAssertEqual(one.fast, true)
+ }
+ }
+ }
// MARK: - StatementColumnConvertible.fetch