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] 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).