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