Merge pull request #499 from groue/feature/EndodableRecord

Extract EncodableRecord from MutablePersistableRecord
This commit is contained in:
Gwendal Roué authored and GitHub committed 2019-03-10 23:01:24 +01:00
commit 4ce6271f6d
18 files changed
+568 -486

No files matched your search

+2
View File
@@ -57,6 +57,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
- [#488](https://github.com/groue/GRDB.swift/pull/488): ValueObservation Cleanup
- [#490](https://github.com/groue/GRDB.swift/pull/490): Indirect Associations
- [#493](https://github.com/groue/GRDB.swift/pull/493): Bump SQLite to [3.27.2](https://www.sqlite.org/releaselog/3_27_2.html)
- [#499](https://github.com/groue/GRDB.swift/pull/499): Extract EncodableRecord from MutablePersistableRecord
### Breaking Changes
@@ -67,6 +68,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
### Documentation Diff
- [SQL Interpolation](Documentation/SQLInterpolation.md): this new document describes the new SQL interpolation feature.
- [Required Protocols](Documentation/AssociationsBasics.md#required-protocols) describes which protocols your record types have to conform to in order to use Associations features.
## 3.7.0
+66 -13
View File
@@ -2,6 +2,7 @@ GRDB Associations
=================
- [Associations Benefits]
- [Required Protocols]
- [The Types of Associations]
- [BelongsTo]
- [HasMany]
@@ -46,12 +47,12 @@ GRDB Associations
Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book:
```swift
struct Author: TableRecord, FetchableRecord {
struct Author {
var id: Int64
var name: String
}
struct Book: TableRecord, FetchableRecord {
struct Book {
var id: Int64
var authorId: Int64?
var title: String
@@ -121,6 +122,52 @@ let bookInfos = BookInfo.fetchAll(db, request)
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter.
## Required Protocols
**Associations are available on types that adopt the necessary supporting protocols.**
When your type is a subclass of the [Record class], all necessary protocols are already setup and ready.
Otherwise:
- **[TableRecord]** is fundamental. This is the one that lets you declare associations between record types:
```swift
extension Author: TableRecord {
static let books = hasMany(Book.self)
}
extension Book: TableRecord {
static let author = belongsTo(Author.self)
}
```
- **[EncodableRecord]** adds the `request(for:)` method, as below:
```swift
extension Book: EncodableRecord {
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
}
func encode(to container: inout PersistenceContainer) {
container["authorId"] = self.authorId
...
}
}
// Fetch a book's author:
let book: Book = ...
let author: Author? = try dbQueue.read { db in
try book.author.fetchOne(db)
}
```
A record type often conforms to EncodableRecord via the [PersistableRecord] protocol. However PersistableRecord grants persistence methods that are able to insert, update, and delete rows in the database. When you want to profit from associations and keep your record type read-only, all you need is EncodableRecord.
EncodableRecord conformance can be derived from the standard Encodable protocol, so that you do not have to write the `encode(to:)` method. See [Codable Records] for more information.
The Types of Associations
=========================
@@ -136,6 +183,7 @@ An association declares a link from a record type to another, as in "one book **
Each one of the three types of associations is appropriate for a particular database situation.
- [Required Protocols]
- [BelongsTo]
- [HasMany]
- [HasOne]
@@ -152,7 +200,7 @@ The **BelongsTo** association sets up a one-to-one connection from a record type
For example, if your application includes authors and books, and each book is assigned its author, you'd declare the `Book.author` association as below, with its companion property:
```swift
struct Book: TableRecord {
struct Book: TableRecord, EncodableRecord {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
@@ -186,7 +234,7 @@ The **HasMany** association indicates a one-to-many connection between two recor
For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the `Author.books` association as below, with its companion property:
```swift
struct Author: TableRecord {
struct Author: TableRecord, EncodableRecord {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
@@ -219,7 +267,7 @@ The **HasOne** association, like BelongsTo, sets up a one-to-one connection from
For example, if your application has one database table for countries, and another for their demographic profiles, you'd declare the `Country.demographics` association as below, with its companion property:
```swift
struct Country: TableRecord {
struct Country: TableRecord, EncodableRecord {
static let demographics = hasOne(Demographics.self)
var demographics: QueryInterfaceRequest<Demographics> {
return request(for: Country.demographics)
@@ -251,7 +299,7 @@ See [Convention for the HasOne Association] for some sample code that defines th
The **HasManyThrough** association is often used to set up a many-to-many connection with another record. This association indicates that the declaring record can be matched with zero or more instances of another record by proceeding through a third record. For example, consider the practice of passport delivery. The relevant association declarations could look like this:
```swift
struct Country: TableRecord {
struct Country: TableRecord, EncodableRecord {
static let passports = hasMany(Passport.self)
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
var citizens: QueryInterfaceRequest<Citizen> {
@@ -264,7 +312,7 @@ struct Passport: TableRecord {
static let citizen = belongsTo(Citizen.self)
}
struct Citizen: TableRecord {
struct Citizen: TableRecord, EncodableRecord {
static let passports = hasMany(Passport.self)
static let countries = hasMany(Country.self, through: passports, using: Passport.country)
var countries: QueryInterfaceRequest<Country> {
@@ -314,7 +362,7 @@ struct Document: TableRecord {
A **HasOneThrough** association sets up a one-to-one connection with another record. This association indicates that the declaring record can be matched with one instance of another record by proceeding through a third record. For example, if each book belongs to a library, and each library has one address, then one knows where the book should be returned to:
```swift
struct Book: TableRecord {
struct Book: TableRecord, EncodableRecord {
static let library = belongsTo(Library.self)
static let returnAddress = hasOne(Address.self, through: library, using: library.address)
var returnAddress: QueryInterfaceRequest<Address> {
@@ -474,7 +522,7 @@ See [The Structure of a Joined Request] for more information.
## Convention for the BelongsTo Association
```swift
extension Book: TableRecord {
extension Book: TableRecord, EncodableRecord {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
@@ -536,7 +584,7 @@ See [Foreign Keys] for more information.
## Convention for the HasMany Association
```swift
extension Author: TableRecord {
extension Author: TableRecord, EncodableRecord {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
@@ -598,7 +646,7 @@ See [Foreign Keys] for more information.
## Convention for the HasOne Association
```swift
extension Country: TableRecord {
extension Country: TableRecord, EncodableRecord {
static let demographics = hasOne(Demographics.self)
var demographics: QueryInterfaceRequest<Demographics> {
return request(for: Country.demographics)
@@ -756,7 +804,7 @@ Fetch requests do not visit the database until you fetch values from them. This
For example, given a `Book.author` **[BelongsTo]** association, you can build a request for the author of a book. In the example below, we return this request from the `Book.author` property:
```swift
struct Book: PersistableRecord {
struct Book: TableRecord, EncodableRecord {
static let author = belongsTo(Author.self)
/// The request for a book's author
@@ -776,7 +824,7 @@ let author = try book.author.fetchOne(db) // Author?
**[HasOne]**, **[HasMany]**, **[HasOneThrough]**, and **[HasManyThrough]** associations can also build requests for associated records. For example:
```swift
struct Author: PersistableRecord {
struct Author: TableRecord, EncodableRecord {
static let books = hasMany(Book.self)
/// The request for an author's books
@@ -2073,6 +2121,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Associations Benefits]: #associations-benefits
[Required Protocols]: #required-protocols
[BelongsTo]: #belongsto
[HasMany]: #hasmany
[HasOne]: #hasone
@@ -2120,3 +2169,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[association requests]: #building-requests-from-associations
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Fetching Aggregated Values]: ../README.md#fetching-aggregated-values
[Record class]: ../README.md#record-class
[EncodableRecord]: ../README.md#persistablerecord-protocol
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Codable Records]: ../README.md#codable-records
+16 -8
View File
@@ -82,6 +82,9 @@
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; };
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; };
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; };
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172947223533F40006E219 /* EncodableRecord.swift */; };
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172947223533F40006E219 /* EncodableRecord.swift */; };
56172950223533F40006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172947223533F40006E219 /* EncodableRecord.swift */; };
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; };
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; };
56176C5B1EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; };
@@ -423,9 +426,9 @@
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
@@ -947,6 +950,7 @@
5615B287222B17BF00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = "<group>"; };
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
56172947223533F40006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -1077,7 +1081,7 @@
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = "<group>"; };
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = "<group>"; };
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = "<group>"; };
5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = "<group>"; };
5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = "<group>"; };
@@ -1894,12 +1898,13 @@
56A2389F1B9C753B0082EB20 /* Record */ = {
isa = PBXGroup;
children = (
56172947223533F40006E219 /* EncodableRecord.swift */,
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */,
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */,
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -2528,6 +2533,7 @@
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */,
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
@@ -2569,7 +2575,7 @@
566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */,
5659F4A61EA8D997004A4992 /* Result.swift in Sources */,
5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
565490C31D5AE236005622CB /* RowAdapter.swift in Sources */,
5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
5659F49E1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -2656,7 +2662,7 @@
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
@@ -2698,6 +2704,7 @@
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */,
564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */,
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
5657AB121D10899D006283EF /* URL.swift in Sources */,
@@ -3197,12 +3204,13 @@
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
@@ -471,7 +471,7 @@ public /* TODO: internal */ struct SQLAssociation {
return nextImpl.relation(from: relation, joinOperator: joinOperator)
}
/// Support for MutablePersistableRecord.request(for:).
/// Support for (TableRecord & EncodableRecord).request(for:).
///
/// Returns a "reversed" relation:
///
@@ -92,12 +92,12 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
}
}
extension MutablePersistableRecord {
extension TableRecord where Self: EncodableRecord {
/// Creates a request that fetches the associated record(s).
///
/// For example:
///
/// struct Team: {
/// struct Team: TableRecord, EncodableRecord {
/// static let players = hasMany(Player.self)
/// var players: QueryInterfaceRequest<Player> {
/// return request(for: Team.players)
@@ -1,6 +1,6 @@
import Foundation
extension MutablePersistableRecord where Self: Encodable {
extension EncodableRecord where Self: Encodable {
public func encode(to container: inout PersistenceContainer) {
let encoder = RecordEncoder<Self>(persistenceContainer: container)
try! encode(to: encoder)
@@ -11,7 +11,7 @@ extension MutablePersistableRecord where Self: Encodable {
// MARK: - RecordEncoder
/// The encoder that encodes a record into GRDB's PersistenceContainer
private class RecordEncoder<Record: MutablePersistableRecord>: Encoder {
private class RecordEncoder<Record: EncodableRecord>: Encoder {
var codingPath: [CodingKey] { return [] }
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
private var _persistenceContainer: PersistenceContainer
@@ -162,7 +162,7 @@ private class RecordEncoder<Record: MutablePersistableRecord>: Encoder {
// MARK: - ColumnEncoder
/// The encoder that encodes into a database column
private class ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
private class ColumnEncoder<Record: EncodableRecord>: Encoder {
var recordEncoder: RecordEncoder<Record>
var key: CodingKey
var codingPath: [CodingKey] { return [key] }
@@ -225,7 +225,7 @@ extension ColumnEncoder: SingleValueEncodingContainer {
private struct JSONRequiredError: Error { }
/// The encoder that always ends up with a JSONRequiredError
private struct JSONRequiredEncoder<Record: MutablePersistableRecord>: Encoder {
private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
+387
View File
@@ -0,0 +1,387 @@
import Foundation // For JSONEncoder
/// Types that adopt EncodableRecord can be encoded into the database.
public protocol EncodableRecord {
/// Encodes the record into database values.
///
/// Store in the *container* argument all values that should be stored in
/// the columns of the database table (see databaseTableName()).
///
/// Primary key columns, if any, must be included.
///
/// struct Player: EncodableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
func encode(to container: inout PersistenceContainer)
// MARK: - Customizing the Format of Database Columns
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, you can use this dictionary to customize the encoding process
/// into database rows.
///
/// For example:
///
/// // A key that holds a encoder's name
/// let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
///
/// struct Player: PersistableRecord, Encodable {
/// // Customize the encoder name when encoding a database row
/// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
///
/// func encode(to encoder: Encoder) throws {
/// // Print the encoder name
/// print(encoder.userInfo[encoderName])
/// ...
/// }
/// }
///
/// let player = Player(...)
///
/// // prints "Database"
/// try player.insert(db)
///
/// // prints "JSON"
/// let encoder = JSONEncoder()
/// encoder.userInfo = [encoderName: "JSON"]
/// let data = try encoder.encode(player)
static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, this method controls the encoding process of nested properties
/// into JSON database columns.
///
/// The default implementation returns a JSONEncoder with the
/// following properties:
///
/// - dataEncodingStrategy: .base64
/// - dateEncodingStrategy: .millisecondsSince1970
/// - nonConformingFloatEncodingStrategy: .throw
/// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
///
/// You can override those defaults:
///
/// struct Achievement: Encodable {
/// var name: String
/// var date: Date
/// }
///
/// struct Player: Encodable, PersistableRecord {
/// // stored in a JSON column
/// var achievements: [Achievement]
///
/// static func databaseJSONEncoder(for column: String) -> JSONEncoder {
/// let encoder = JSONEncoder()
/// encoder.dateEncodingStrategy = .iso8601
/// return encoder
/// }
/// }
static func databaseJSONEncoder(for column: String) -> JSONEncoder
/// When the EncodableRecord type also adopts the standard Encodable
/// 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 }
/// When the EncodableRecord 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 EncodableRecord {
public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] {
return [:]
}
public static func databaseJSONEncoder(for column: String) -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, *) {
// guarantee some stability in order to ease record comparison
encoder.outputFormatting = .sortedKeys
}
return encoder
}
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
return .deferredToDate
}
public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy {
return .deferredToUUID
}
}
extension EncodableRecord {
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
public var databaseDictionary: [String: DatabaseValue] {
return Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null }
}
}
extension EncodableRecord {
// MARK: - Record Comparison
/// Returns a boolean indicating whether this record and the other record
/// have the same database representation.
public func databaseEquals(_ record: Self) -> Bool {
return PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil
}
/// A dictionary of values changed from the other record.
///
/// Its keys are column names. Its values come from the other record.
///
/// Note that this method is not symmetrical, not only in terms of values,
/// but also in terms of columns. When the two records don't define the
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges<Record: EncodableRecord>(from record: Record) -> [String: DatabaseValue] {
return Dictionary(uniqueKeysWithValues: PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)))
}
}
// MARK: - PersistenceContainer
/// Use persistence containers in the `encode(to:)` method of your
/// encodable records:
///
/// struct Player: EncodableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
public struct PersistenceContainer {
// fileprivate for Row(_:PersistenceContainer)
// The ordering of the OrderedDictionary helps generating always the same
// SQL queries, and hit the statement cache.
@usableFromInline var storage: OrderedDictionary<String, DatabaseValueConvertible?>
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript(_ column: String) -> DatabaseValueConvertible? {
get { return storage[column] ?? nil }
set { storage.updateValue(newValue, forKey: column) }
}
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
get { return self[column.name] }
set { self[column.name] = newValue }
}
init() {
storage = OrderedDictionary()
}
init(minimumCapacity: Int) {
storage = OrderedDictionary(minimumCapacity: minimumCapacity)
}
/// Convenience initializer from a record
init<Record: EncodableRecord>(_ record: Record) {
self.init()
record.encode(to: &self)
}
/// Columns stored in the container, ordered like values.
var columns: [String] {
return Array(storage.keys)
}
/// Values stored in the container, ordered like columns.
var values: [DatabaseValueConvertible?] {
return Array(storage.values)
}
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
///
/// :nodoc:
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
get {
if let value = storage[column] {
return value
}
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value
}
return nil
}
set {
if storage[column] != nil {
storage[column] = newValue
return
}
let lowercaseColumn = column.lowercased()
for key in storage.keys where key.lowercased() == lowercaseColumn {
storage[key] = newValue
return
}
storage[column] = newValue
}
}
// Returns nil if column is not defined
func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? {
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value?.databaseValue ?? .null
}
return nil
}
var isEmpty: Bool {
return storage.isEmpty
}
/// An iterator over the (column, value) pairs
func makeIterator() -> IndexingIterator<OrderedDictionary<String, DatabaseValueConvertible?>> {
return storage.makeIterator()
}
func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = container[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
if newDbValue != oldDbValue {
return (column, oldDbValue)
}
}
return nil
}
}
}
extension Row {
convenience init<Record: EncodableRecord>(_ record: Record) {
self.init(PersistenceContainer(record))
}
convenience init(_ container: PersistenceContainer) {
self.init(Dictionary(container.storage))
}
}
// MARK: - DatabaseDateEncodingStrategy
/// DatabaseDateEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their date properties.
///
/// For example:
///
/// struct Player: EncodableRecord, 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.
///
/// 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 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
/// Encodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> DatabaseValueConvertible?)
}
// MARK: - DatabaseUUIDEncodingStrategy
/// DatabaseUUIDEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their UUID properties.
///
/// For example:
///
/// struct Player: EncodableProtocol, 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 encodes UUIDs as 16-bytes data blobs.
case deferredToUUID
/// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
case string
}
+1 -1
View File
@@ -879,7 +879,7 @@ extension FetchedRecordsController {
}
}
extension FetchedRecordsController where Record: MutablePersistableRecord {
extension FetchedRecordsController where Record: EncodableRecord {
/// Returns the indexPath of a given record.
///
+12 -397
View File
@@ -1,5 +1,3 @@
import Foundation
extension Database.ConflictResolution {
@usableFromInline
var invalidatesLastInsertedRowID: Bool {
@@ -13,8 +11,6 @@ extension Database.ConflictResolution {
}
}
// MARK: - PersistenceError
/// An error thrown by a type that adopts PersistableRecord.
public enum PersistenceError: Error, CustomStringConvertible {
@@ -38,141 +34,6 @@ extension PersistenceError {
}
}
// MARK: - PersistenceContainer
/// Use persistence containers in the `encode(to:)` method of your
/// encodable records:
///
/// struct Player : MutablePersistableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
public struct PersistenceContainer {
// fileprivate for Row(_:PersistenceContainer)
// The ordering of the OrderedDictionary helps generating always the same
// SQL queries, and hit the statement cache.
@usableFromInline var storage: OrderedDictionary<String, DatabaseValueConvertible?>
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript(_ column: String) -> DatabaseValueConvertible? {
get { return storage[column] ?? nil }
set { storage.updateValue(newValue, forKey: column) }
}
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
get { return self[column.name] }
set { self[column.name] = newValue }
}
init() {
storage = OrderedDictionary()
}
init(minimumCapacity: Int) {
storage = OrderedDictionary(minimumCapacity: minimumCapacity)
}
/// Convenience initializer from a record
init<Record: MutablePersistableRecord>(_ record: Record) {
self.init()
record.encode(to: &self)
}
/// Convenience initializer from a database connection and a record
init<Record: MutablePersistableRecord>(_ db: Database,_ record: Record) throws {
let databaseTableName = type(of: record).databaseTableName
let columnCount = try db.columns(in: databaseTableName).count
self.init(minimumCapacity: columnCount)
record.encode(to: &self)
}
/// Columns stored in the container, ordered like values.
var columns: [String] {
return Array(storage.keys)
}
/// Values stored in the container, ordered like columns.
var values: [DatabaseValueConvertible?] {
return Array(storage.values)
}
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
///
/// :nodoc:
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
get {
if let value = storage[column] {
return value
}
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value
}
return nil
}
set {
if storage[column] != nil {
storage[column] = newValue
return
}
let lowercaseColumn = column.lowercased()
for key in storage.keys where key.lowercased() == lowercaseColumn {
storage[key] = newValue
return
}
storage[column] = newValue
}
}
// Returns nil if column is not defined
func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? {
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value?.databaseValue ?? .null
}
return nil
}
var isEmpty: Bool {
return storage.isEmpty
}
/// An iterator over the (column, value) pairs
func makeIterator() -> IndexingIterator<OrderedDictionary<String, DatabaseValueConvertible?>> {
return storage.makeIterator()
}
}
extension Row {
convenience init<Record: MutablePersistableRecord>(_ record: Record) {
self.init(PersistenceContainer(record))
}
convenience init(_ container: PersistenceContainer) {
self.init(Dictionary(container.storage))
}
}
// MARK: - MutablePersistableRecord
/// The MutablePersistableRecord protocol uses this type in order to handle SQLite
/// conflicts when records are inserted or updated.
///
@@ -194,7 +55,7 @@ public struct PersistenceConflictPolicy {
}
/// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted.
public protocol MutablePersistableRecord : TableRecord {
public protocol MutablePersistableRecord : EncodableRecord, TableRecord {
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
///
@@ -209,28 +70,6 @@ public protocol MutablePersistableRecord : TableRecord {
/// See https://www.sqlite.org/lang_conflict.html
static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
/// Defines the values persisted in the database.
///
/// Store in the *container* argument all values that should be stored in
/// the columns of the database table (see databaseTableName()).
///
/// Primary key columns, if any, must be included.
///
/// struct Player : MutablePersistableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
func encode(to container: inout PersistenceContainer)
/// Notifies the record that it was succesfully inserted.
///
/// Do not call this method directly: it is called for you, in a protected
@@ -336,134 +175,6 @@ public protocol MutablePersistableRecord : TableRecord {
/// - returns: Whether the primary key matches a row in the database.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
func exists(_ db: Database) throws -> Bool
// MARK: - Customizing the Format of Database Columns
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, you can use this dictionary to customize the encoding process
/// into database rows.
///
/// For example:
///
/// // A key that holds a encoder's name
/// let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
///
/// // A PersistableRecord + Encodable record
/// struct Player: PersistableRecord, Encodable {
/// // Customize the encoder name when encoding a database row
/// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
///
/// func encode(to encoder: Encoder) throws {
/// // Print the encoder name
/// print(encoder.userInfo[encoderName])
/// ...
/// }
/// }
///
/// let player = Player(...)
///
/// // prints "Database"
/// try player.insert(db)
///
/// // prints "JSON"
/// let encoder = JSONEncoder()
/// encoder.userInfo = [encoderName: "JSON"]
/// let data = try encoder.encode(player)
static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, this method controls the encoding process of nested properties
/// into JSON database columns.
///
/// The default implementation returns a JSONEncoder with the
/// following properties:
///
/// - dataEncodingStrategy: .base64
/// - dateEncodingStrategy: .millisecondsSince1970
/// - nonConformingFloatEncodingStrategy: .throw
/// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
///
/// You can override those defaults:
///
/// struct Achievement: Encodable {
/// var name: String
/// var date: Date
/// }
///
/// struct Player: Encodable, PersistableRecord {
/// // stored in a JSON column
/// var achievements: [Achievement]
///
/// static func databaseJSONEncoder(for column: String) -> JSONEncoder {
/// let encoder = JSONEncoder()
/// encoder.dateEncodingStrategy = .iso8601
/// return encoder
/// }
/// }
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
///
/// 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 }
/// 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 {
public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] {
return [:]
}
public static func databaseJSONEncoder(for column: String) -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, *) {
// guarantee some stability in order to ease record comparison
encoder.outputFormatting = .sortedKeys
}
return encoder
}
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
return .deferredToDate
}
public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy {
return .deferredToUUID
}
}
extension MutablePersistableRecord {
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
public var databaseDictionary: [String: DatabaseValue] {
return Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null }
}
}
extension MutablePersistableRecord {
@@ -619,43 +330,9 @@ extension MutablePersistableRecord {
// MARK: - Record Comparison
/// Returns a boolean indicating whether this record and the other record
/// have the same database representation.
public func databaseEquals(_ record: Self) -> Bool {
return databaseChangesIterator(from: PersistenceContainer(record)).next() == nil
}
/// A dictionary of values changed from the other record.
///
/// Its keys are column names. Its values come from the other record.
///
/// Note that this method is not symmetrical, not only in terms of values,
/// but also in terms of columns. When the two records don't define the
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges<Record: MutablePersistableRecord>(from record: Record) -> [String: DatabaseValue] {
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record)))
}
private func databaseChangesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = container[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
if newDbValue != oldDbValue {
return (column, oldDbValue)
}
}
return nil
}
}
@discardableResult
fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool {
let changes = databaseChangesIterator(from: container)
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return false
@@ -816,7 +493,6 @@ extension MutablePersistableRecord where Self: AnyObject {
try change(self)
return try updateChanges(db, from: container)
}
}
extension MutablePersistableRecord {
@@ -1069,79 +745,18 @@ extension PersistableRecord {
}
}
// MARK: - DatabaseDateEncodingStrategy
/// 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.
///
/// 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 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
/// Encodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
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 encodes UUIDs as 16-bytes data blobs.
case deferredToUUID
/// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
case string
}
// MARK: - DAO
extension PersistenceContainer {
/// Convenience initializer from a database connection and a record
init<Record: EncodableRecord & TableRecord>(_ db: Database,_ record: Record) throws {
let databaseTableName = type(of: record).databaseTableName
let columnCount = try db.columns(in: databaseTableName).count
self.init(minimumCapacity: columnCount)
record.encode(to: &self)
}
}
/// DAO takes care of PersistableRecord CRUD
@usableFromInline
final class DAO<Record: MutablePersistableRecord> {
+12 -6
View File
@@ -132,6 +132,8 @@
561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; };
5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; };
5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; };
5617295B223534260006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172959223534260006E219 /* EncodableRecord.swift */; };
5617295C223534260006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172959223534260006E219 /* EncodableRecord.swift */; };
56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; };
56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; };
56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; };
@@ -557,8 +559,8 @@
5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; };
5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; };
@@ -1087,6 +1089,7 @@
5615B27F222B17A100061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = "<group>"; };
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
56172959223534260006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -1214,7 +1217,7 @@
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = "<group>"; };
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = "<group>"; };
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = "<group>"; };
5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = "<group>"; };
5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = "<group>"; };
@@ -1994,12 +1997,13 @@
56A2389F1B9C753B0082EB20 /* Record */ = {
isa = PBXGroup;
children = (
56172959223534260006E219 /* EncodableRecord.swift */,
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */,
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */,
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -2411,11 +2415,12 @@
564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */,
5659F4991EA8D989004A4992 /* Pool.swift in Sources */,
5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */,
5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */,
5617295C223534260006E219 /* EncodableRecord.swift in Sources */,
5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
5698AD191DAAD17B0056AF8C /* FTS5Tokenizer.swift in Sources */,
56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
@@ -2916,11 +2921,12 @@
564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */,
5659F49C1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */,
5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */,
5617295B223534260006E219 /* EncodableRecord.swift in Sources */,
5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
5698AD1A1DAAD17C0056AF8C /* FTS5Tokenizer.swift in Sources */,
56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
+12 -6
View File
@@ -40,6 +40,8 @@
561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; };
5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; };
5616AAF7207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; };
561729552235340E0006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561729532235340E0006E219 /* EncodableRecord.swift */; };
561729562235340E0006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561729532235340E0006E219 /* EncodableRecord.swift */; };
56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
@@ -247,8 +249,8 @@
5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; };
5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; };
5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; };
5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; };
@@ -705,6 +707,7 @@
5615B284222B17B900061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = "<group>"; };
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
5616AAF4207CD59300AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
561729532235340E0006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -830,7 +833,7 @@
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = "<group>"; };
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = "<group>"; };
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = "<group>"; };
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = "<group>"; };
5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = "<group>"; };
5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = "<group>"; };
@@ -1584,12 +1587,13 @@
56A2389F1B9C753B0082EB20 /* Record */ = {
isa = PBXGroup;
children = (
561729532235340E0006E219 /* EncodableRecord.swift */,
5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */,
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */,
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -2027,7 +2031,7 @@
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */,
5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
@@ -2035,6 +2039,7 @@
5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */,
5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
561729552235340E0006E219 /* EncodableRecord.swift in Sources */,
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */,
@@ -2343,7 +2348,7 @@
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */,
5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
@@ -2351,6 +2356,7 @@
5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */,
5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
561729562235340E0006E219 /* EncodableRecord.swift in Sources */,
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */,
+12 -7
View File
@@ -2526,27 +2526,32 @@ try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citi
## PersistableRecord Protocol
**GRDB provides two protocols that let adopting types create, update, and delete rows in the database:**
**GRDB record types can create, update, and delete rows in the database.**
Those abilities are granted by three protocols:
```swift
protocol MutablePersistableRecord : TableRecord {
// Defines how a record encodes itself into the database
protocol EncodableRecord {
/// Defines the values persisted in the database
func encode(to container: inout PersistenceContainer)
}
// Adds persistence methods
protocol MutablePersistableRecord: TableRecord, EncodableRecord {
/// Optional method that lets your adopting type store its rowID upon
/// successful insertion. Don't call it directly: it is called for you.
mutating func didInsert(with rowID: Int64, for column: String?)
}
```
```swift
protocol PersistableRecord : MutablePersistableRecord {
// Adds immutability
protocol PersistableRecord: MutablePersistableRecord {
/// Non-mutating version of the optional didInsert(with:for:)
func didInsert(with rowID: Int64, for column: String?)
}
```
Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other:
Yes, three protocols instead of one. Here is how you pick one or the other:
- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(with:for:)` if the database table has an auto-incremented primary key.
@@ -11,7 +11,7 @@ import XCTest
class AssociationBelongsToSQLTests: GRDBTestCase {
func testSingleColumnNoForeignKeyNoPrimaryKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentId"] = 1
@@ -95,7 +95,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testSingleColumnNoForeignKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentId"] = 1
@@ -179,7 +179,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testSingleColumnSingleForeignKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentId"] = 1
@@ -292,7 +292,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testSingleColumnSeveralForeignKeys() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parent1Id"] = 1
@@ -436,7 +436,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testCompoundColumnNoForeignKeyNoPrimaryKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentA"] = 1
@@ -494,7 +494,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testCompoundColumnNoForeignKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentA"] = 1
@@ -582,7 +582,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testCompoundColumnSingleForeignKey() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parentA"] = 1
@@ -700,7 +700,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
func testCompoundColumnSeveralForeignKeys() throws {
struct Child : TableRecord, MutablePersistableRecord {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "children"
func encode(to container: inout PersistenceContainer) {
container["parent1A"] = 1
@@ -15,7 +15,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -90,7 +90,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -164,7 +164,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -262,7 +262,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -385,7 +385,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -438,7 +438,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -516,7 +516,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -619,7 +619,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -12,7 +12,7 @@ import XCTest
class AssociationHasManyThroughSQLTests: GRDBTestCase {
func testBelongsToHasMany() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -52,7 +52,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
func testHasOneHasMany() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -92,7 +92,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
func testHasManyBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -132,7 +132,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
func testHasManyHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -15,7 +15,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -90,7 +90,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -164,7 +164,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -262,7 +262,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
@@ -385,7 +385,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -438,7 +438,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -516,7 +516,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -619,7 +619,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
static let databaseTableName = "children"
}
struct Parent : TableRecord, MutablePersistableRecord {
struct Parent : TableRecord, EncodableRecord {
static let databaseTableName = "parents"
func encode(to container: inout PersistenceContainer) {
container["a"] = 1
@@ -12,7 +12,7 @@ import XCTest
class AssociationHasOneThroughSQLTests: GRDBTestCase {
func testBelongsToBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -52,7 +52,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testBelongsToHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -92,7 +92,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -132,7 +132,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
@@ -317,7 +317,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testBelongsToBelongsToBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -374,7 +374,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testBelongsToBelongsToHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -431,7 +431,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testBelongsToHasOneBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -488,7 +488,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testBelongsToHasOneHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -545,7 +545,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneBelongsToBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -602,7 +602,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneBelongsToHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -659,7 +659,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneHasOneBelongsTo() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
@@ -716,7 +716,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
func testHasOneHasOneHasOne() throws {
struct A: MutablePersistableRecord {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let dThroughC = hasOne(D.self, through: c, using: C.d)
+1 -1
View File
@@ -131,7 +131,7 @@ class GRDBTestCase: XCTestCase {
XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)")
}
func assert(_ record: MutablePersistableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) {
func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) {
let recordDict = record.databaseDictionary
let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
XCTAssertEqual(recordDict, rowDict, file: file, line: line)