From d03b76b7e7a7960155eda261d1bea0053454cb33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 19:49:53 +0200 Subject: [PATCH 01/36] DatabaseDateDecodingStrategy --- GRDB/Record/FetchableRecord+Decodable.swift | 43 +++- GRDB/Record/FetchableRecord.swift | 210 ++++++++++++++++---- 2 files changed, 210 insertions(+), 43 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 9cb05eef4..19eb6689d 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -68,14 +68,16 @@ private struct RowDecoder: Decoder { if let index = row.index(ofColumn: keyName) { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. - if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + if type == Date.self { + return decodeDateIfPresent(fromRow: row, columnAtIndex: index, key: key) as! T? + } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? DatabaseValueConvertible.Type { return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T? } else if row.impl.hasNull(atUncheckedIndex: index) { return nil } else { - return try decode(type, fromColumnAtIndex: index, key: key) + return try decode(type, fromRow: row, columnAtIndex: index, key: key) } } @@ -96,12 +98,14 @@ private struct RowDecoder: Decoder { if let index = row.index(ofColumn: keyName) { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. - if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + if type == Date.self { + return decodeDate(fromRow: row, columnAtIndex: index, key: key) as! T + } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { return type.fastDecode(from: row, atUncheckedIndex: index) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { return type.decode(from: row, atUncheckedIndex: index) as! T } else { - return try decode(type, fromColumnAtIndex: index, key: key) + return try decode(type, fromRow: row, columnAtIndex: index, key: key) } } @@ -164,6 +168,34 @@ private struct RowDecoder: Decoder { // Helper methods + @inline(__always) + private func decodeDateIfPresent(fromRow row: Row, columnAtIndex index: Int, key: Key) -> Date? { + if let sqliteStatement = row.sqliteStatement { + return Record.databaseDateDecodingStrategy.decodeIfPresent( + sqliteStatement: sqliteStatement, + index: Int32(index), + conversionContext: ValueConversionContext(row).atColumn(index)) + } else { + return Record.databaseDateDecodingStrategy.decodeIfPresent( + from: row[index], + conversionContext: ValueConversionContext(row).atColumn(index)) + } + } + + @inline(__always) + private func decodeDate(fromRow row: Row, columnAtIndex index: Int, key: Key) -> Date { + if let sqliteStatement = row.sqliteStatement { + return Record.databaseDateDecodingStrategy.decode( + sqliteStatement: sqliteStatement, + index: Int32(index), + conversionContext: ValueConversionContext(row).atColumn(index)) + } else { + return Record.databaseDateDecodingStrategy.decode( + from: row[index], + conversionContext: ValueConversionContext(row).atColumn(index)) + } + } + @inline(__always) private func decode(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable { if let type = T.self as? FetchableRecord.Type { @@ -176,8 +208,7 @@ private struct RowDecoder: Decoder { } @inline(__always) - private func decode(_ type: T.Type, fromColumnAtIndex index: Int, key: Key) throws -> T where T: Decodable { - let row = decoder.row + private func decode(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable { do { // This decoding will fail for types that decode from keyed // or unkeyed containers, because we're decoding a single diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index bd8e313e5..cb73a3e16 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -95,6 +95,10 @@ public protocol FetchableRecord { /// } /// } static func databaseJSONDecoder(for column: String) -> JSONDecoder + + /// When the FetchableRecord type also adopts the standard Decodable + /// protocol, this property controls the decoding of date properties. + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } } extension FetchableRecord { @@ -114,44 +118,9 @@ extension FetchableRecord { decoder.nonConformingFloatDecodingStrategy = .throw return decoder } -} - -/// A cursor of records. For example: -/// -/// struct Player : FetchableRecord { ... } -/// try dbQueue.read { db in -/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM player") -/// } -public final class RecordCursor : Cursor { - private let statement: SelectStatement - private let row: Row // Reused for performance - private let sqliteStatement: SQLiteStatement - private var done = false - init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - self.statement = statement - self.row = try Row(statement: statement).adapted(with: adapter, layout: statement) - self.sqliteStatement = statement.sqliteStatement - statement.reset(withArguments: arguments) - } - - /// :nodoc: - public func next() throws -> Record? { - if done { - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - } - switch sqlite3_step(sqliteStatement) { - case SQLITE_DONE: - done = true - return nil - case SQLITE_ROW: - return Record(row: row) - case let code: - statement.database.selectStatementDidFail(statement) - throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) - } + public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { + return .deferredToDate } } @@ -329,6 +298,8 @@ extension FetchableRecord { } } +// MARK: - FetchRequest + extension FetchRequest where RowDecoder: FetchableRecord { // MARK: Fetching Records @@ -377,3 +348,168 @@ extension FetchRequest where RowDecoder: FetchableRecord { return try RowDecoder.fetchOne(db, self) } } + +// MARK: - RecordCursor + +/// A cursor of records. For example: +/// +/// struct Player : FetchableRecord { ... } +/// try dbQueue.read { db in +/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM player") +/// } +public final class RecordCursor : Cursor { + private let statement: SelectStatement + private let row: Row // Reused for performance + private let sqliteStatement: SQLiteStatement + private var done = false + + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + self.statement = statement + self.row = try Row(statement: statement).adapted(with: adapter, layout: statement) + self.sqliteStatement = statement.sqliteStatement + statement.reset(withArguments: arguments) + } + + /// :nodoc: + public func next() throws -> Record? { + if done { + // make sure this instance never yields a value again, even if the + // statement is reset by another cursor. + return nil + } + switch sqlite3_step(sqliteStatement) { + case SQLITE_DONE: + done = true + return nil + case SQLITE_ROW: + return Record(row: row) + case let code: + statement.database.selectStatementDidFail(statement) + throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) + } + } +} + +// MARK: - DateDatabaseDecodingStrategy + +/// The strategies available for formatting dates when decoding them from a +/// database column. +public enum DatabaseDateDecodingStrategy { + /// The strategy that uses formatting from the Date structure. + /// + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#date-and-datecomponents + /// for details. + case deferredToDate + case timeIntervalSinceReferenceDate + case timeIntervalSince1970 + case millisecondsSince1970 + @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) + case iso8601(ISO8601DateFormatter) + case formatted(DateFormatter) + case custom((DatabaseValue) -> Date?) +} + +extension DatabaseDateDecodingStrategy { + @inline(__always) + func decode(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + switch self { + case .deferredToDate: + return Date(sqliteStatement: sqliteStatement, index: index) + case .timeIntervalSinceReferenceDate: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSinceReferenceDate: timeInterval) + case .timeIntervalSince1970: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSince1970: timeInterval) + case .millisecondsSince1970: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSince1970: timeInterval / 1000.0) + case .iso8601(let formatter): + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = formatter.date(from: string) else { + fatalConversionError( + to: Date.self, + from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), + conversionContext: conversionContext()) + } + return date + case .formatted(let formatter): + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = formatter.date(from: string) else { + fatalConversionError( + to: Date.self, + from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), + conversionContext: conversionContext()) + } + return date + case .custom(let format): + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + guard let date = format(dbValue) else { + fatalConversionError( + to: Date.self, + from: dbValue, + conversionContext: conversionContext()) + } + return date + } + } + + @inline(__always) + func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + return decode(sqliteStatement:sqliteStatement, index:index, conversionContext: conversionContext) + } + + @inline(__always) + func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + if let date = dateFromDatabaseValue(dbValue) { + return date + } else { + fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + } + } + + @inline(__always) + func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + if dbValue.isNull { + return nil + } else if let date = dateFromDatabaseValue(dbValue) { + return date + } else { + fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + } + } + + // Returns nil if decoding fails + @inline(__always) + private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? { + switch self { + case .deferredToDate: + return Date.fromDatabaseValue(dbValue) + case .timeIntervalSinceReferenceDate: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSinceReferenceDate: $0) } + case .timeIntervalSince1970: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSince1970: $0) } + case .millisecondsSince1970: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSince1970: $0 / 1000.0) } + case .iso8601(let formatter): + return String + .fromDatabaseValue(dbValue) + .flatMap { formatter.date(from: $0) } + case .formatted(let formatter): + return String + .fromDatabaseValue(dbValue) + .flatMap { formatter.date(from: $0) } + case .custom(let format): + return format(dbValue) + } + } +} From fc914470f551217ea9c126018548ff7afcba7844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 19:51:09 +0200 Subject: [PATCH 02/36] DatabaseDateDecodingStrategy tests --- GRDB.xcodeproj/project.pbxproj | 6 + GRDBCipher.xcodeproj/project.pbxproj | 10 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../DatabaseDateDecodingStrategyTests.swift | 342 ++++++++++++++++++ 4 files changed, 364 insertions(+) create mode 100644 Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b518661a9..53e9326c8 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -301,6 +301,8 @@ 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; 5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; }; 5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; }; + 5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; @@ -929,6 +931,7 @@ 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; + 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1479,6 +1482,7 @@ 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( + 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */, 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); @@ -2603,6 +2607,7 @@ 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */, 563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */, + 5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, @@ -2765,6 +2770,7 @@ 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */, 56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */, 562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */, 56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */, 5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 29826951b..395b10643 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -341,6 +341,10 @@ 5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; }; 5665F86E203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; }; 5665F86F203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; }; + 5665FA222129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA232129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA242129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA252129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; }; 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; }; 566A843020413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; @@ -1019,6 +1023,7 @@ 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; + 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1541,6 +1546,7 @@ 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( + 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */, 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); @@ -2291,6 +2297,7 @@ 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */, 567DAF361EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5665FA222129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */, 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */, @@ -2453,6 +2460,7 @@ 56176C671EACCCC8000F3F2B /* FTS5RecordTests.swift in Sources */, 567DAF371EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 567156351CB16729007DC145 /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5665FA232129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 567156361CB16729007DC145 /* RowFromStatementTests.swift in Sources */, 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, @@ -2727,6 +2735,7 @@ 56176C731EACCCCA000F3F2B /* FTS5RecordTests.swift in Sources */, 567DAF3A1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, + 5665FA242129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, 566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */, 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */, @@ -2889,6 +2898,7 @@ 56176C791EACCCCB000F3F2B /* FTS5RecordTests.swift in Sources */, 567DAF3B1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 56AFCA9F1CB1ABC800F48B96 /* RecordPrimaryKeyMultipleTests.swift in Sources */, + 5665FA252129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */, 5690C32C1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 0ff2908eb..488f477cb 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -145,6 +145,8 @@ 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; }; 5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; }; + 5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; @@ -689,6 +691,7 @@ 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; + 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1185,6 +1188,7 @@ 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( + 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */, 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); @@ -1964,6 +1968,7 @@ 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, + 5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5657AB451D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, @@ -2238,6 +2243,7 @@ F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, + 5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, 5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */, 5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift new file mode 100644 index 000000000..428a793d1 --- /dev/null +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -0,0 +1,342 @@ +import Foundation +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private protocol StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy { get } +} + +private enum StrategyDeferredToDate: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .deferredToDate +} + +private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .timeIntervalSinceReferenceDate +} + +private enum StrategyTimeIntervalSince1970: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 +} + +private enum StrategyMillisecondsSince1970: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970 +} + +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +private enum StrategyIso8601Strategy: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .iso8601({ + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }()) +} + +private enum StrategyFormatted: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .formatted({ + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0)! + formatter.dateStyle = .full + formatter.timeStyle = .full + return formatter + }()) +} + +private enum StrategyCustom: StrategyProvider { + static var strategy: DatabaseDateDecodingStrategy = .custom { _ in + return Date(timeIntervalSinceReferenceDate: 123456) + } +} + +private struct RecordWithDate: FetchableRecord, Decodable { + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy } + var date: Date +} + +private struct RecordWithOptionalDate: FetchableRecord, Decodable { + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy } + var date: Date? +} + +class DatabaseDateDecodingStrategyTests: GRDBTestCase { + /// test the conversion from a database value to a date extracted from a record + private func test( + _ db: Database, + record: T.Type, + date: (T) -> Date?, + databaseValue: DatabaseValueConvertible?, + with test: (Date?) -> Void) throws + { + let request = SQLRequest("SELECT ? AS date", arguments: [databaseValue]) + do { + // test decoding straight from SQLite + let record = try T.fetchOne(db, request)! + test(date(record)) + } + do { + // test decoding from copied row + let record = try T(row: Row.fetchOne(db, request)!) + test(date(record)) + } + } + + /// test the conversion from a database value to a date with a given strategy + private func test(_ db: Database, strategy: Strategy.Type, databaseValue: DatabaseValueConvertible, _ test: (Date) -> Void) throws { + try self.test(db, record: RecordWithDate.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) }) + try self.test(db, record: RecordWithOptionalDate.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) }) + } + + private func testNullDecoding(_ db: Database, strategy: Strategy.Type) throws { + try self.test(db, record: RecordWithOptionalDate.self, date: { $0.date }, databaseValue: nil) { date in + XCTAssertNil(date) + } + } +} + +// MARK: - deferredToDate + +extension DatabaseDateDecodingStrategyTests { + func testDeferredToDate() throws { + try makeDatabaseQueue().read { db in + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + + // Null + try testNullDecoding(db, strategy: StrategyDeferredToDate.self) + + // YMD + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 0) + XCTAssertEqual(calendar.component(.minute, from: date), 0) + XCTAssertEqual(calendar.component(.second, from: date), 0) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // YMD_HM + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + XCTAssertEqual(calendar.component(.second, from: date), 0) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // YMD_HMS + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02:03") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + XCTAssertEqual(calendar.component(.second, from: date), 3) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // YMD_HMSS + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02:03.00456") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + 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. + } + + // Timestamp + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: 1437526920) { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + XCTAssertEqual(calendar.component(.second, from: date), 0) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // Iso8601YMD_HM + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + XCTAssertEqual(calendar.component(.second, from: date), 0) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // Iso8601YMD_HMS + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02:03") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + XCTAssertEqual(calendar.component(.second, from: date), 3) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + + // Iso8601YMD_HMSS + try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02:03.00456") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2015) + XCTAssertEqual(calendar.component(.month, from: date), 7) + XCTAssertEqual(calendar.component(.day, from: date), 22) + XCTAssertEqual(calendar.component(.hour, from: date), 1) + XCTAssertEqual(calendar.component(.minute, from: date), 2) + 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. + } + } + } +} + +// MARK: - timeIntervalSinceReferenceDate + +extension DatabaseDateDecodingStrategyTests { + func testTimeIntervalSinceReferenceDate() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyTimeIntervalSinceReferenceDate.self) + + // 0 + try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 0) { date in + XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0)) + } + + // 123.456 + try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 123.456) { date in + XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456)) + } + } + } +} + +// MARK: - timeIntervalSince1970 + +extension DatabaseDateDecodingStrategyTests { + func testTimeIntervalSince1970() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyTimeIntervalSince1970.self) + + // 0 + try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 0) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) + } + + // 123.456 + try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 123.456) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456)) + } + } + } +} + +// MARK: - millisecondsSince1970 + +extension DatabaseDateDecodingStrategyTests { + func testMillisecondsSince1970() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyMillisecondsSince1970.self) + + // 0 + try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 0) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) + } + + // 123.456 + try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123.456) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456 / 1000 )) + } + + // 123456 + try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.0 / 1000)) + } + + // 123456.789 + try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456.789) { date in + XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000)) + } + } + } +} + +// MARK: - iso8601(ISO8601DateFormatter) + +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +extension DatabaseDateDecodingStrategyTests { + func testIso8601() throws { + try makeDatabaseQueue().read { db in + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + + // Null + try testNullDecoding(db, strategy: StrategyIso8601Strategy.self) + + // Date + try test(db, strategy: StrategyIso8601Strategy.self, databaseValue: "2018-08-19T17:18:07Z") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2018) + XCTAssertEqual(calendar.component(.month, from: date), 8) + XCTAssertEqual(calendar.component(.day, from: date), 19) + XCTAssertEqual(calendar.component(.hour, from: date), 17) + XCTAssertEqual(calendar.component(.minute, from: date), 18) + XCTAssertEqual(calendar.component(.second, from: date), 7) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + } + } +} + +// MARK: - formatted(DateFormatter) + +extension DatabaseDateDecodingStrategyTests { + func testFormatted() throws { + try makeDatabaseQueue().read { db in + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + + // Null + try testNullDecoding(db, strategy: StrategyFormatted.self) + + // Date + try test(db, strategy: StrategyFormatted.self, databaseValue: "Sunday, August 19, 2018 at 5:21:55 PM Greenwich Mean Time") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2018) + XCTAssertEqual(calendar.component(.month, from: date), 8) + XCTAssertEqual(calendar.component(.day, from: date), 19) + XCTAssertEqual(calendar.component(.hour, from: date), 17) + XCTAssertEqual(calendar.component(.minute, from: date), 21) + XCTAssertEqual(calendar.component(.second, from: date), 55) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } + } + } +} + +// MARK: - custom((DatabaseValue) -> Date? + +extension DatabaseDateDecodingStrategyTests { + func testCustom() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyCustom.self) + + // Date + try test(db, strategy: StrategyCustom.self, databaseValue: "whatever") { date in + XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456)) + } + } + } +} From f5d0e4db125d8ba27f19778aa03bda4b44bed286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 20:28:47 +0200 Subject: [PATCH 03/36] Cleanup & documentation --- GRDB/Record/FetchableRecord+Decodable.swift | 114 +++++++++++++++- GRDB/Record/FetchableRecord.swift | 141 +++++--------------- 2 files changed, 142 insertions(+), 113 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 19eb6689d..c5587667f 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,5 +1,12 @@ import Foundation +extension FetchableRecord where Self: Decodable { + public init(row: Row) { + let decoder = RowDecoder(row: row, codingPath: []) + try! self.init(from: decoder) + } +} + // MARK: - RowDecoder /// The decoder that decodes a record from a database row @@ -292,10 +299,107 @@ extension ColumnDecoder: SingleValueDecodingContainer { /// The error that triggers JSON decoding private struct JSONRequiredError: Error { } -extension FetchableRecord where Self: Decodable { - /// Initializes a record from `row`. - public init(row: Row) { - let decoder = RowDecoder(row: row, codingPath: []) - try! self.init(from: decoder) +private extension DatabaseDateDecodingStrategy { + @inline(__always) + func decode(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + switch self { + case .deferredToDate: + return Date(sqliteStatement: sqliteStatement, index: index) + case .timeIntervalSinceReferenceDate: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSinceReferenceDate: timeInterval) + case .timeIntervalSince1970: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSince1970: timeInterval) + case .millisecondsSince1970: + let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) + return Date(timeIntervalSince1970: timeInterval / 1000.0) + case .iso8601(let formatter): + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = formatter.date(from: string) else { + fatalConversionError( + to: Date.self, + from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), + conversionContext: conversionContext()) + } + return date + case .formatted(let formatter): + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = formatter.date(from: string) else { + fatalConversionError( + to: Date.self, + from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), + conversionContext: conversionContext()) + } + return date + case .custom(let format): + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + guard let date = format(dbValue) else { + fatalConversionError( + to: Date.self, + from: dbValue, + conversionContext: conversionContext()) + } + return date + } + } + + @inline(__always) + func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + return decode(sqliteStatement:sqliteStatement, index:index, conversionContext: conversionContext) + } + + @inline(__always) + func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + if let date = dateFromDatabaseValue(dbValue) { + return date + } else { + fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + } + } + + @inline(__always) + func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + if dbValue.isNull { + return nil + } else if let date = dateFromDatabaseValue(dbValue) { + return date + } else { + fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + } + } + + // Returns nil if decoding fails + @inline(__always) + private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? { + switch self { + case .deferredToDate: + return Date.fromDatabaseValue(dbValue) + case .timeIntervalSinceReferenceDate: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSinceReferenceDate: $0) } + case .timeIntervalSince1970: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSince1970: $0) } + case .millisecondsSince1970: + return TimeInterval + .fromDatabaseValue(dbValue) + .map { Date(timeIntervalSince1970: $0 / 1000.0) } + case .iso8601(let formatter): + return String + .fromDatabaseValue(dbValue) + .flatMap { formatter.date(from: $0) } + case .formatted(let formatter): + return String + .fromDatabaseValue(dbValue) + .flatMap { formatter.date(from: $0) } + case .custom(let format): + return format(dbValue) + } } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index cb73a3e16..e93281dfd 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -390,126 +390,51 @@ public final class RecordCursor : Cursor { } } -// MARK: - DateDatabaseDecodingStrategy +// MARK: - DatabaseDateDecodingStrategy /// The strategies available for formatting dates when decoding them from a /// database column. public enum DatabaseDateDecodingStrategy { /// The strategy that uses formatting from the Date structure. /// - /// See https://github.com/groue/GRDB.swift/blob/master/README.md#date-and-datecomponents - /// for details. + /// It decodes numeric values as a nunber of seconds since Epoch + /// (midnight UTC on January 1st, 1970). + /// + /// It decodes strings in the following formats, assuming UTC time zone. + /// Missing components are assumed to be zero. + /// + /// - `YYYY-MM-DD` + /// - `YYYY-MM-DD HH:MM` + /// - `YYYY-MM-DD HH:MM:SS` + /// - `YYYY-MM-DD HH:MM:SS.SSS` + /// - `YYYY-MM-DDTHH:MM` + /// - `YYYY-MM-DDTHH:MM:SS` + /// - `YYYY-MM-DDTHH:MM:SS.SSS` case deferredToDate + + /// Decodes numeric values as a number of seconds between the date and + /// midnight UTC on 1 January 2001 case timeIntervalSinceReferenceDate + + /// Decodes numeric values as a number of seconds between the date and + /// midnight UTC on 1 January 1970 case timeIntervalSince1970 + + /// Decodes numeric values as a number of milliseconds between the date and + /// midnight UTC on 1 January 1970 case millisecondsSince1970 + + /// Decodes a String, according to the provided formatter @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601(ISO8601DateFormatter) + + /// Decodes a String, according to the provided formatter case formatted(DateFormatter) + + /// Decodes according to the user-provided function. + /// + /// If the database value does not contain a suitable value, the function + /// must return nil (GRDB will interpret this nil result as a conversion + /// error, and react accordingly). case custom((DatabaseValue) -> Date?) } - -extension DatabaseDateDecodingStrategy { - @inline(__always) - func decode(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { - switch self { - case .deferredToDate: - return Date(sqliteStatement: sqliteStatement, index: index) - case .timeIntervalSinceReferenceDate: - let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) - return Date(timeIntervalSinceReferenceDate: timeInterval) - case .timeIntervalSince1970: - let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) - return Date(timeIntervalSince1970: timeInterval) - case .millisecondsSince1970: - let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) - return Date(timeIntervalSince1970: timeInterval / 1000.0) - case .iso8601(let formatter): - let string = String(sqliteStatement: sqliteStatement, index: index) - guard let date = formatter.date(from: string) else { - fatalConversionError( - to: Date.self, - from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), - conversionContext: conversionContext()) - } - return date - case .formatted(let formatter): - let string = String(sqliteStatement: sqliteStatement, index: index) - guard let date = formatter.date(from: string) else { - fatalConversionError( - to: Date.self, - from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), - conversionContext: conversionContext()) - } - return date - case .custom(let format): - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - guard let date = format(dbValue) else { - fatalConversionError( - to: Date.self, - from: dbValue, - conversionContext: conversionContext()) - } - return date - } - } - - @inline(__always) - func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - return nil - } - return decode(sqliteStatement:sqliteStatement, index:index, conversionContext: conversionContext) - } - - @inline(__always) - func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { - if let date = dateFromDatabaseValue(dbValue) { - return date - } else { - fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) - } - } - - @inline(__always) - func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { - if dbValue.isNull { - return nil - } else if let date = dateFromDatabaseValue(dbValue) { - return date - } else { - fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) - } - } - - // Returns nil if decoding fails - @inline(__always) - private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? { - switch self { - case .deferredToDate: - return Date.fromDatabaseValue(dbValue) - case .timeIntervalSinceReferenceDate: - return TimeInterval - .fromDatabaseValue(dbValue) - .map { Date(timeIntervalSinceReferenceDate: $0) } - case .timeIntervalSince1970: - return TimeInterval - .fromDatabaseValue(dbValue) - .map { Date(timeIntervalSince1970: $0) } - case .millisecondsSince1970: - return TimeInterval - .fromDatabaseValue(dbValue) - .map { Date(timeIntervalSince1970: $0 / 1000.0) } - case .iso8601(let formatter): - return String - .fromDatabaseValue(dbValue) - .flatMap { formatter.date(from: $0) } - case .formatted(let formatter): - return String - .fromDatabaseValue(dbValue) - .flatMap { formatter.date(from: $0) } - case .custom(let format): - return format(dbValue) - } - } -} From d1892c649c7ea15fff27491b3bcee286c9b61862 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 21:41:47 +0200 Subject: [PATCH 04/36] Documentation --- GRDB/Record/FetchableRecord.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index e93281dfd..4ccb07756 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -98,6 +98,8 @@ public protocol FetchableRecord { /// When the FetchableRecord type also adopts the standard Decodable /// protocol, this property controls the decoding of date properties. + /// + /// Default value is .deferredToDate static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } } From ff306c21e2c37f40f9ed16b1dbf5b79d2e40dd77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 21:54:41 +0200 Subject: [PATCH 05/36] DatabaseDateEncodingStrategy --- GRDB/Record/PersistableRecord+Encodable.swift | 221 +++++++++--------- GRDB/Record/PersistableRecord.swift | 47 ++++ 2 files changed, 161 insertions(+), 107 deletions(-) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 046e0272b..3dd51ecf0 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -1,5 +1,13 @@ import Foundation +extension MutablePersistableRecord where Self: Encodable { + public func encode(to container: inout PersistenceContainer) { + let encoder = RecordEncoder() + try! encode(to: encoder) + container = encoder.persistenceContainer + } +} + // MARK: - RecordEncoder /// The encoder that encodes a record into GRDB's PersistenceContainer @@ -13,12 +21,6 @@ private class RecordEncoder: Encoder { _persistenceContainer = PersistenceContainer() } - /// Helper method - @inline(__always) - fileprivate func encode(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { - _persistenceContainer[key.stringValue] = value - } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { let container = KeyedContainer(recordEncoder: self) return KeyedEncodingContainer(container) @@ -53,71 +55,47 @@ private class RecordEncoder: Encoder { var codingPath: [CodingKey] { return [] } - func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int16, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int32, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int64, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt8, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt16, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt32, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt64, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Float, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Double, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: String, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } + func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: T, forKey key: Key) throws where T : Encodable { - if let value = value as? DatabaseValueConvertible { - // Prefer DatabaseValueConvertible encoding over Decodable. - // This allows us to encode Date as String, for example. - recordEncoder.encode(value.databaseValue, forKey: key) - } else { - do { - // This encoding will fail for types that encode into keyed - // or unkeyed containers, because we're encoding a single - // value here (string, int, double, data, null). If such an - // error happens, we'll switch to JSON encoding. - let encoder = ColumnEncoder(recordEncoder: recordEncoder, key: key) - try value.encode(to: encoder) - } catch is JSONRequiredError { - // Encode to JSON - let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) - - // Store JSON String in the database for easier debugging and - // database inspection. Thanks to SQLite weak typing, we won't - // have any trouble decoding this string into data when we - // eventually perform JSON decoding. - // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String - recordEncoder.encode(jsonString, forKey: key) - } - } + try recordEncoder.encode(value, forKey: key) } - func encodeNil(forKey key: Key) throws { recordEncoder.encode(nil, forKey: key) } + func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) } - func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } - func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.encode(value, forKey: key) } + func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { - try encode(value, forKey: key) + try recordEncoder.encode(value, forKey: key) } else { - recordEncoder.encode(nil, forKey: key) + recordEncoder.persist(nil, forKey: key) } } @@ -137,6 +115,43 @@ private class RecordEncoder: Encoder { fatalError("Not implemented") } } + + /// Helper methods + @inline(__always) + fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { + _persistenceContainer[key.stringValue] = value + } + + @inline(__always) + fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T : Encodable { + if let date = value as? Date { + persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) + } else if let value = value as? DatabaseValueConvertible { + // Prefer DatabaseValueConvertible encoding over Decodable. + // This allows us to encode Date as String, for example. + persist(value.databaseValue, forKey: key) + } else { + do { + // This encoding will fail for types that encode into keyed + // or unkeyed containers, because we're encoding a single + // value here (string, int, double, data, null). If such an + // error happens, we'll switch to JSON encoding. + let encoder = ColumnEncoder(recordEncoder: self, key: key) + try value.encode(to: encoder) + } catch is JSONRequiredError { + // Encode to JSON + let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) + + // Store JSON String in the database for easier debugging and + // database inspection. Thanks to SQLite weak typing, we won't + // have any trouble decoding this string into data when we + // eventually perform JSON decoding. + // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string + let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String + persist(jsonString, forKey: key) + } + } + } } // MARK: - ColumnEncoder @@ -174,49 +189,25 @@ private struct ColumnEncoder: Encoder { } extension ColumnEncoder: SingleValueEncodingContainer { - func encodeNil() throws { recordEncoder.encode(nil, forKey: key) } + func encodeNil() throws { recordEncoder.persist(nil, forKey: key) } - func encode(_ value: Bool ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int8 ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int16 ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int32 ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Int64 ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt8 ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt16) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt32) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: UInt64) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Float ) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: Double) throws { recordEncoder.encode(value, forKey: key) } - func encode(_ value: String) throws { recordEncoder.encode(value, forKey: key) } + func encode(_ value: Bool ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int8 ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int16 ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int32 ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Int64 ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt8 ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt16) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt32) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: UInt64) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Float ) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) } + func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: T) throws where T : Encodable { - if let value = value as? DatabaseValueConvertible { - // Prefer DatabaseValueConvertible encoding over Decodable. - // This allows us to encode Date as String, for example. - recordEncoder.encode(value.databaseValue, forKey: key) - } else { - do { - // This encoding will fail for types that encode into keyed - // or unkeyed containers, because we're encoding a single - // value here (string, int, double, data, null). If such an - // error happens, we'll switch to JSON encoding. - let encoder = ColumnEncoder(recordEncoder: recordEncoder, key: key) - try value.encode(to: encoder) - } catch is JSONRequiredError { - // Encode to JSON - let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) - - // Store JSON String in the database for easier debugging and - // database inspection. Thanks to SQLite weak typing, we won't - // have any trouble decoding this string into data when we - // eventually perform JSON decoding. - // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String - recordEncoder.encode(jsonString, forKey: key) - } - } + try recordEncoder.encode(value, forKey: key) } } @@ -323,10 +314,26 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { } } -extension MutablePersistableRecord where Self: Encodable { - public func encode(to container: inout PersistenceContainer) { - let encoder = RecordEncoder() - try! encode(to: encoder) - container = encoder.persistenceContainer +private extension DatabaseDateEncodingStrategy { + @inline(__always) + func encode(_ date: Date) -> DatabaseValueConvertible? { + switch self { + case .deferredToDate: + return date.databaseValue + case .timeIntervalSinceReferenceDate: + return date.timeIntervalSinceReferenceDate + case .timeIntervalSince1970: + return date.timeIntervalSince1970 + case .millisecondsSince1970: + return Int64(floor(1000.0 * date.timeIntervalSince1970)) + case .secondsSince1970: + return Int64(floor(date.timeIntervalSince1970)) + case .iso8601(let formatter): + return formatter.string(from: date) + case .formatted(let formatter): + return formatter.string(from: date) + case .custom(let format): + return format(date) + } } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index d27adaf38..414e68fe6 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -387,6 +387,12 @@ public protocol MutablePersistableRecord : TableRecord { /// } /// } static func databaseJSONEncoder(for column: String) -> JSONEncoder + + /// When the PersistableRecord type also adopts the standard Encodable + /// protocol, this property controls the encoding of date properties. + /// + /// Default value is .deferredToDate + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } } extension MutablePersistableRecord { @@ -411,6 +417,10 @@ extension MutablePersistableRecord { } return encoder } + + public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { + return .deferredToDate + } } extension MutablePersistableRecord { @@ -944,7 +954,44 @@ extension PersistableRecord { try insert(db) } } +} + + +// MARK: - DatabaseDateEncodingStrategy + +/// The strategies available for formatting dates when encoding them into a +/// database column. +public enum DatabaseDateEncodingStrategy { + /// The strategy that uses formatting from the Date structure. + /// + /// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone. + case deferredToDate + /// Encodes a Double: the number of seconds between the date and + /// midnight UTC on 1 January 2001 + case timeIntervalSinceReferenceDate + + /// Encodes a Double: the number of seconds between the date and + /// midnight UTC on 1 January 1970 + case timeIntervalSince1970 + + /// Encodes an Int64: the number of seconds between the date and + /// midnight UTC on 1 January 1970 + case secondsSince1970 + + /// Encodes an Int64: the number of milliseconds between the date and + /// midnight UTC on 1 January 1970 + case millisecondsSince1970 + + /// Encodes a String, according to the provided formatter + @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) + case iso8601(ISO8601DateFormatter) + + /// Encodes a String, according to the provided formatter + case formatted(DateFormatter) + + /// Encodes the result of the user-provided function + case custom((Date) -> DatabaseValueConvertible?) } // MARK: - DAO From 140c590c49008b90a71af8bf925b8610ae0f5be9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 21:54:50 +0200 Subject: [PATCH 06/36] DatabaseDateEncodingStrategy tests --- GRDB.xcodeproj/project.pbxproj | 6 + GRDBCipher.xcodeproj/project.pbxproj | 10 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../DatabaseDateEncodingStrategyTests.swift | 219 ++++++++++++++++++ 4 files changed, 241 insertions(+) create mode 100644 Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 53e9326c8..3a32ac2b2 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -303,6 +303,8 @@ 5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; }; 5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; @@ -932,6 +934,7 @@ 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; + 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1281,6 +1284,7 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2662,6 +2666,7 @@ 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, @@ -2825,6 +2830,7 @@ 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, + 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 395b10643..333564c8f 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -345,6 +345,10 @@ 5665FA232129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA242129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA252129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA412129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 5665FA422129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 5665FA432129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 5665FA442129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; }; 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; }; 566A843020413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; @@ -1024,6 +1028,7 @@ 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; + 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1323,6 +1328,7 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2352,6 +2358,7 @@ 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, + 5665FA412129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE8220F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2515,6 +2522,7 @@ 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, + 5665FA422129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE8320F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2790,6 +2798,7 @@ 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, + 5665FA432129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE8420F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, @@ -2953,6 +2962,7 @@ 5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, + 5665FA442129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 488f477cb..f995a7d50 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -147,6 +147,8 @@ 5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; }; 5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; + 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; @@ -692,6 +694,7 @@ 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; + 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -980,6 +983,7 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2023,6 +2027,7 @@ F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, + 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2298,6 +2303,7 @@ F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift new file mode 100644 index 000000000..981f2b55a --- /dev/null +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -0,0 +1,219 @@ +import XCTest +import Foundation +#if GRDBCIPHER + @testable import GRDBCipher +#elseif GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +private protocol StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy { get } +} + +private enum StrategyDeferredToDate: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .deferredToDate +} + +private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .timeIntervalSinceReferenceDate +} + +private enum StrategyTimeIntervalSince1970: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 +} + +private enum StrategySecondsSince1970: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .secondsSince1970 +} + +private enum StrategyMillisecondsSince1970: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970 +} + +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +private enum StrategyIso8601: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .iso8601({ + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }()) +} + +private enum StrategyFormatted: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .formatted({ + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0)! + formatter.dateStyle = .full + formatter.timeStyle = .full + return formatter + }()) +} + +private enum StrategyCustom: StrategyProvider { + static var strategy: DatabaseDateEncodingStrategy = .custom { _ in "custom" } +} + +private struct RecordWithDate: PersistableRecord, Encodable { + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy } + var date: Date +} + +private struct RecordWithOptionalDate: PersistableRecord, Encodable { + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy } + var date: Date? +} + +class DatabaseDateEncodingStrategyTests: GRDBTestCase { + let testedDates = [ + Date(timeIntervalSince1970: -987654.321), + Date(timeIntervalSince1970: 123456.789), + Date(timeIntervalSinceReferenceDate: 0), + Date(timeIntervalSinceReferenceDate: 123456.789), + ] + + private func test( + record: T, + expectedStorage: DatabaseValue.Storage) + { + var container = PersistenceContainer() + record.encode(to: &container) + if let dbValue = container["date"]?.databaseValue { + XCTAssertEqual(dbValue.storage, expectedStorage) + } else { + XCTAssertEqual(.null, expectedStorage) + } + } + + private func test(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) { + test(record: RecordWithDate(date: date), expectedStorage: value.databaseValue.storage) + test(record: RecordWithOptionalDate(date: date), expectedStorage: value.databaseValue.storage) + } + + private func testNullEncoding(strategy: Strategy.Type) { + test(record: RecordWithOptionalDate(date: nil), expectedStorage: .null) + } +} + +// MARK: - deferredToDate + +extension DatabaseDateEncodingStrategyTests { + func testDeferredToDate() { + testNullEncoding(strategy: StrategyDeferredToDate.self) + + for (date, value) in zip(testedDates, [ + "1969-12-20 13:39:05.679", + "1970-01-02 10:17:36.789", + "2001-01-01 00:00:00.000", + "2001-01-02 10:17:36.789", + ]) { test(strategy: StrategyDeferredToDate.self, encodesDate: date, as: value) } + } +} + +// MARK: - timeIntervalSinceReferenceDate + +extension DatabaseDateEncodingStrategyTests { + func testTimeIntervalSinceReferenceDate() { + testNullEncoding(strategy: StrategyTimeIntervalSinceReferenceDate.self) + + for (date, value) in zip(testedDates, [ + -979294854.321, + -978183743.211, + 0.0, + 123456.789, + ]) { test(strategy: StrategyTimeIntervalSinceReferenceDate.self, encodesDate: date, as: value) } + } +} + +// MARK: - timeIntervalSince1970 + +extension DatabaseDateEncodingStrategyTests { + func testTimeIntervalSince1970() { + testNullEncoding(strategy: StrategyTimeIntervalSince1970.self) + + for (date, value) in zip(testedDates, [ + -987654.32099997997, + 123456.78900003433, + 978307200.0, + 978430656.789, + ]) { test(strategy: StrategyTimeIntervalSince1970.self, encodesDate: date, as: value) } + } +} + +// MARK: - secondsSince1970 + +extension DatabaseDateEncodingStrategyTests { + func testSecondsSince1970() { + testNullEncoding(strategy: StrategySecondsSince1970.self) + + for (date, value) in zip(testedDates, [ + -987655, + 123456, + 978307200, + 978430656, + ]) { test(strategy: StrategySecondsSince1970.self, encodesDate: date, as: value) } + } +} + +// MARK: - millisecondsSince1970 + +extension DatabaseDateEncodingStrategyTests { + func testMillisecondsSince1970() { + testNullEncoding(strategy: StrategyMillisecondsSince1970.self) + + for (date, value) in zip(testedDates, [ + -987654321, + 123456789, + 978307200000, + 978430656789, + ]) { test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) } + } +} + +// MARK: - iso8601(ISO8601DateFormatter) + +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +extension DatabaseDateEncodingStrategyTests { + func testIso8601() { + testNullEncoding(strategy: StrategyIso8601.self) + + for (date, value) in zip(testedDates, [ + "1969-12-20T13:39:05Z", + "1970-01-02T10:17:36Z", + "2001-01-01T00:00:00Z", + "2001-01-02T10:17:36Z", + ]) { test(strategy: StrategyIso8601.self, encodesDate: date, as: value) } + } +} + +// MARK: - formatted(DateFormatter) + +extension DatabaseDateEncodingStrategyTests { + func testFormatted() { + testNullEncoding(strategy: StrategyFormatted.self) + + for (date, value) in zip(testedDates, [ + "Saturday, December 20, 1969 at 1:39:05 PM GMT", + "Friday, January 2, 1970 at 10:17:36 AM Greenwich Mean Time", + "Monday, January 1, 2001 at 12:00:00 AM Greenwich Mean Time", + "Tuesday, January 2, 2001 at 10:17:36 AM Greenwich Mean Time", + ]) { test(strategy: StrategyFormatted.self, encodesDate: date, as: value) } + } +} + +// MARK: - custom((Date) -> DatabaseValueConvertible?) + +extension DatabaseDateEncodingStrategyTests { + func testCustom() { + testNullEncoding(strategy: StrategyCustom.self) + + for (date, value) in zip(testedDates, [ + "custom", + "custom", + "custom", + "custom", + ]) { test(strategy: StrategyCustom.self, encodesDate: date, as: value) } + } +} From bbf7eb0b735c6d367fb8ed4faf4f9bc1ff4f91b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 22:15:19 +0200 Subject: [PATCH 07/36] Make tests platform-independent --- GRDB/Record/FetchableRecord+Decodable.swift | 18 ++++--- GRDB/Record/PersistableRecord+Encodable.swift | 6 ++- .../DatabaseDateDecodingStrategyTests.swift | 50 ++++++++++--------- .../DatabaseDateEncodingStrategyTests.swift | 47 +++++++++-------- 4 files changed, 67 insertions(+), 54 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index c5587667f..2a17df2ad 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -315,14 +315,18 @@ private extension DatabaseDateDecodingStrategy { let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) return Date(timeIntervalSince1970: timeInterval / 1000.0) case .iso8601(let formatter): - let string = String(sqliteStatement: sqliteStatement, index: index) - guard let date = formatter.date(from: string) else { - fatalConversionError( - to: Date.self, - from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), - conversionContext: conversionContext()) + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + let string = String(sqliteStatement: sqliteStatement, index: index) + guard let date = formatter.date(from: string) else { + fatalConversionError( + to: Date.self, + from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), + conversionContext: conversionContext()) + } + return date + } else { + fatalError("ISO8601DateFormatter is unavailable on this platform.") } - return date case .formatted(let formatter): let string = String(sqliteStatement: sqliteStatement, index: index) guard let date = formatter.date(from: string) else { diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 3dd51ecf0..67caf4cf6 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -329,7 +329,11 @@ private extension DatabaseDateEncodingStrategy { case .secondsSince1970: return Int64(floor(date.timeIntervalSince1970)) case .iso8601(let formatter): - return formatter.string(from: date) + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + return formatter.string(from: date) + } else { + fatalError("ISO8601DateFormatter is unavailable on this platform.") + } case .formatted(let formatter): return formatter.string(from: date) case .custom(let format): diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index 428a793d1..4a587f3c1 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -13,24 +13,24 @@ private protocol StrategyProvider { } private enum StrategyDeferredToDate: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .deferredToDate + static let strategy: DatabaseDateDecodingStrategy = .deferredToDate } private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .timeIntervalSinceReferenceDate + static let strategy: DatabaseDateDecodingStrategy = .timeIntervalSinceReferenceDate } private enum StrategyTimeIntervalSince1970: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 + static let strategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 } private enum StrategyMillisecondsSince1970: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970 + static let strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970 } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601Strategy: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .iso8601({ + static let strategy: DatabaseDateDecodingStrategy = .iso8601({ let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter @@ -38,7 +38,7 @@ private enum StrategyIso8601Strategy: StrategyProvider { } private enum StrategyFormatted: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .formatted({ + static let strategy: DatabaseDateDecodingStrategy = .formatted({ let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0)! @@ -49,7 +49,7 @@ private enum StrategyFormatted: StrategyProvider { } private enum StrategyCustom: StrategyProvider { - static var strategy: DatabaseDateDecodingStrategy = .custom { _ in + static let strategy: DatabaseDateDecodingStrategy = .custom { _ in return Date(timeIntervalSinceReferenceDate: 123456) } } @@ -276,25 +276,27 @@ extension DatabaseDateDecodingStrategyTests { // MARK: - iso8601(ISO8601DateFormatter) -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension DatabaseDateDecodingStrategyTests { func testIso8601() throws { - try makeDatabaseQueue().read { db in - var calendar = Calendar(identifier: .gregorian) - calendar.timeZone = TimeZone(secondsFromGMT: 0)! - - // Null - try testNullDecoding(db, strategy: StrategyIso8601Strategy.self) - - // Date - try test(db, strategy: StrategyIso8601Strategy.self, databaseValue: "2018-08-19T17:18:07Z") { date in - XCTAssertEqual(calendar.component(.year, from: date), 2018) - XCTAssertEqual(calendar.component(.month, from: date), 8) - XCTAssertEqual(calendar.component(.day, from: date), 19) - XCTAssertEqual(calendar.component(.hour, from: date), 17) - XCTAssertEqual(calendar.component(.minute, from: date), 18) - XCTAssertEqual(calendar.component(.second, from: date), 7) - XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + // check ISO8601DateFormatter availabiliity + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + try makeDatabaseQueue().read { db in + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + + // Null + try testNullDecoding(db, strategy: StrategyIso8601Strategy.self) + + // Date + try test(db, strategy: StrategyIso8601Strategy.self, databaseValue: "2018-08-19T17:18:07Z") { date in + XCTAssertEqual(calendar.component(.year, from: date), 2018) + XCTAssertEqual(calendar.component(.month, from: date), 8) + XCTAssertEqual(calendar.component(.day, from: date), 19) + XCTAssertEqual(calendar.component(.hour, from: date), 17) + XCTAssertEqual(calendar.component(.minute, from: date), 18) + XCTAssertEqual(calendar.component(.second, from: date), 7) + XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) + } } } } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 981f2b55a..bde1c1707 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -13,28 +13,28 @@ private protocol StrategyProvider { } private enum StrategyDeferredToDate: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .deferredToDate + static let strategy: DatabaseDateEncodingStrategy = .deferredToDate } private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .timeIntervalSinceReferenceDate + static let strategy: DatabaseDateEncodingStrategy = .timeIntervalSinceReferenceDate } private enum StrategyTimeIntervalSince1970: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 + static let strategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 } private enum StrategySecondsSince1970: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .secondsSince1970 + static let strategy: DatabaseDateEncodingStrategy = .secondsSince1970 } private enum StrategyMillisecondsSince1970: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970 + static let strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970 } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .iso8601({ + static let strategy: DatabaseDateEncodingStrategy = .iso8601({ let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter @@ -42,18 +42,18 @@ private enum StrategyIso8601: StrategyProvider { } private enum StrategyFormatted: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .formatted({ + static let strategy: DatabaseDateEncodingStrategy = .formatted({ let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0)! formatter.dateStyle = .full - formatter.timeStyle = .full + formatter.timeStyle = .medium return formatter }()) } private enum StrategyCustom: StrategyProvider { - static var strategy: DatabaseDateEncodingStrategy = .custom { _ in "custom" } + static let strategy: DatabaseDateEncodingStrategy = .custom { _ in "custom" } } private struct RecordWithDate: PersistableRecord, Encodable { @@ -168,7 +168,7 @@ extension DatabaseDateEncodingStrategyTests { 123456789, 978307200000, 978430656789, - ]) { test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) } + ] as [Int64]) { test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) } } } @@ -177,14 +177,17 @@ extension DatabaseDateEncodingStrategyTests { @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension DatabaseDateEncodingStrategyTests { func testIso8601() { - testNullEncoding(strategy: StrategyIso8601.self) - - for (date, value) in zip(testedDates, [ - "1969-12-20T13:39:05Z", - "1970-01-02T10:17:36Z", - "2001-01-01T00:00:00Z", - "2001-01-02T10:17:36Z", - ]) { test(strategy: StrategyIso8601.self, encodesDate: date, as: value) } + // check ISO8601DateFormatter availabiliity + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + testNullEncoding(strategy: StrategyIso8601.self) + + for (date, value) in zip(testedDates, [ + "1969-12-20T13:39:05Z", + "1970-01-02T10:17:36Z", + "2001-01-01T00:00:00Z", + "2001-01-02T10:17:36Z", + ]) { test(strategy: StrategyIso8601.self, encodesDate: date, as: value) } + } } } @@ -195,10 +198,10 @@ extension DatabaseDateEncodingStrategyTests { testNullEncoding(strategy: StrategyFormatted.self) for (date, value) in zip(testedDates, [ - "Saturday, December 20, 1969 at 1:39:05 PM GMT", - "Friday, January 2, 1970 at 10:17:36 AM Greenwich Mean Time", - "Monday, January 1, 2001 at 12:00:00 AM Greenwich Mean Time", - "Tuesday, January 2, 2001 at 10:17:36 AM Greenwich Mean Time", + "Saturday, December 20, 1969 at 1:39:05 PM", + "Friday, January 2, 1970 at 10:17:36 AM", + "Monday, January 1, 2001 at 12:00:00 AM", + "Tuesday, January 2, 2001 at 10:17:36 AM", ]) { test(strategy: StrategyFormatted.self, encodesDate: date, as: value) } } } From f925d7e3d49c230d1e928b2a03f5e7d677a3e942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 22:21:03 +0200 Subject: [PATCH 08/36] Fix SPM --- GRDB/Record/FetchableRecord+Decodable.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 2a17df2ad..bdedec508 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,4 +1,9 @@ import Foundation +#if SWIFT_PACKAGE + import CSQLite +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER + import SQLite3 +#endif extension FetchableRecord where Self: Decodable { public init(row: Row) { From bb90ea0259a77d7fc3186f4135b808a4d2614fab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Aug 2018 22:40:51 +0200 Subject: [PATCH 09/36] Improve explanation why the sortedKeys JSON option is recommended --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40275a384..18592ee17 100644 --- a/README.md +++ b/README.md @@ -2706,7 +2706,7 @@ struct Player: Codable, FetchableRecord, PersistableRecord { } ``` -> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable, and this helps [Record Comparison] yield the expected results. +> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) to accurately recognize changed records. ### The userInfo Dictionary From b7273e0a7ec7d56bd79ba0343fa232a2b24ee073 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:05:20 +0200 Subject: [PATCH 10/36] Documentation --- GRDB/Record/FetchableRecord.swift | 22 ++++++- GRDB/Record/PersistableRecord.swift | 22 ++++++- README.md | 90 ++++++++++++++++++----------- 3 files changed, 97 insertions(+), 37 deletions(-) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 4ccb07756..11d7def07 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -100,6 +100,15 @@ public protocol FetchableRecord { /// protocol, this property controls the decoding of date properties. /// /// Default value is .deferredToDate + /// + /// For example: + /// + /// struct Player: FetchableRecord, Decodable { + /// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 + /// + /// var name: String + /// var registrationDate: Date // decoded from epoch timestamp + /// } static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } } @@ -394,8 +403,17 @@ public final class RecordCursor : Cursor { // MARK: - DatabaseDateDecodingStrategy -/// The strategies available for formatting dates when decoding them from a -/// database column. +/// DatabaseDateDecodingStrategy specifies how FetchableRecord types that also +/// adopt the standard Decodable protocol decode their date properties. +/// +/// For example: +/// +/// struct Player: FetchableRecord, Decodable { +/// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 +/// +/// var name: String +/// var registrationDate: Date // decoded from epoch timestamp +/// } public enum DatabaseDateDecodingStrategy { /// The strategy that uses formatting from the Date structure. /// diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 414e68fe6..42086fdae 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -392,6 +392,15 @@ public protocol MutablePersistableRecord : TableRecord { /// protocol, this property controls the encoding of date properties. /// /// Default value is .deferredToDate + /// + /// For example: + /// + /// struct Player: PersistableRecord, Encodable { + /// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 + /// + /// var name: String + /// var registrationDate: Date // encoded as an epoch timestamp + /// } static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } } @@ -959,8 +968,17 @@ extension PersistableRecord { // MARK: - DatabaseDateEncodingStrategy -/// The strategies available for formatting dates when encoding them into a -/// database column. +/// DatabaseDateEncodingStrategy specifies how PersistableRecord types that also +/// adopt the standard Encodable protocol encode their date properties. +/// +/// For example: +/// +/// struct Player: PersistableRecord, Encodable { +/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 +/// +/// var name: String +/// var registrationDate: Date // encoded as an epoch timestamp +/// } public enum DatabaseDateEncodingStrategy { /// The strategy that uses formatting from the Date structure. /// diff --git a/README.md b/README.md index 18592ee17..0cf6f6f23 100644 --- a/README.md +++ b/README.md @@ -2602,39 +2602,10 @@ try dbQueue.write { db in } ``` -> :point_up: **Note**: Some codable values have a different way to encode and decode themselves in a standard archive vs. a database column. For example, [Date](#date-and-datecomponents) saves itself as a numerical timestamp (archive) or a string (database). When such an ambiguity happens, GRDB always favors customized database encoding and decoding. - -> :point_up: **Note**: When your Codable record provides a custom implementation for `Decodable.init(from:)` or `Encodable.encode(to:)`, you may want to provide a `userInfo` context dictionary: see [The userInfo Dictionary]. - - -If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can use coding keys as [query interface](#the-query-interface) columns, just by adding conformance to the ColumnExpression protocol: - -```swift -struct Player: Codable, FetchableRecord, PersistableRecord { - var name: String - var score: Int - - private enum CodingKeys: String, CodingKey, ColumnExpression { - case name, score - } - - static func filter(name: String) -> QueryInterfaceRequest { - return filter(CodingKeys.name == name) - } - - static var maximumScore: QueryInterfaceRequest { - return select(max(CodingKeys.score), as: Int.self) - } -} - -try dbQueue.read { db in - // SELECT * FROM player WHERE name = 'Arthur' - let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player? - - // SELECT MAX(score) FROM player - let maxScore = try Player.maximumScore.fetchOne(db) // Int? -} -``` +- [JSON Columns] +- [Date Coding Strategies](#date-coding-strategies) +- [The userInfo Dictionary] +- [Tip: Use CodingKeys as Columns](#tip-use-codingkeys-as-columns) ### JSON Columns @@ -2709,6 +2680,27 @@ struct Player: Codable, FetchableRecord, PersistableRecord { > :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) to accurately recognize changed records. +### Date Coding Strategies + +By default, [Codable records](#codable-records) encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). + +This behavior can be overridden: + +```swift +protocol FetchableRecord { + static var databaseDateDecodingStrategy: + DatabaseDateDecodingStrategy { get } +} + +protocol MutablePersistableRecord { + static var databaseDateEncodingStrategy: + DatabaseDateEncodingStrategy { get } +} +``` + +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html) and [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html) for more information. + + ### The userInfo Dictionary Your [Codable records](#codable-records) can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context. @@ -2754,6 +2746,38 @@ let player = try Player.fetchOne(db, ...) ``` +### Tip: Use CodingKeys as Columns + +If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can use coding keys as [query interface](#the-query-interface) columns, just by adding conformance to the ColumnExpression protocol: + +```swift +struct Player: Codable, FetchableRecord, PersistableRecord { + var name: String + var score: Int + + private enum CodingKeys: String, CodingKey, ColumnExpression { + case name, score + } + + static func filter(name: String) -> QueryInterfaceRequest { + return filter(CodingKeys.name == name) + } + + static var maximumScore: QueryInterfaceRequest { + return select(max(CodingKeys.score), as: Int.self) + } +} + +try dbQueue.read { db in + // SELECT * FROM player WHERE name = 'Arthur' + let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player? + + // SELECT MAX(score) FROM player + let maxScore = try Player.maximumScore.fetchOne(db) // Int? +} +``` + + ## Record Class **Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can compare against previous versions of themselves in order to [avoid useless updates](#record-comparison). From 81e777a323ccdc148568c123891f3510023c577b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:14:51 +0200 Subject: [PATCH 11/36] Enhance "Use CodingKeys as Columns" chapter --- README.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0cf6f6f23..0df4213c6 100644 --- a/README.md +++ b/README.md @@ -2748,17 +2748,24 @@ let player = try Player.fetchOne(db, ...) ### Tip: Use CodingKeys as Columns -If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can use coding keys as [query interface](#the-query-interface) columns, just by adding conformance to the ColumnExpression protocol: +If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can instruct GRDB to use those coding keys as database columns: ```swift struct Player: Codable, FetchableRecord, PersistableRecord { var name: String var score: Int + // Add ColumnExpression conformance private enum CodingKeys: String, CodingKey, ColumnExpression { case name, score } - +} +``` + +This allows your record to build requests with the [query interface](#the-query-interface): + +```swift +extension Player { static func filter(name: String) -> QueryInterfaceRequest { return filter(CodingKeys.name == name) } @@ -2767,7 +2774,12 @@ struct Player: Codable, FetchableRecord, PersistableRecord { return select(max(CodingKeys.score), as: Int.self) } } +``` +Those requests can both fetch... + +```swift +// Fetch values try dbQueue.read { db in // SELECT * FROM player WHERE name = 'Arthur' let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player? @@ -2777,6 +2789,17 @@ try dbQueue.read { db in } ``` +... and feed database observation tools such as [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): + +```swift +// Observe changes +Player.maximumScore.rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { maxScore: Int? in + print("The maximum score has changed") + }) +``` + ## Record Class From 1c9ce6781bea399142028b177ba751a23651e7f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:30:57 +0200 Subject: [PATCH 12/36] Enhance "JSON Columns" chapter --- README.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0df4213c6..84929e647 100644 --- a/README.md +++ b/README.md @@ -2618,9 +2618,9 @@ enum AchievementColor: String, Codable { } struct Achievement: Codable { - var name: String - var color: AchievementColor - var date: Date + var name: String + var color: AchievementColor + var date: Date } struct Player: Codable, FetchableRecord, PersistableRecord { @@ -2629,14 +2629,17 @@ struct Player: Codable, FetchableRecord, PersistableRecord { var achievements: [Achievement] // stored in a JSON column } -try dbQueue.write { db in +try! dbQueue.write { db in // INSERT INTO player (name, score, achievements) // VALUES ( // 'Arthur', // 100, - // '[{"color":"gold","name":"Use Codable Records"}]') - let achievement = Achievement(name: "Use Codable Records", color: .gold) - try Player(name: "Arthur", score: 100, achievements: [achievement]).insert(db) + // '[{"color":"gold", + // "date":1534746534010.4429, + // "name":"Use Codable Records"}]') + let achievement = Achievement(name: "Use Codable Records", color: .gold, date: Date()) + let player = Player(name: "Arthur", score: 100, achievements: [achievement]) + try player.insert(db) } ``` From 063fe707663db6cc558089154879a6c1c6fcd17f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:50:13 +0200 Subject: [PATCH 13/36] More fostering of Codable records --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 84929e647..3af4b5aee 100644 --- a/README.md +++ b/README.md @@ -2212,7 +2212,9 @@ Details follow: } ``` - FetchableRecord is not able to build SQL requests for you, though. For that, you also need TableRecord: + > :bulb: **Tip**: FetchableRecord can derive its implementation from the standard [Decodable](https://developer.apple.com/documentation/swift/decodable) protocol. See [Codable Records] for more information. + + FetchableRecord can decode database rows, but it is not able to build SQL requests for you. For that, you also need TableRecord: - [TableRecord] is able to **generate SQL queries**: @@ -2243,6 +2245,8 @@ Details follow: ``` A persistable record can also [compare](#record-comparison) itself against other records, and avoid useless database updates. + + > :bulb: **Tip**: PersistableRecord can derive its implementation from the standard [Encodable](https://developer.apple.com/documentation/swift/encodable) protocol. See [Codable Records] for more information. ## FetchableRecord Protocol From ad6f1f4a37f05f1fe8ffd0861363f97e28d8e638 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:51:48 +0200 Subject: [PATCH 14/36] Fix inner link --- README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3af4b5aee..fdb5028cb 100644 --- a/README.md +++ b/README.md @@ -2062,7 +2062,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [PersistableRecord Protocol](#persistablerecord-protocol) - [Persistence Methods](#persistence-methods) - [Customizing the Persistence Methods] -- [Codable Records](#codable-records) +- [Codable Records] - [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] @@ -2171,7 +2171,7 @@ Details follow: - [FetchableRecord Protocol](#fetchablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) - [PersistableRecord Protocol](#persistablerecord-protocol) -- [Codable Records](#codable-records) +- [Codable Records] - [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] @@ -2300,7 +2300,7 @@ extension Place : FetchableRecord { See [column values](#column-values) for more information about the `row[]` subscript. -When your record type adopts the standard Decodable protocol, you don't have to provide the implementation for `init(row:)`. See [Codable Records](#codable-records) for more information: +When your record type adopts the standard Decodable protocol, you don't have to provide the implementation for `init(row:)`. See [Codable Records] for more information: ```swift // That's all @@ -2484,7 +2484,7 @@ extension Place : MutablePersistableRecord { } ``` -When your record type adopts the standard Encodable protocol, you don't have to provide the implementation for `encode(to:)`. See [Codable Records](#codable-records) for more information: +When your record type adopts the standard Encodable protocol, you don't have to provide the implementation for `encode(to:)`. See [Codable Records] for more information: ```swift // That's all @@ -2689,7 +2689,7 @@ struct Player: Codable, FetchableRecord, PersistableRecord { ### Date Coding Strategies -By default, [Codable records](#codable-records) encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). +By default, [Codable Records] encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). This behavior can be overridden: @@ -2710,7 +2710,7 @@ See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/E ### The userInfo Dictionary -Your [Codable records](#codable-records) can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context. +Your [Codable Records] can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context. The recommended way to provide such context is the `userInfo` dictionary. Implement those properties: @@ -3185,7 +3185,7 @@ Each one of the three examples below is correct. You will pick one or the other This is the shortest way to define a record type. -See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records](#codable-records) for more information. +See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records] for more information. ```swift struct Place: Codable { @@ -5613,7 +5613,7 @@ PlayerInfo.all() ### Splitting Rows, the Codable Way -[Codable Records](#codable-records) build on top of the standard Decodable protocol in order to decode database rows. +[Codable Records] build on top of the standard Decodable protocol in order to decode database rows. You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code: @@ -7691,6 +7691,7 @@ This chapter has been renamed [Beyond FetchableRecord]. [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord +[Codable Records]: #codable-records [Columns Selected by a Request]: #columns-selected-by-a-request [Conflict Resolution]: #conflict-resolution [Customizing the Persistence Methods]: #customizing-the-persistence-methods From 8ea13dc5fd57b731163f4bc49ed81c45d31637a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:52:51 +0200 Subject: [PATCH 15/36] Quiet --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fdb5028cb..e562e0eba 100644 --- a/README.md +++ b/README.md @@ -2212,7 +2212,7 @@ Details follow: } ``` - > :bulb: **Tip**: FetchableRecord can derive its implementation from the standard [Decodable](https://developer.apple.com/documentation/swift/decodable) protocol. See [Codable Records] for more information. + > :bulb: **Tip**: FetchableRecord can derive its implementation from the standard Decodable protocol. See [Codable Records] for more information. FetchableRecord can decode database rows, but it is not able to build SQL requests for you. For that, you also need TableRecord: @@ -2246,7 +2246,7 @@ Details follow: A persistable record can also [compare](#record-comparison) itself against other records, and avoid useless database updates. - > :bulb: **Tip**: PersistableRecord can derive its implementation from the standard [Encodable](https://developer.apple.com/documentation/swift/encodable) protocol. See [Codable Records] for more information. + > :bulb: **Tip**: PersistableRecord can derive its implementation from the standard Encodable protocol. See [Codable Records] for more information. ## FetchableRecord Protocol From 319ac27b1582b944447e04cf1254abf8989aa03d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:56:02 +0200 Subject: [PATCH 16/36] Extend "Record Customization Options" chapter --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e562e0eba..87a6155c4 100644 --- a/README.md +++ b/README.md @@ -2607,7 +2607,7 @@ try dbQueue.write { db in ``` - [JSON Columns] -- [Date Coding Strategies](#date-coding-strategies) +- [Date Coding Strategies] - [The userInfo Dictionary] - [Tip: Use CodingKeys as Columns](#tip-use-codingkeys-as-columns) @@ -2950,6 +2950,7 @@ GRDB records come with many default behaviors, that are designed to fit most sit - [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. - [The Implicit RowID Primary Key]: all about the special `rowid` column. - [JSON Columns]: control the format of JSON columns. +- [Date Coding Strategies]: control the format of Date properties in your Codable records. - [The userInfo Dictionary]: adapt your Codable implementation for the database. - [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story. @@ -7695,6 +7696,7 @@ This chapter has been renamed [Beyond FetchableRecord]. [Columns Selected by a Request]: #columns-selected-by-a-request [Conflict Resolution]: #conflict-resolution [Customizing the Persistence Methods]: #customizing-the-persistence-methods +[Date Coding Strategies]: #date-coding-strategies [Fetching from Requests]: #fetching-from-requests [The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key [The userInfo Dictionary]: #the-userinfo-dictionary From 1e34128213deddf4978c0d7c3d5d3cd58590234f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:57:35 +0200 Subject: [PATCH 17/36] Sort "Record Customization Options" by expected popularity --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 87a6155c4..22e7272da 100644 --- a/README.md +++ b/README.md @@ -2947,10 +2947,10 @@ GRDB records come with many default behaviors, that are designed to fit most sit - [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`. - [Customizing the Persistence Methods]: define what happens when you call a persistance method such as `player.insert(db)` -- [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. -- [The Implicit RowID Primary Key]: all about the special `rowid` column. - [JSON Columns]: control the format of JSON columns. - [Date Coding Strategies]: control the format of Date properties in your Codable records. +- [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. +- [The Implicit RowID Primary Key]: all about the special `rowid` column. - [The userInfo Dictionary]: adapt your Codable implementation for the database. - [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story. From ba984427a432514abcf392c1526d2cc362f39bad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 08:58:17 +0200 Subject: [PATCH 18/36] Sort "Record Customization Options" by expected popularity --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 22e7272da..99b26113b 100644 --- a/README.md +++ b/README.md @@ -2945,12 +2945,12 @@ For an efficient algorithm which synchronizes the content of a database table wi GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs: -- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`. - [Customizing the Persistence Methods]: define what happens when you call a persistance method such as `player.insert(db)` - [JSON Columns]: control the format of JSON columns. - [Date Coding Strategies]: control the format of Date properties in your Codable records. - [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. - [The Implicit RowID Primary Key]: all about the special `rowid` column. +- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`. - [The userInfo Dictionary]: adapt your Codable implementation for the database. - [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story. From 2c9a4b69681b9a73c1a923141d310b4a27adf7f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 09:00:35 +0200 Subject: [PATCH 19/36] Enhance "Record Customization Options" chapter --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 99b26113b..d4b11c9fd 100644 --- a/README.md +++ b/README.md @@ -2946,14 +2946,17 @@ For an efficient algorithm which synchronizes the content of a database table wi GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs: - [Customizing the Persistence Methods]: define what happens when you call a persistance method such as `player.insert(db)` -- [JSON Columns]: control the format of JSON columns. -- [Date Coding Strategies]: control the format of Date properties in your Codable records. - [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index. - [The Implicit RowID Primary Key]: all about the special `rowid` column. - [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`. -- [The userInfo Dictionary]: adapt your Codable implementation for the database. - [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story. +[Codable Records] have a few extra options: + +- [JSON Columns]: control the format of JSON columns. +- [Date Coding Strategies]: control the format of Date properties in your Codable records. +- [The userInfo Dictionary]: adapt your Codable implementation for the database. + ### Conflict Resolution From e438d580b412db94e46ecc2b894b94975c052bf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 09:02:15 +0200 Subject: [PATCH 20/36] Don't close doors --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4b11c9fd..9abe9ad58 100644 --- a/README.md +++ b/README.md @@ -3155,7 +3155,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu **Some GRDB users eventually discover that the [FetchableRecord] protocol does not fit all situations.** Use cases that are not well handled by FetchableRecord include: -- Your application needs polymorphic row decoding: it decodes some class or another, depending on the values contained in a database row. +- Your application needs polymorphic row decoding: it decodes some type or another, depending on the values contained in a database row. - Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database. From f583ef0d2a07b4634cd4b9d689d044bd6412e9a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 19:30:59 +0200 Subject: [PATCH 21/36] Documentation --- README.md | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/README.md b/README.md index 9abe9ad58..6cf3417fe 100644 --- a/README.md +++ b/README.md @@ -2661,29 +2661,6 @@ protocol MutablePersistableRecord { } ``` -For example, here is how the Player type can customize the json format of its "achievements" JSON column: - -```swift -struct Player: Codable, FetchableRecord, PersistableRecord { - var name: String - var score: Int - var achievements: [Achievement] // stored in a JSON column - - static func databaseJSONDecoder(for column: String) -> JSONDecoder { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - } - - static func databaseJSONEncoder(for column: String) -> JSONEncoder { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - encoder.outputFormatting = .sortedKeys - return encoder - } -} -``` - > :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) to accurately recognize changed records. From 34c7b0b40c62d35b2c2d70f5a75cfc42b86773ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 19:32:59 +0200 Subject: [PATCH 22/36] Documentation --- README.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 6cf3417fe..b7fd343a9 100644 --- a/README.md +++ b/README.md @@ -2624,7 +2624,6 @@ enum AchievementColor: String, Codable { struct Achievement: Codable { var name: String var color: AchievementColor - var date: Date } struct Player: Codable, FetchableRecord, PersistableRecord { @@ -2638,10 +2637,8 @@ try! dbQueue.write { db in // VALUES ( // 'Arthur', // 100, - // '[{"color":"gold", - // "date":1534746534010.4429, - // "name":"Use Codable Records"}]') - let achievement = Achievement(name: "Use Codable Records", color: .gold, date: Date()) + // '[{"color":"gold","name":"Use Codable Records"}]') + let achievement = Achievement(name: "Use Codable Records", color: .gold) let player = Player(name: "Arthur", score: 100, achievements: [achievement]) try player.insert(db) } From 8fa405452dc9c4965b25c220f0d1d2e59248bfb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 19:38:11 +0200 Subject: [PATCH 23/36] Documentation --- README.md | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index b7fd343a9..bb499d0ca 100644 --- a/README.md +++ b/README.md @@ -2663,7 +2663,7 @@ protocol MutablePersistableRecord { ### Date Coding Strategies -By default, [Codable Records] encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). +By default, [Codable Records] encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). This behavior can be overridden: @@ -2686,7 +2686,7 @@ See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/E Your [Codable Records] can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context. -The recommended way to provide such context is the `userInfo` dictionary. Implement those properties: +The standard way to provide such context is the `userInfo` dictionary. Implement those properties: ```swift protocol FetchableRecord { @@ -2698,7 +2698,7 @@ protocol MutablePersistableRecord { } ``` -For example, here is how the Player type can customize its decoding: +For example, here is a Player type that customizes its decoding: ```swift // A key that holds a decoder's name @@ -2707,22 +2707,30 @@ let decoderName = CodingUserInfoKey(rawValue: "decoderName")! struct Player: FetchableRecord, Decodable { init(from decoder: Decoder) throws { // Print the decoder name - print(decoder.userInfo[decoderName]) + let decoderName = decoder.userInfo[decoderName] as? String + print("Decoded from \(decoderName ?? "nil")") ... } } +``` -// prints "JSON" +You can have a specific decoding from JSON... + +```swift +// prints "Decoded from JSON" let decoder = JSONDecoder() decoder.userInfo = [decoderName: "JSON"] -let player = try decoder.decode(Player.self, from: ...) +let player = try decoder.decode(Player.self, from: jsonData) +``` +... and another one from database rows: + +```swift extension Player: FetchableRecord { - // Customize the decoder name when decoding a database row - static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] + static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "database row"] } -// prints "Database" +// prints "Decoded from database row" let player = try Player.fetchOne(db, ...) ``` From c6b187229135daf3772c5bb7615513a0fd780671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 19:40:23 +0200 Subject: [PATCH 24/36] Documentation --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bb499d0ca..26646e370 100644 --- a/README.md +++ b/README.md @@ -2669,13 +2669,11 @@ This behavior can be overridden: ```swift protocol FetchableRecord { - static var databaseDateDecodingStrategy: - DatabaseDateDecodingStrategy { get } + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } } protocol MutablePersistableRecord { - static var databaseDateEncodingStrategy: - DatabaseDateEncodingStrategy { get } + static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } } ``` From fb209d88059d641e730bc5428cf3a893df6effcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 21:13:58 +0200 Subject: [PATCH 25/36] Decode UUID and NSUUID from both blobs and strings --- GRDB/Core/Support/Foundation/UUID.swift | 61 +++++++++++++++--- README.md | 4 +- Tests/GRDBTests/FoundationNSUUIDTests.swift | 70 ++++++++++---------- Tests/GRDBTests/FoundationUUIDTests.swift | 71 +++++++++++---------- 4 files changed, 131 insertions(+), 75 deletions(-) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 7deb4e2cf..373606f80 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -2,9 +2,7 @@ import Foundation #if !os(Linux) /// NSUUID adopts DatabaseValueConvertible -extension NSUUID : DatabaseValueConvertible { - - /// Returns a value that can be stored in the database. +extension NSUUID: DatabaseValueConvertible { public var databaseValue: DatabaseValue { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in @@ -13,15 +11,62 @@ extension NSUUID : DatabaseValueConvertible { } } - /// Returns an NSUUID initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else { + switch dbValue.storage { + case .blob(let data) where data.count == 16: + return data.withUnsafeBytes { + self.init(uuidBytes: $0) + } + case .string(let string): + return self.init(uuidString: string) + default: return nil } - return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self)) - } + } } #endif /// UUID adopts DatabaseValueConvertible -extension UUID : DatabaseValueConvertible { } +extension UUID: DatabaseValueConvertible { + public var databaseValue: DatabaseValue { + var uuid_t = uuid + return withUnsafeBytes(of: &uuid_t) { + Data(bytes: $0.baseAddress!, count: $0.count).databaseValue + } + } + + public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? { + switch dbValue.storage { + case .blob(let data) where data.count == 16: + return data.withUnsafeBytes { + UUID(uuid: $0.pointee) + } + case .string(let string): + return UUID(uuidString: string) + default: + return nil + } + } +} + +extension UUID: StatementColumnConvertible { + 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) + } + 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) + } + self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee) + default: + fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index) + } + } +} diff --git a/README.md b/README.md index 26646e370..51428677a 100644 --- a/README.md +++ b/README.md @@ -1313,7 +1313,9 @@ let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) ### UUID -**UUID** can be stored and fetched from the database just like other [values](#values). GRDB stores uuids as 16-bytes data blobs. +**UUID** can be stored and fetched from the database just like other [values](#values). + +GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F". ### Swift Enums diff --git a/Tests/GRDBTests/FoundationNSUUIDTests.swift b/Tests/GRDBTests/FoundationNSUUIDTests.swift index d80027b3e..cf251ac35 100644 --- a/Tests/GRDBTests/FoundationNSUUIDTests.swift +++ b/Tests/GRDBTests/FoundationNSUUIDTests.swift @@ -8,47 +8,51 @@ import XCTest #endif class FoundationNSUUIDTests: GRDBTestCase { - - func testNSUUIDDatabaseRoundTrip() throws { - let dbQueue = try makeDatabaseQueue() - func roundTrip(_ value: NSUUID) throws -> Bool { - guard let back = try dbQueue.inDatabase({ try NSUUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else { - XCTFail() - return false + private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws { + try makeDatabaseQueue().read { db in + if let expectedUUID = expectedUUID { + let decodedUUID = try NSUUID.fetchOne(db, "SELECT ?", arguments: [value]) + XCTAssertEqual(decodedUUID, expectedUUID) + } else if value == nil { + let decodedUUID = try Optional.fetchAll(db, "SELECT NULL")[0] + XCTAssertNil(decodedUUID) } - return back == value } - XCTAssertTrue(try roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)) - XCTAssertTrue(try roundTrip(NSUUID())) + let decodedUUID = NSUUID.fromDatabaseValue(value?.databaseValue ?? .null) + XCTAssertEqual(decodedUUID, expectedUUID) } - func testNSUUIDDatabaseValueRoundTrip() { - - func roundTrip(_ value: NSUUID) -> Bool { - let dbValue = value.databaseValue - guard let back = NSUUID.fromDatabaseValue(dbValue) else { - XCTFail("Failed to convert from DatabaseValue to NSUUID") - return false - } - return back.isEqual(value) + private func assertRoundTrip(_ uuid: UUID) throws { + let string = uuid.uuidString + var uuid_t = uuid.uuid + let data = withUnsafeBytes(of: &uuid_t) { + Data(bytes: $0.baseAddress!, count: $0.count) } - - XCTAssertTrue(roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)) - XCTAssertTrue(roundTrip(NSUUID())) + try assert(string, isDecodedAs: uuid as NSUUID) + try assert(string.lowercased(), isDecodedAs: uuid as NSUUID) + try assert(string.uppercased(), isDecodedAs: uuid as NSUUID) + try assert(uuid, isDecodedAs: uuid as NSUUID) + try assert(uuid as NSUUID, isDecodedAs: uuid as NSUUID) + try assert(data, isDecodedAs: uuid as NSUUID) } - func testNSUUIDFromDatabaseValueFailure() { - let databaseValue_Null = DatabaseValue.null - let databaseValue_Int64 = Int64(1).databaseValue - let databaseValue_Double = Double(100000.1).databaseValue - let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue - let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue - XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Null)) - XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Int64)) - XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Double)) - XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_String)) - XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_badBlob)) + func testSuccess() throws { + try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!) + try assertRoundTrip(UUID()) + try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: NSUUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")) } + func testFailure() throws { + try assert(nil, isDecodedAs: nil) + try assert(DatabaseValue.null, isDecodedAs: nil) + try assert(1, isDecodedAs: nil) + try assert(100000.1, isDecodedAs: nil) + try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil) + try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil) + try assert("foo", isDecodedAs: nil) + try assert("bar".data(using: .utf8)!, isDecodedAs: nil) + try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil) + try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil) + } } diff --git a/Tests/GRDBTests/FoundationUUIDTests.swift b/Tests/GRDBTests/FoundationUUIDTests.swift index 47f7ca6b4..7e33b041c 100644 --- a/Tests/GRDBTests/FoundationUUIDTests.swift +++ b/Tests/GRDBTests/FoundationUUIDTests.swift @@ -1,4 +1,5 @@ import XCTest +import Foundation #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE @@ -8,47 +9,51 @@ import XCTest #endif class FoundationUUIDTests: GRDBTestCase { - - func testUUIDDatabaseRoundTrip() throws { - let dbQueue = try makeDatabaseQueue() - func roundTrip(_ value: UUID) throws -> Bool { - guard let back = try dbQueue.inDatabase({ try UUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else { - XCTFail() - return false + private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws { + try makeDatabaseQueue().read { db in + if let expectedUUID = expectedUUID { + let decodedUUID = try UUID.fetchOne(db, "SELECT ?", arguments: [value]) + XCTAssertEqual(decodedUUID, expectedUUID) + } else if value == nil { + let decodedUUID = try Optional.fetchAll(db, "SELECT NULL")[0] + XCTAssertNil(decodedUUID) } - return back == value } - XCTAssertTrue(try roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)) - XCTAssertTrue(try roundTrip(UUID())) + let decodedUUID = UUID.fromDatabaseValue(value?.databaseValue ?? .null) + XCTAssertEqual(decodedUUID, expectedUUID) } - func testUUIDDatabaseValueRoundTrip() { - - func roundTrip(_ value: UUID) -> Bool { - let dbValue = value.databaseValue - guard let back = UUID.fromDatabaseValue(dbValue) else { - XCTFail("Failed to convert from DatabaseValue to UUID") - return false - } - return back == value + private func assertRoundTrip(_ uuid: UUID) throws { + let string = uuid.uuidString + var uuid_t = uuid.uuid + let data = withUnsafeBytes(of: &uuid_t) { + Data(bytes: $0.baseAddress!, count: $0.count) } - - XCTAssertTrue(roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)) - XCTAssertTrue(roundTrip(UUID())) + try assert(string, isDecodedAs: uuid) + try assert(string.lowercased(), isDecodedAs: uuid) + try assert(string.uppercased(), isDecodedAs: uuid) + try assert(uuid, isDecodedAs: uuid) + try assert(uuid as NSUUID, isDecodedAs: uuid) + try assert(data, isDecodedAs: uuid) } - func testUUIDFromDatabaseValueFailure() { - let databaseValue_Null = DatabaseValue.null - let databaseValue_Int64 = Int64(1).databaseValue - let databaseValue_Double = Double(100000.1).databaseValue - let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue - let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue - XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Null)) - XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Int64)) - XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Double)) - XCTAssertNil(UUID.fromDatabaseValue(databaseValue_String)) - XCTAssertNil(UUID.fromDatabaseValue(databaseValue_badBlob)) + func testSuccess() throws { + try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!) + try assertRoundTrip(UUID()) + try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")) } + func testFailure() throws { + try assert(nil, isDecodedAs: nil) + try assert(DatabaseValue.null, isDecodedAs: nil) + try assert(1, isDecodedAs: nil) + try assert(100000.1, isDecodedAs: nil) + try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil) + try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil) + try assert("foo", isDecodedAs: nil) + try assert("bar".data(using: .utf8)!, isDecodedAs: nil) + try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil) + try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil) + } } From 13f3e5ec0da28d3faa491edbd87b2cb561cc8c1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 21:14:32 +0200 Subject: [PATCH 26/36] Remove useless conversions from Int to Int32 --- GRDB/Core/DatabaseValue.swift | 12 ++++++------ GRDB/Core/Support/Foundation/Data.swift | 4 ++-- GRDB/Core/Support/Foundation/Date.swift | 2 +- .../Support/StandardLibrary/StandardLibrary.swift | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index acd23942e..6f440c663 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -121,18 +121,18 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. init(sqliteStatement: SQLiteStatement, index: Int32) { - switch sqlite3_column_type(sqliteStatement, Int32(index)) { + switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: storage = .null case SQLITE_INTEGER: - storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index))) + storage = .int64(sqlite3_column_int64(sqliteStatement, index)) case SQLITE_FLOAT: - storage = .double(sqlite3_column_double(sqliteStatement, Int32(index))) + storage = .double(sqlite3_column_double(sqliteStatement, index)) case SQLITE_TEXT: - storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index)))) + storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index))) case SQLITE_BLOB: - if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) { - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + if let bytes = sqlite3_column_blob(sqliteStatement, index) { + let count = Int(sqlite3_column_bytes(sqliteStatement, index)) storage = .blob(Data(bytes: bytes, count: count)) // copy bytes } else { storage = .blob(Data()) diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 80a49dfcd..ece9321ed 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -8,8 +8,8 @@ import Foundation /// Data is convertible to and from DatabaseValue. extension Data : DatabaseValueConvertible, StatementColumnConvertible { public init(sqliteStatement: SQLiteStatement, index: Int32) { - if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) { - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + if let bytes = sqlite3_column_blob(sqliteStatement, index) { + let count = Int(sqlite3_column_bytes(sqliteStatement, index)) self.init(bytes: bytes, count: count) // copy bytes } else { self.init() diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 2d8ea3bc7..ea9faa6d4 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -125,7 +125,7 @@ extension Date: StatementColumnConvertible { public init(sqliteStatement: SQLiteStatement, index: Int32) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_INTEGER, SQLITE_FLOAT: - self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, Int32(index))) + 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 { diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 976ae455b..e3438aacd 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -445,7 +445,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. public init(sqliteStatement: SQLiteStatement, index: Int32) { - self = String(cString: sqlite3_column_text(sqliteStatement, Int32(index))!) + self = String(cString: sqlite3_column_text(sqliteStatement, index)!) } /// Returns a value that can be stored in the database. From f70e9b3e39f7914bcdd4f271fefaa98ef679b1f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 21:14:51 +0200 Subject: [PATCH 27/36] Introduce DatabaseUUIDEncodingStrategy --- GRDB/Record/PersistableRecord+Encodable.swift | 15 +++++- GRDB/Record/PersistableRecord.swift | 48 ++++++++++++++++--- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 67caf4cf6..5da4cf610 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -126,9 +126,10 @@ private class RecordEncoder: Encoder { fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T : Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) + } else if let uuid = value as? UUID { + persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) } else if let value = value as? DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. - // This allows us to encode Date as String, for example. persist(value.databaseValue, forKey: key) } else { do { @@ -341,3 +342,15 @@ private extension DatabaseDateEncodingStrategy { } } } + +private extension DatabaseUUIDEncodingStrategy { + @inline(__always) + func encode(_ uuid: UUID) -> DatabaseValueConvertible? { + switch self { + case .deferredToUUID: + return uuid.databaseValue + case .string: + return uuid.uuidString + } + } +} diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 42086fdae..b9ffdabbe 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -402,6 +402,21 @@ public protocol MutablePersistableRecord : TableRecord { /// var registrationDate: Date // encoded as an epoch timestamp /// } static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } + + /// When the PersistableRecord type also adopts the standard Encodable + /// protocol, this property controls the encoding of UUID properties. + /// + /// Default value is .deferredToUUID + /// + /// For example: + /// + /// struct Player: PersistableProtocol, Encodable { + /// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string + /// + /// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + /// var uuid: UUID + /// } + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } } extension MutablePersistableRecord { @@ -409,12 +424,6 @@ extension MutablePersistableRecord { return [:] } - /// Returns a JSONEncoder with the following properties: - /// - /// - dataEncodingStrategy: .base64 - /// - dateEncodingStrategy: .millisecondsSince1970 - /// - nonConformingFloatEncodingStrategy: .throw - /// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+) public static func databaseJSONEncoder(for column: String) -> JSONEncoder { let encoder = JSONEncoder() encoder.dataEncodingStrategy = .base64 @@ -430,6 +439,10 @@ extension MutablePersistableRecord { public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return .deferredToDate } + + public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { + return .deferredToUUID + } } extension MutablePersistableRecord { @@ -1012,6 +1025,29 @@ public enum DatabaseDateEncodingStrategy { case custom((Date) -> DatabaseValueConvertible?) } +// MARK: - DatabaseUUIDEncodingStrategy + +/// DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also +/// adopt the standard Encodable protocol encode their UUID properties. +/// +/// For example: +/// +/// struct Player: PersistableProtocol, Encodable { +/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string +/// +/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" +/// var uuid: UUID +/// } +public enum DatabaseUUIDEncodingStrategy { + /// The strategy that uses formatting from the UUID type. + /// + /// It can encodes UUIDs as 16-bytes data blobs. + case deferredToUUID + + /// Encode UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + case string +} + // MARK: - DAO /// DAO takes care of PersistableRecord CRUD From e9b76bb1969e120b71937ffdb3e25e19dec42629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 22:16:29 +0200 Subject: [PATCH 28/36] Tests for DatabaseUUIDEncodingStrategy --- GRDB.xcodeproj/project.pbxproj | 6 ++ GRDBCipher.xcodeproj/project.pbxproj | 10 ++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ .../DatabaseUUIDEncodingStrategyTests.swift | 92 +++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 3a32ac2b2..3aeb059f2 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -330,6 +330,8 @@ 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 */; }; + 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; }; 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; @@ -945,6 +947,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 = ""; }; + 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; @@ -1285,6 +1288,7 @@ isa = PBXGroup; children = ( 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, + 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2696,6 +2700,7 @@ 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, + 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, @@ -2860,6 +2865,7 @@ 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, + 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 333564c8f..c64ca048b 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -375,6 +375,10 @@ 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 5670329F212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 567032A0212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 567032A1212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 567032A2212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; }; @@ -1039,6 +1043,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 = ""; }; + 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1329,6 +1334,7 @@ isa = PBXGroup; children = ( 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */, + 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2388,6 +2394,7 @@ 562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, 566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5670329F212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */, 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */, @@ -2552,6 +2559,7 @@ 562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, 566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 567032A0212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */, @@ -2828,6 +2836,7 @@ 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 567032A1212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */, @@ -2992,6 +3001,7 @@ 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 567032A2212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index f995a7d50..d51e5568d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -169,6 +169,8 @@ 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; + 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; @@ -705,6 +707,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 = ""; }; + 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; @@ -984,6 +987,7 @@ isa = PBXGroup; children = ( 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */, + 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, @@ -2057,6 +2061,7 @@ 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, + 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */, 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2333,6 +2338,7 @@ F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, + 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */, F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */, F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift new file mode 100644 index 000000000..351809d9a --- /dev/null +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -0,0 +1,92 @@ +import XCTest +import Foundation +#if GRDBCIPHER + @testable import GRDBCipher +#elseif GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +private protocol StrategyProvider { + static var strategy: DatabaseUUIDEncodingStrategy { get } +} + +private enum StrategyDeferredToUUID: StrategyProvider { + static let strategy: DatabaseUUIDEncodingStrategy = .deferredToUUID +} + +private enum StrategyString: StrategyProvider { + static let strategy: DatabaseUUIDEncodingStrategy = .string +} + +private struct RecordWithUUID: PersistableRecord, Encodable { + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy } + var uuid: UUID +} + +private struct RecordWithOptionalUUID: PersistableRecord, Encodable { + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy } + var uuid: UUID? +} + +class DatabaseUUIDEncodingStrategyTests: GRDBTestCase { + private func test( + record: T, + expectedStorage: DatabaseValue.Storage) + { + var container = PersistenceContainer() + record.encode(to: &container) + if let dbValue = container["uuid"]?.databaseValue { + XCTAssertEqual(dbValue.storage, expectedStorage) + } else { + XCTAssertEqual(.null, expectedStorage) + } + } + + private func test(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) { + test(record: RecordWithUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) + test(record: RecordWithOptionalUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) + } + + private func testNullEncoding(strategy: Strategy.Type) { + test(record: RecordWithOptionalUUID(uuid: nil), expectedStorage: .null) + } +} + +// MARK: - deferredToUUID + +extension DatabaseUUIDEncodingStrategyTests { + func testDeferredToUUID() { + testNullEncoding(strategy: StrategyDeferredToUUID.self) + + test( + strategy: StrategyDeferredToUUID.self, + encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + as: "abcdefghijklmnop".data(using: .utf8)!) + } +} + +// MARK: - string + +extension DatabaseUUIDEncodingStrategyTests { + func testString() { + testNullEncoding(strategy: StrategyString.self) + + test( + strategy: StrategyString.self, + encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + as: "61626364-6566-6768-696A-6B6C6D6E6F70") + + test( + strategy: StrategyString.self, + encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, + as: "56E7D8D3-E9E4-48B6-968E-8D102833AF00") + + let uuid = UUID() + test( + strategy: StrategyString.self, + encodesUUID: uuid, + as: uuid.uuidString.uppercased()) // Assert stable casing + } +} From edca38470e316817285fb84a4a006189dd738c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 22:24:26 +0200 Subject: [PATCH 29/36] Documentation --- README.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 51428677a..94d0b1b67 100644 --- a/README.md +++ b/README.md @@ -2609,7 +2609,7 @@ try dbQueue.write { db in ``` - [JSON Columns] -- [Date Coding Strategies] +- [Date and UUID Coding Strategies] - [The userInfo Dictionary] - [Tip: Use CodingKeys as Columns](#tip-use-codingkeys-as-columns) @@ -2663,11 +2663,13 @@ protocol MutablePersistableRecord { > :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) to accurately recognize changed records. -### Date Coding Strategies +### Date and UUID Coding Strategies -By default, [Codable Records] encode their date properties in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone (see [Date and DateComponents](#date-and-datecomponents) for more information about the default handling of dates). +By default, [Codable Records] encode and decode their Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters. -This behavior can be overridden: +To sum up: dates encode themselves in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F". + +Those behaviors can be overridden: ```swift protocol FetchableRecord { @@ -2676,10 +2678,11 @@ protocol FetchableRecord { protocol MutablePersistableRecord { static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } + static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html) and [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html) for more information. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseUUIDEncodingStrategy.html) for more information. ### The userInfo Dictionary @@ -2936,7 +2939,7 @@ GRDB records come with many default behaviors, that are designed to fit most sit [Codable Records] have a few extra options: - [JSON Columns]: control the format of JSON columns. -- [Date Coding Strategies]: control the format of Date properties in your Codable records. +- [Date and UUID Coding Strategies]: control the format of Date and UUID properties in your Codable records. - [The userInfo Dictionary]: adapt your Codable implementation for the database. @@ -7681,7 +7684,7 @@ This chapter has been renamed [Beyond FetchableRecord]. [Columns Selected by a Request]: #columns-selected-by-a-request [Conflict Resolution]: #conflict-resolution [Customizing the Persistence Methods]: #customizing-the-persistence-methods -[Date Coding Strategies]: #date-coding-strategies +[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests [The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key [The userInfo Dictionary]: #the-userinfo-dictionary From 209b3d0d37c32d23f9fc04134aee087a2cc61a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 23:32:38 +0200 Subject: [PATCH 30/36] Fix SPM and -O builds --- GRDB/Core/Support/Foundation/UUID.swift | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 373606f80..13bb3bca6 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,4 +1,9 @@ import Foundation +#if SWIFT_PACKAGE + import CSQLite +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER + import SQLite3 +#endif #if !os(Linux) /// NSUUID adopts DatabaseValueConvertible @@ -14,9 +19,19 @@ extension NSUUID: DatabaseValueConvertible { public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { switch dbValue.storage { case .blob(let data) where data.count == 16: - return data.withUnsafeBytes { - self.init(uuidBytes: $0) - } + // The code below works in debug configuration, but crashes in + // release configuration (Xcode 9.4.1) + +// return data.withUnsafeBytes { +// self.init(uuidBytes: $0) +// } + + // Workaround (involves a useless copy) + let buffer = UnsafeMutableBufferPointer.allocate(capacity: 16) + _ = data.copyBytes(to: buffer) + let uuid = self.init(uuidBytes: UnsafePointer(buffer.baseAddress!)) + buffer.deallocate() + return uuid case .string(let string): return self.init(uuidString: string) default: From ad11affd213580f15f06f9905efdee7ac4499195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Aug 2018 23:43:04 +0200 Subject: [PATCH 31/36] ISO8601: don't let user customize the formatter --- GRDB/Record/FetchableRecord+Decodable.swift | 23 ++++++++++++++----- GRDB/Record/FetchableRecord.swift | 4 ++-- GRDB/Record/PersistableRecord+Encodable.swift | 11 +++++++-- GRDB/Record/PersistableRecord.swift | 4 ++-- .../DatabaseDateDecodingStrategyTests.swift | 12 ++++------ .../DatabaseDateEncodingStrategyTests.swift | 6 +---- 6 files changed, 35 insertions(+), 25 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index bdedec508..b09a5dcfc 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -304,6 +304,13 @@ extension ColumnDecoder: SingleValueDecodingContainer { /// The error that triggers JSON decoding private struct JSONRequiredError: Error { } +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +fileprivate var iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter +}() + private extension DatabaseDateDecodingStrategy { @inline(__always) func decode(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { @@ -319,10 +326,10 @@ private extension DatabaseDateDecodingStrategy { case .millisecondsSince1970: let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) return Date(timeIntervalSince1970: timeInterval / 1000.0) - case .iso8601(let formatter): + case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = String(sqliteStatement: sqliteStatement, index: index) - guard let date = formatter.date(from: string) else { + guard let date = iso8601Formatter.date(from: string) else { fatalConversionError( to: Date.self, from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), @@ -399,10 +406,14 @@ private extension DatabaseDateDecodingStrategy { return TimeInterval .fromDatabaseValue(dbValue) .map { Date(timeIntervalSince1970: $0 / 1000.0) } - case .iso8601(let formatter): - return String - .fromDatabaseValue(dbValue) - .flatMap { formatter.date(from: $0) } + case .iso8601: + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + return String + .fromDatabaseValue(dbValue) + .flatMap { iso8601Formatter.date(from: $0) } + } else { + fatalError("ISO8601DateFormatter is unavailable on this platform.") + } case .formatted(let formatter): return String .fromDatabaseValue(dbValue) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 11d7def07..49d6ad720 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -444,9 +444,9 @@ public enum DatabaseDateDecodingStrategy { /// midnight UTC on 1 January 1970 case millisecondsSince1970 - /// Decodes a String, according to the provided formatter + /// Decodes dates according to the ISO 8601 standards @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - case iso8601(ISO8601DateFormatter) + case iso8601 /// Decodes a String, according to the provided formatter case formatted(DateFormatter) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 5da4cf610..231b71ea6 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -315,6 +315,13 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { } } +@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +fileprivate var iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter +}() + private extension DatabaseDateEncodingStrategy { @inline(__always) func encode(_ date: Date) -> DatabaseValueConvertible? { @@ -329,9 +336,9 @@ private extension DatabaseDateEncodingStrategy { return Int64(floor(1000.0 * date.timeIntervalSince1970)) case .secondsSince1970: return Int64(floor(date.timeIntervalSince1970)) - case .iso8601(let formatter): + case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { - return formatter.string(from: date) + return iso8601Formatter.string(from: date) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index b9ffdabbe..ff14837e4 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1014,9 +1014,9 @@ public enum DatabaseDateEncodingStrategy { /// midnight UTC on 1 January 1970 case millisecondsSince1970 - /// Encodes a String, according to the provided formatter + /// Encodes dates according to the ISO 8601 and RFC 3339 standards @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - case iso8601(ISO8601DateFormatter) + case iso8601 /// Encodes a String, according to the provided formatter case formatted(DateFormatter) diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index 4a587f3c1..d3e1a9c6b 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -29,12 +29,8 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -private enum StrategyIso8601Strategy: StrategyProvider { - static let strategy: DatabaseDateDecodingStrategy = .iso8601({ - let formatter = ISO8601DateFormatter() - formatter.formatOptions = .withInternetDateTime - return formatter - }()) +private enum StrategyIso8601: StrategyProvider { + static let strategy: DatabaseDateDecodingStrategy = .iso8601 } private enum StrategyFormatted: StrategyProvider { @@ -285,10 +281,10 @@ extension DatabaseDateDecodingStrategyTests { calendar.timeZone = TimeZone(secondsFromGMT: 0)! // Null - try testNullDecoding(db, strategy: StrategyIso8601Strategy.self) + try testNullDecoding(db, strategy: StrategyIso8601.self) // Date - try test(db, strategy: StrategyIso8601Strategy.self, databaseValue: "2018-08-19T17:18:07Z") { date in + try test(db, strategy: StrategyIso8601.self, databaseValue: "2018-08-19T17:18:07Z") { date in XCTAssertEqual(calendar.component(.year, from: date), 2018) XCTAssertEqual(calendar.component(.month, from: date), 8) XCTAssertEqual(calendar.component(.day, from: date), 19) diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index bde1c1707..b4f109185 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -34,11 +34,7 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { - static let strategy: DatabaseDateEncodingStrategy = .iso8601({ - let formatter = ISO8601DateFormatter() - formatter.formatOptions = .withInternetDateTime - return formatter - }()) + static let strategy: DatabaseDateEncodingStrategy = .iso8601 } private enum StrategyFormatted: StrategyProvider { From baee699591e08aadf9ff0c77df3f921041a6b288 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Aug 2018 06:58:18 +0200 Subject: [PATCH 32/36] CHANGELOG --- CHANGELOG.md | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec588d903..8ef000049 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Release Notes ## Next Version +This release focuses on enhancing the relationships between [Codable records](README.md#codable-records) and the database, with JSON columns, customized date formats, and better diagnostics when things go wrong. + +Other notable enhancements are: + +- Support for the FTS5 full-text engine when available in the operating system (iOS 11.4+ / macOS 10.13+ / watchOS 4.3+) + + ### Fixed - The `write` and `unsafeReentrantRead` DatabaseQueue methods used to have an incorrect `throws/rethrows` qualifier. @@ -10,14 +17,23 @@ Release Notes ### New -- [#397](https://github.com/groue/GRDB.swift/pull/397): Codable records: JSON encoding and decoding of codable record properties +- [#397](https://github.com/groue/GRDB.swift/pull/397) by [@gusrota](https://github.com/gusrota) and [@valexa](https://github.com/valexa): Codable records: JSON encoding and decoding of codable record properties - [#399](https://github.com/groue/GRDB.swift/pull/399): Codable records: customize the `userInfo` context dictionary, and the format of JSON columns +- [#403](https://github.com/groue/GRDB.swift/pull/403): Codable records: customize date and uuid format - [#401](https://github.com/groue/GRDB.swift/pull/401): Query Interface: set the selection and the fetched type in a single method call - [#393](https://github.com/groue/GRDB.swift/pull/393): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus. - [#384](https://github.com/groue/GRDB.swift/pull/384): Improve database value decoding diagnostics - Cursors of optimized values (Strint, Int, Date, etc.) have been renamed: FastDatabaseValueCursor and FastNullableDatabaseValueCursor replace the deprecated ColumnCursor and NullableColumnCursor. +### Documentation Diff + +- [Enabling FTS5 Support](README.md#enabling-fts5-support): Procedure for enabling FTS5 support in GRDB. +- [Codable Records](README.md#codable-records): Updated documentation for JSON columns, customized date and uuid formats, and other customization options. +- [Record Customization Options](README.md#record-customization-options): A new chapter that gathers all your customization options. +- [Fetching from Requests](README.md#fetching-from-requests): Enhanced documentation about requests that don't fetch their origin record (such as aggregates, or associated records). + + ### API diff Fixes: @@ -36,11 +52,14 @@ Enhancements to Codable support: ```diff protocol FetchableRecord { + static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get } ++ static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } + static func databaseJSONDecoder(for column: String) -> JSONDecoder } protocol MutablePersistableRecord: TableRecord { + static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get } ++ static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } ++ static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } + static func databaseJSONEncoder(for column: String) -> JSONEncoder } ``` @@ -74,14 +93,6 @@ Deprecations: ``` -### Documentation Diff - -- [Enabling FTS5 Support](README.md#enabling-fts5-support): Procedure for enabling FTS5 support in GRDB. -- [Codable Records](README.md#codable-records): Updated documentation for JSON columns, tips, and customization options. -- [Record Customization Options](README.md#record-customization-options): A new chapter that gather all your customization options. -- [Fetching from Requests](README.md#fetching-from-requests): Enhanced documentation about requests that don't fetch their origin record (such as aggregates, or associated records). - - ## 3.2.0 Released July 8, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.1.0...v3.2.0) From a386fb6580faf048a0211c64cc5a2267e859a0ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Aug 2018 08:17:57 +0200 Subject: [PATCH 33/36] Documentation --- Documentation/GRDB2MigrationGuide.md | 38 +++++++++++++++++++++++++++- README.md | 12 +++++++-- TODO.md | 11 -------- 3 files changed, 47 insertions(+), 14 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a68511405..617e3e2ff 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -160,9 +160,45 @@ struct Player: FetchableRecord, TableRecord { score = row[Columns.score] } } + +extension Player { + static func filter(name: String) -> QueryInterfaceRequest { + return filter(Columns.name == name) + } + + static var maximumScore: QueryInterfaceRequest { + return select(max(Columns.score), as: Int.self) + } +} ``` -GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type: +When your record adops the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns: + +```swift +// GRDB 3 +struct Player: Codable, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String + var score: Int + + // Add ColumnExpression conformance + private enum CodingKeys: String, CodingKey, ColumnExpression { + case id, name, score + } +} + +extension Player { + static func filter(name: String) -> QueryInterfaceRequest { + return filter(CodingKeys.name == name) + } + + static var maximumScore: QueryInterfaceRequest { + return select(max(CodingKeys.score), as: Int.self) + } +} +``` + +GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol whenever you define a custom column type: ```swift struct TypedColumn: ColumnExpression { diff --git a/README.md b/README.md index 94d0b1b67..af7294bf1 100644 --- a/README.md +++ b/README.md @@ -2608,10 +2608,18 @@ try dbQueue.write { db in } ``` +Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements: + +- A property prefers its database representation when it has one (all [values](#values) that adopt the [DatabaseValueConvertible](#custom-value-types) protocol). +- You can customize the encoding and decoding of dates and uuids. +- Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON. + +For more information about Codable records, see: + - [JSON Columns] - [Date and UUID Coding Strategies] - [The userInfo Dictionary] -- [Tip: Use CodingKeys as Columns](#tip-use-codingkeys-as-columns) +- [Tip: Use Coding Keys as Columns](#tip-use-coding-keys-as-columns) ### JSON Columns @@ -2738,7 +2746,7 @@ let player = try Player.fetchOne(db, ...) ``` -### Tip: Use CodingKeys as Columns +### Tip: Use Coding Keys as Columns If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can instruct GRDB to use those coding keys as database columns: diff --git a/TODO.md b/TODO.md index d5fdfbedd..2d25d9def 100644 --- a/TODO.md +++ b/TODO.md @@ -29,17 +29,6 @@ let lefts = Left.select(Left.Columns.id, Left.Columns.name) try Right.insert(lefts) ``` -- [ ] requestselect(..., as:) - - ```swift - // current - request - .select(Column("name")) - .asRequest(of: String.self) - - // new - request.select(Column("name"), as: String.self) - ``` - [ ] select values from a JSON column: ```swift From 8493984949e4a0574fae591a4c12d7be875ef5f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Aug 2018 14:32:43 +0200 Subject: [PATCH 34/36] Fix Typo --- Documentation/GRDB2MigrationGuide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 617e3e2ff..61cbcc078 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -172,7 +172,7 @@ extension Player { } ``` -When your record adops the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns: +When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns: ```swift // GRDB 3 From 5a8381b2826b4dc1ade1c147a647d242778a8cd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Aug 2018 14:39:46 +0200 Subject: [PATCH 35/36] Add missing attribution --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ef000049..cfe607ede 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ Other notable enhancements are: - [#399](https://github.com/groue/GRDB.swift/pull/399): Codable records: customize the `userInfo` context dictionary, and the format of JSON columns - [#403](https://github.com/groue/GRDB.swift/pull/403): Codable records: customize date and uuid format - [#401](https://github.com/groue/GRDB.swift/pull/401): Query Interface: set the selection and the fetched type in a single method call -- [#393](https://github.com/groue/GRDB.swift/pull/393): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus. +- [#393](https://github.com/groue/GRDB.swift/pull/393) by [@Marus](https://github.com/Marus): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus. - [#384](https://github.com/groue/GRDB.swift/pull/384): Improve database value decoding diagnostics - Cursors of optimized values (Strint, Int, Date, etc.) have been renamed: FastDatabaseValueCursor and FastNullableDatabaseValueCursor replace the deprecated ColumnCursor and NullableColumnCursor. From 0932e92fb46fb9b3e6cc2905ce31c3dcb9fd4541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Aug 2018 19:39:34 +0200 Subject: [PATCH 36/36] Documentation --- GRDB/Record/FetchableRecord.swift | 2 +- GRDB/Record/PersistableRecord.swift | 7 ++++--- README.md | 10 +++++++--- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 49d6ad720..3e54a2757 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -421,7 +421,7 @@ public enum DatabaseDateDecodingStrategy { /// (midnight UTC on January 1st, 1970). /// /// It decodes strings in the following formats, assuming UTC time zone. - /// Missing components are assumed to be zero. + /// Missing components are assumed to be zero: /// /// - `YYYY-MM-DD` /// - `YYYY-MM-DD HH:MM` diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index ff14837e4..750c7a547 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -995,7 +995,8 @@ extension PersistableRecord { public enum DatabaseDateEncodingStrategy { /// The strategy that uses formatting from the Date structure. /// - /// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone. + /// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the + /// UTC time zone. case deferredToDate /// Encodes a Double: the number of seconds between the date and @@ -1041,10 +1042,10 @@ public enum DatabaseDateEncodingStrategy { public enum DatabaseUUIDEncodingStrategy { /// The strategy that uses formatting from the UUID type. /// - /// It can encodes UUIDs as 16-bytes data blobs. + /// It encodes UUIDs as 16-bytes data blobs. case deferredToUUID - /// Encode UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + /// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" case string } diff --git a/README.md b/README.md index af7294bf1..4eddd8e72 100644 --- a/README.md +++ b/README.md @@ -2690,7 +2690,9 @@ protocol MutablePersistableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseUUIDEncodingStrategy.html) for more information. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. + +> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). ### The userInfo Dictionary @@ -2719,7 +2721,7 @@ struct Player: FetchableRecord, Decodable { init(from decoder: Decoder) throws { // Print the decoder name let decoderName = decoder.userInfo[decoderName] as? String - print("Decoded from \(decoderName ?? "nil")") + print("Decoded from \(decoderName ?? "unknown decoder")") ... } } @@ -2745,6 +2747,8 @@ extension Player: FetchableRecord { let player = try Player.fetchOne(db, ...) ``` +> :point_up: **Note**: make sure the `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties are explicitly declared as `[CodingUserInfoKey: Any]`. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo. + ### Tip: Use Coding Keys as Columns @@ -3898,7 +3902,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions