mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge pull request #403 from groue/feature/decoding-strategies
Codable records: customize date and uuid format
This commit is contained in:
21 files changed
+1590
-343
No files matched your search
+21
-10
@@ -3,6 +3,13 @@ Release Notes
|
||||
|
||||
## Next Version
|
||||
|
||||
This release focuses on enhancing the relationships between [Codable records](README.md#codable-records) and the database, with JSON columns, customized date formats, and better diagnostics when things go wrong.
|
||||
|
||||
Other notable enhancements are:
|
||||
|
||||
- Support for the FTS5 full-text engine when available in the operating system (iOS 11.4+ / macOS 10.13+ / watchOS 4.3+)
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- The `write` and `unsafeReentrantRead` DatabaseQueue methods used to have an incorrect `throws/rethrows` qualifier.
|
||||
@@ -10,14 +17,23 @@ Release Notes
|
||||
|
||||
### New
|
||||
|
||||
- [#397](https://github.com/groue/GRDB.swift/pull/397): Codable records: JSON encoding and decoding of codable record properties
|
||||
- [#397](https://github.com/groue/GRDB.swift/pull/397) by [@gusrota](https://github.com/gusrota) and [@valexa](https://github.com/valexa): Codable records: JSON encoding and decoding of codable record properties
|
||||
- [#399](https://github.com/groue/GRDB.swift/pull/399): Codable records: customize the `userInfo` context dictionary, and the format of JSON columns
|
||||
- [#403](https://github.com/groue/GRDB.swift/pull/403): Codable records: customize date and uuid format
|
||||
- [#401](https://github.com/groue/GRDB.swift/pull/401): Query Interface: set the selection and the fetched type in a single method call
|
||||
- [#393](https://github.com/groue/GRDB.swift/pull/393): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus.
|
||||
- [#393](https://github.com/groue/GRDB.swift/pull/393) by [@Marus](https://github.com/Marus): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus.
|
||||
- [#384](https://github.com/groue/GRDB.swift/pull/384): Improve database value decoding diagnostics
|
||||
- Cursors of optimized values (Strint, Int, Date, etc.) have been renamed: FastDatabaseValueCursor and FastNullableDatabaseValueCursor replace the deprecated ColumnCursor and NullableColumnCursor.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [Enabling FTS5 Support](README.md#enabling-fts5-support): Procedure for enabling FTS5 support in GRDB.
|
||||
- [Codable Records](README.md#codable-records): Updated documentation for JSON columns, customized date and uuid formats, and other customization options.
|
||||
- [Record Customization Options](README.md#record-customization-options): A new chapter that gathers all your customization options.
|
||||
- [Fetching from Requests](README.md#fetching-from-requests): Enhanced documentation about requests that don't fetch their origin record (such as aggregates, or associated records).
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
Fixes:
|
||||
@@ -36,11 +52,14 @@ Enhancements to Codable support:
|
||||
```diff
|
||||
protocol FetchableRecord {
|
||||
+ static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get }
|
||||
+ static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
|
||||
+ static func databaseJSONDecoder(for column: String) -> JSONDecoder
|
||||
}
|
||||
|
||||
protocol MutablePersistableRecord: TableRecord {
|
||||
+ static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
|
||||
+ static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
|
||||
+ static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
|
||||
+ static func databaseJSONEncoder(for column: String) -> JSONEncoder
|
||||
}
|
||||
```
|
||||
@@ -74,14 +93,6 @@ Deprecations:
|
||||
```
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [Enabling FTS5 Support](README.md#enabling-fts5-support): Procedure for enabling FTS5 support in GRDB.
|
||||
- [Codable Records](README.md#codable-records): Updated documentation for JSON columns, tips, and customization options.
|
||||
- [Record Customization Options](README.md#record-customization-options): A new chapter that gather all your customization options.
|
||||
- [Fetching from Requests](README.md#fetching-from-requests): Enhanced documentation about requests that don't fetch their origin record (such as aggregates, or associated records).
|
||||
|
||||
|
||||
## 3.2.0
|
||||
|
||||
Released July 8, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.1.0...v3.2.0)
|
||||
|
||||
@@ -160,9 +160,45 @@ struct Player: FetchableRecord, TableRecord {
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(Columns.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(Columns.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type:
|
||||
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
// Add ColumnExpression conformance
|
||||
private enum CodingKeys: String, CodingKey, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(CodingKeys.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(CodingKeys.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol whenever you define a custom column type:
|
||||
|
||||
```swift
|
||||
struct TypedColumn: ColumnExpression {
|
||||
|
||||
@@ -301,6 +301,10 @@
|
||||
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
|
||||
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
|
||||
@@ -326,6 +330,8 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; };
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
@@ -929,6 +935,8 @@
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
|
||||
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
|
||||
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
|
||||
@@ -939,6 +947,7 @@
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1278,6 +1287,8 @@
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
@@ -1479,6 +1490,7 @@
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
|
||||
);
|
||||
@@ -2603,6 +2615,7 @@
|
||||
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
|
||||
56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
|
||||
563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */,
|
||||
5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
|
||||
56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
|
||||
56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
|
||||
@@ -2657,6 +2670,7 @@
|
||||
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
@@ -2686,6 +2700,7 @@
|
||||
56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */,
|
||||
568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */,
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
562393641DEE06D300A6B01F /* CursorTests.swift in Sources */,
|
||||
@@ -2765,6 +2780,7 @@
|
||||
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
|
||||
56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */,
|
||||
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
|
||||
5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
|
||||
56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */,
|
||||
5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
|
||||
@@ -2819,6 +2835,7 @@
|
||||
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
|
||||
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
@@ -2848,6 +2865,7 @@
|
||||
56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
|
||||
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
|
||||
56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */,
|
||||
5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
|
||||
@@ -121,18 +121,18 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
case SQLITE_INTEGER:
|
||||
storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
|
||||
storage = .int64(sqlite3_column_int64(sqliteStatement, index))
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, Int32(index)))
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
|
||||
@@ -8,8 +8,8 @@ import Foundation
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
} else {
|
||||
self.init()
|
||||
|
||||
@@ -125,7 +125,7 @@ extension Date: StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER, SQLITE_FLOAT:
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, Int32(index)))
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = Date(databaseDateComponents: databaseDateComponents) else {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
|
||||
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
|
||||
@@ -13,15 +16,72 @@ extension NSUUID : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSUUID initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
// The code below works in debug configuration, but crashes in
|
||||
// release configuration (Xcode 9.4.1)
|
||||
|
||||
// return data.withUnsafeBytes {
|
||||
// self.init(uuidBytes: $0)
|
||||
// }
|
||||
|
||||
// Workaround (involves a useless copy)
|
||||
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 16)
|
||||
_ = data.copyBytes(to: buffer)
|
||||
let uuid = self.init(uuidBytes: UnsafePointer(buffer.baseAddress!))
|
||||
buffer.deallocate()
|
||||
return uuid
|
||||
case .string(let string):
|
||||
return self.init(uuidString: string)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID : DatabaseValueConvertible { }
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var uuid_t = uuid
|
||||
return withUnsafeBytes(of: &uuid_t) {
|
||||
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
UUID(uuid: $0.pointee)
|
||||
}
|
||||
case .string(let string):
|
||||
return UUID(uuidString: string)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UUID: StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
guard let uuid = UUID(uuidString: string) else {
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
default:
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,7 +445,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, Int32(index))!)
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension FetchableRecord where Self: Decodable {
|
||||
public init(row: Row) {
|
||||
let decoder = RowDecoder<Self>(row: row, codingPath: [])
|
||||
try! self.init(from: decoder)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - RowDecoder
|
||||
|
||||
@@ -68,14 +80,16 @@ private struct RowDecoder<Record: FetchableRecord>: Decoder {
|
||||
if let index = row.index(ofColumn: keyName) {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
if type == Date.self {
|
||||
return decodeDateIfPresent(fromRow: row, columnAtIndex: index, key: key) as! T?
|
||||
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T?
|
||||
} else if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T?
|
||||
} else if row.impl.hasNull(atUncheckedIndex: index) {
|
||||
return nil
|
||||
} else {
|
||||
return try decode(type, fromColumnAtIndex: index, key: key)
|
||||
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,12 +110,14 @@ private struct RowDecoder<Record: FetchableRecord>: Decoder {
|
||||
if let index = row.index(ofColumn: keyName) {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
if type == Date.self {
|
||||
return decodeDate(fromRow: row, columnAtIndex: index, key: key) as! T
|
||||
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
return type.fastDecode(from: row, atUncheckedIndex: index) as! T
|
||||
} else if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
return type.decode(from: row, atUncheckedIndex: index) as! T
|
||||
} else {
|
||||
return try decode(type, fromColumnAtIndex: index, key: key)
|
||||
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +180,34 @@ private struct RowDecoder<Record: FetchableRecord>: Decoder {
|
||||
|
||||
// Helper methods
|
||||
|
||||
@inline(__always)
|
||||
private func decodeDateIfPresent(fromRow row: Row, columnAtIndex index: Int, key: Key) -> Date? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return Record.databaseDateDecodingStrategy.decodeIfPresent(
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: Int32(index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
} else {
|
||||
return Record.databaseDateDecodingStrategy.decodeIfPresent(
|
||||
from: row[index],
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func decodeDate(fromRow row: Row, columnAtIndex index: Int, key: Key) -> Date {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return Record.databaseDateDecodingStrategy.decode(
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: Int32(index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
} else {
|
||||
return Record.databaseDateDecodingStrategy.decode(
|
||||
from: row[index],
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func decode<T>(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable {
|
||||
if let type = T.self as? FetchableRecord.Type {
|
||||
@@ -176,8 +220,7 @@ private struct RowDecoder<Record: FetchableRecord>: Decoder {
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func decode<T>(_ type: T.Type, fromColumnAtIndex index: Int, key: Key) throws -> T where T: Decodable {
|
||||
let row = decoder.row
|
||||
private func decode<T>(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable {
|
||||
do {
|
||||
// This decoding will fail for types that decode from keyed
|
||||
// or unkeyed containers, because we're decoding a single
|
||||
@@ -261,10 +304,122 @@ extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
/// The error that triggers JSON decoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
extension FetchableRecord where Self: Decodable {
|
||||
/// Initializes a record from `row`.
|
||||
public init(row: Row) {
|
||||
let decoder = RowDecoder<Self>(row: row, codingPath: [])
|
||||
try! self.init(from: decoder)
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = .withInternetDateTime
|
||||
return formatter
|
||||
}()
|
||||
|
||||
private extension DatabaseDateDecodingStrategy {
|
||||
@inline(__always)
|
||||
func decode(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date {
|
||||
switch self {
|
||||
case .deferredToDate:
|
||||
return Date(sqliteStatement: sqliteStatement, index: index)
|
||||
case .timeIntervalSinceReferenceDate:
|
||||
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
|
||||
return Date(timeIntervalSinceReferenceDate: timeInterval)
|
||||
case .timeIntervalSince1970:
|
||||
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
|
||||
return Date(timeIntervalSince1970: timeInterval)
|
||||
case .millisecondsSince1970:
|
||||
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
|
||||
return Date(timeIntervalSince1970: timeInterval / 1000.0)
|
||||
case .iso8601:
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = iso8601Formatter.date(from: string) else {
|
||||
fatalConversionError(
|
||||
to: Date.self,
|
||||
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
|
||||
conversionContext: conversionContext())
|
||||
}
|
||||
return date
|
||||
} else {
|
||||
fatalError("ISO8601DateFormatter is unavailable on this platform.")
|
||||
}
|
||||
case .formatted(let formatter):
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = formatter.date(from: string) else {
|
||||
fatalConversionError(
|
||||
to: Date.self,
|
||||
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
|
||||
conversionContext: conversionContext())
|
||||
}
|
||||
return date
|
||||
case .custom(let format):
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = format(dbValue) else {
|
||||
fatalConversionError(
|
||||
to: Date.self,
|
||||
from: dbValue,
|
||||
conversionContext: conversionContext())
|
||||
}
|
||||
return date
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return decode(sqliteStatement:sqliteStatement, index:index, conversionContext: conversionContext)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date {
|
||||
if let date = dateFromDatabaseValue(dbValue) {
|
||||
return date
|
||||
} else {
|
||||
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? {
|
||||
if dbValue.isNull {
|
||||
return nil
|
||||
} else if let date = dateFromDatabaseValue(dbValue) {
|
||||
return date
|
||||
} else {
|
||||
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
// Returns nil if decoding fails
|
||||
@inline(__always)
|
||||
private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
switch self {
|
||||
case .deferredToDate:
|
||||
return Date.fromDatabaseValue(dbValue)
|
||||
case .timeIntervalSinceReferenceDate:
|
||||
return TimeInterval
|
||||
.fromDatabaseValue(dbValue)
|
||||
.map { Date(timeIntervalSinceReferenceDate: $0) }
|
||||
case .timeIntervalSince1970:
|
||||
return TimeInterval
|
||||
.fromDatabaseValue(dbValue)
|
||||
.map { Date(timeIntervalSince1970: $0) }
|
||||
case .millisecondsSince1970:
|
||||
return TimeInterval
|
||||
.fromDatabaseValue(dbValue)
|
||||
.map { Date(timeIntervalSince1970: $0 / 1000.0) }
|
||||
case .iso8601:
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
return String
|
||||
.fromDatabaseValue(dbValue)
|
||||
.flatMap { iso8601Formatter.date(from: $0) }
|
||||
} else {
|
||||
fatalError("ISO8601DateFormatter is unavailable on this platform.")
|
||||
}
|
||||
case .formatted(let formatter):
|
||||
return String
|
||||
.fromDatabaseValue(dbValue)
|
||||
.flatMap { formatter.date(from: $0) }
|
||||
case .custom(let format):
|
||||
return format(dbValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,21 @@ public protocol FetchableRecord {
|
||||
/// }
|
||||
/// }
|
||||
static func databaseJSONDecoder(for column: String) -> JSONDecoder
|
||||
|
||||
/// When the FetchableRecord type also adopts the standard Decodable
|
||||
/// protocol, this property controls the decoding of date properties.
|
||||
///
|
||||
/// 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 }
|
||||
}
|
||||
|
||||
extension FetchableRecord {
|
||||
@@ -114,44 +129,9 @@ extension FetchableRecord {
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of records. For example:
|
||||
///
|
||||
/// struct Player : FetchableRecord { ... }
|
||||
/// try dbQueue.read { db in
|
||||
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RecordCursor<Record: FetchableRecord> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let row: Row // Reused for performance
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Record? {
|
||||
if done {
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
}
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Record(row: row)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy {
|
||||
return .deferredToDate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +309,8 @@ extension FetchableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FetchRequest
|
||||
|
||||
extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
|
||||
// MARK: Fetching Records
|
||||
@@ -377,3 +359,102 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - RecordCursor
|
||||
|
||||
/// A cursor of records. For example:
|
||||
///
|
||||
/// struct Player : FetchableRecord { ... }
|
||||
/// try dbQueue.read { db in
|
||||
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RecordCursor<Record: FetchableRecord> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let row: Row // Reused for performance
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Record? {
|
||||
if done {
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
}
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Record(row: row)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseDateDecodingStrategy
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// It decodes numeric values as a nunber of seconds since Epoch
|
||||
/// (midnight UTC on January 1st, 1970).
|
||||
///
|
||||
/// It decodes strings in the following formats, assuming UTC time zone.
|
||||
/// Missing components are assumed to be zero:
|
||||
///
|
||||
/// - `YYYY-MM-DD`
|
||||
/// - `YYYY-MM-DD HH:MM`
|
||||
/// - `YYYY-MM-DD HH:MM:SS`
|
||||
/// - `YYYY-MM-DD HH:MM:SS.SSS`
|
||||
/// - `YYYY-MM-DDTHH:MM`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS.SSS`
|
||||
case deferredToDate
|
||||
|
||||
/// Decodes numeric values as a number of seconds between the date and
|
||||
/// midnight UTC on 1 January 2001
|
||||
case timeIntervalSinceReferenceDate
|
||||
|
||||
/// Decodes numeric values as a number of seconds between the date and
|
||||
/// midnight UTC on 1 January 1970
|
||||
case timeIntervalSince1970
|
||||
|
||||
/// Decodes numeric values as a number of milliseconds between the date and
|
||||
/// midnight UTC on 1 January 1970
|
||||
case millisecondsSince1970
|
||||
|
||||
/// Decodes dates according to the ISO 8601 standards
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
case iso8601
|
||||
|
||||
/// Decodes a String, according to the provided formatter
|
||||
case formatted(DateFormatter)
|
||||
|
||||
/// Decodes according to the user-provided function.
|
||||
///
|
||||
/// If the database value does not contain a suitable value, the function
|
||||
/// must return nil (GRDB will interpret this nil result as a conversion
|
||||
/// error, and react accordingly).
|
||||
case custom((DatabaseValue) -> Date?)
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
extension MutablePersistableRecord where Self: Encodable {
|
||||
public func encode(to container: inout PersistenceContainer) {
|
||||
let encoder = RecordEncoder<Self>()
|
||||
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<Record: MutablePersistableRecord>: Encoder {
|
||||
_persistenceContainer = PersistenceContainer()
|
||||
}
|
||||
|
||||
/// Helper method
|
||||
@inline(__always)
|
||||
fileprivate func encode(_ value: DatabaseValueConvertible?, forKey key: CodingKey) {
|
||||
_persistenceContainer[key.stringValue] = value
|
||||
}
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
let container = KeyedContainer<Key>(recordEncoder: self)
|
||||
return KeyedEncodingContainer(container)
|
||||
@@ -53,71 +55,47 @@ private class RecordEncoder<Record: MutablePersistableRecord>: 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<T>(_ 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<T>(_ 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,44 @@ private class RecordEncoder<Record: MutablePersistableRecord>: 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<T>(_ value: T, forKey key: CodingKey) throws where T : Encodable {
|
||||
if let date = value as? Date {
|
||||
persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key)
|
||||
} else if let uuid = value as? UUID {
|
||||
persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key)
|
||||
} else if let value = value as? DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
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 +190,25 @@ private struct ColumnEncoder<Record: MutablePersistableRecord>: 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<T>(_ 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 +315,49 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord where Self: Encodable {
|
||||
public func encode(to container: inout PersistenceContainer) {
|
||||
let encoder = RecordEncoder<Self>()
|
||||
try! encode(to: encoder)
|
||||
container = encoder.persistenceContainer
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = .withInternetDateTime
|
||||
return formatter
|
||||
}()
|
||||
|
||||
private extension DatabaseDateEncodingStrategy {
|
||||
@inline(__always)
|
||||
func encode(_ date: Date) -> DatabaseValueConvertible? {
|
||||
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:
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
return iso8601Formatter.string(from: date)
|
||||
} else {
|
||||
fatalError("ISO8601DateFormatter is unavailable on this platform.")
|
||||
}
|
||||
case .formatted(let formatter):
|
||||
return formatter.string(from: date)
|
||||
case .custom(let format):
|
||||
return format(date)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension DatabaseUUIDEncodingStrategy {
|
||||
@inline(__always)
|
||||
func encode(_ uuid: UUID) -> DatabaseValueConvertible? {
|
||||
switch self {
|
||||
case .deferredToUUID:
|
||||
return uuid.databaseValue
|
||||
case .string:
|
||||
return uuid.uuidString
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -387,6 +387,36 @@ 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
|
||||
///
|
||||
/// 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 {
|
||||
@@ -394,12 +424,6 @@ extension MutablePersistableRecord {
|
||||
return [:]
|
||||
}
|
||||
|
||||
/// Returns a JSONEncoder with the following properties:
|
||||
///
|
||||
/// - dataEncodingStrategy: .base64
|
||||
/// - dateEncodingStrategy: .millisecondsSince1970
|
||||
/// - nonConformingFloatEncodingStrategy: .throw
|
||||
/// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
|
||||
public static func databaseJSONEncoder(for column: String) -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
@@ -411,6 +435,14 @@ extension MutablePersistableRecord {
|
||||
}
|
||||
return encoder
|
||||
}
|
||||
|
||||
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
|
||||
return .deferredToDate
|
||||
}
|
||||
|
||||
public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy {
|
||||
return .deferredToUUID
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
@@ -944,7 +976,77 @@ extension PersistableRecord {
|
||||
try insert(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
|
||||
@@ -341,6 +341,14 @@
|
||||
5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665F86E203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665F86F203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665FA222129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA232129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA242129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA252129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA412129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
5665FA422129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
5665FA432129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
5665FA442129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A843020413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; };
|
||||
@@ -367,6 +375,10 @@
|
||||
566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
5670329F212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567032A0212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567032A1212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567032A2212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; };
|
||||
567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; };
|
||||
567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
|
||||
@@ -1019,6 +1031,8 @@
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
|
||||
5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
|
||||
566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
|
||||
566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1029,6 +1043,7 @@
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567071F6208A00D4006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -1318,6 +1333,8 @@
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA3F2129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
5670329D212B546D007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
@@ -1541,6 +1558,7 @@
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA202129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
|
||||
);
|
||||
@@ -2291,6 +2309,7 @@
|
||||
56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */,
|
||||
567DAF361EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */,
|
||||
5665FA222129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */,
|
||||
560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */,
|
||||
@@ -2345,6 +2364,7 @@
|
||||
560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */,
|
||||
5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */,
|
||||
5665FA412129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE8220F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
@@ -2374,6 +2394,7 @@
|
||||
562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
5670329F212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */,
|
||||
568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */,
|
||||
@@ -2453,6 +2474,7 @@
|
||||
56176C671EACCCC8000F3F2B /* FTS5RecordTests.swift in Sources */,
|
||||
567DAF371EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
567156351CB16729007DC145 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
|
||||
5665FA232129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
567156361CB16729007DC145 /* RowFromStatementTests.swift in Sources */,
|
||||
567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
|
||||
@@ -2507,6 +2529,7 @@
|
||||
567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */,
|
||||
5665FA422129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE8320F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
@@ -2536,6 +2559,7 @@
|
||||
562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
567032A0212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
|
||||
568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */,
|
||||
@@ -2727,6 +2751,7 @@
|
||||
56176C731EACCCCA000F3F2B /* FTS5RecordTests.swift in Sources */,
|
||||
567DAF3A1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
|
||||
5665FA242129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */,
|
||||
566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */,
|
||||
56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */,
|
||||
@@ -2781,6 +2806,7 @@
|
||||
56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */,
|
||||
5665FA432129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE8420F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
@@ -2810,6 +2836,7 @@
|
||||
56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
567032A1212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */,
|
||||
568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */,
|
||||
@@ -2889,6 +2916,7 @@
|
||||
56176C791EACCCCB000F3F2B /* FTS5RecordTests.swift in Sources */,
|
||||
567DAF3B1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
56AFCA9F1CB1ABC800F48B96 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
5665FA252129D81F004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
|
||||
56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */,
|
||||
5690C32C1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
@@ -2943,6 +2971,7 @@
|
||||
5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */,
|
||||
5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
5665FA442129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */,
|
||||
@@ -2972,6 +3001,7 @@
|
||||
56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
567032A2212B546E007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */,
|
||||
568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */,
|
||||
|
||||
@@ -145,6 +145,10 @@
|
||||
566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
|
||||
5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; };
|
||||
5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
|
||||
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
|
||||
566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; };
|
||||
566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; };
|
||||
@@ -165,6 +169,8 @@
|
||||
566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
@@ -689,6 +695,8 @@
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
|
||||
5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
|
||||
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
|
||||
566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
|
||||
@@ -699,6 +707,7 @@
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
@@ -977,6 +986,8 @@
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
@@ -1185,6 +1196,7 @@
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
|
||||
);
|
||||
@@ -1964,6 +1976,7 @@
|
||||
56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
|
||||
F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */,
|
||||
5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
|
||||
5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
5657AB451D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
|
||||
@@ -2018,6 +2031,7 @@
|
||||
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
|
||||
5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
|
||||
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
@@ -2047,6 +2061,7 @@
|
||||
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */,
|
||||
5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
|
||||
568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
|
||||
@@ -2238,6 +2253,7 @@
|
||||
F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */,
|
||||
6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
|
||||
F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
|
||||
5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
|
||||
F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */,
|
||||
5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
|
||||
@@ -2292,6 +2308,7 @@
|
||||
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
|
||||
56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
@@ -2321,6 +2338,7 @@
|
||||
F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */,
|
||||
566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
|
||||
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
|
||||
F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */,
|
||||
F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */,
|
||||
F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */,
|
||||
|
||||
@@ -1313,7 +1313,9 @@ let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2)
|
||||
|
||||
### UUID
|
||||
|
||||
**UUID** can be stored and fetched from the database just like other [values](#values). GRDB stores uuids as 16-bytes data blobs.
|
||||
**UUID** can be stored and fetched from the database just like other [values](#values).
|
||||
|
||||
GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
|
||||
|
||||
|
||||
### Swift Enums
|
||||
@@ -2062,7 +2064,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in
|
||||
- [PersistableRecord Protocol](#persistablerecord-protocol)
|
||||
- [Persistence Methods](#persistence-methods)
|
||||
- [Customizing the Persistence Methods]
|
||||
- [Codable Records](#codable-records)
|
||||
- [Codable Records]
|
||||
- [Record Class](#record-class)
|
||||
- [Record Comparison]
|
||||
- [Record Customization Options]
|
||||
@@ -2171,7 +2173,7 @@ Details follow:
|
||||
- [FetchableRecord Protocol](#fetchablerecord-protocol)
|
||||
- [TableRecord Protocol](#tablerecord-protocol)
|
||||
- [PersistableRecord Protocol](#persistablerecord-protocol)
|
||||
- [Codable Records](#codable-records)
|
||||
- [Codable Records]
|
||||
- [Record Class](#record-class)
|
||||
- [Record Comparison]
|
||||
- [Record Customization Options]
|
||||
@@ -2212,7 +2214,9 @@ Details follow:
|
||||
}
|
||||
```
|
||||
|
||||
FetchableRecord is not able to build SQL requests for you, though. For that, you also need TableRecord:
|
||||
> :bulb: **Tip**: FetchableRecord can derive its implementation from the standard Decodable protocol. See [Codable Records] for more information.
|
||||
|
||||
FetchableRecord can decode database rows, but it is not able to build SQL requests for you. For that, you also need TableRecord:
|
||||
|
||||
- [TableRecord] is able to **generate SQL queries**:
|
||||
|
||||
@@ -2243,6 +2247,8 @@ Details follow:
|
||||
```
|
||||
|
||||
A persistable record can also [compare](#record-comparison) itself against other records, and avoid useless database updates.
|
||||
|
||||
> :bulb: **Tip**: PersistableRecord can derive its implementation from the standard Encodable protocol. See [Codable Records] for more information.
|
||||
|
||||
|
||||
## FetchableRecord Protocol
|
||||
@@ -2296,7 +2302,7 @@ extension Place : FetchableRecord {
|
||||
|
||||
See [column values](#column-values) for more information about the `row[]` subscript.
|
||||
|
||||
When your record type adopts the standard Decodable protocol, you don't have to provide the implementation for `init(row:)`. See [Codable Records](#codable-records) for more information:
|
||||
When your record type adopts the standard Decodable protocol, you don't have to provide the implementation for `init(row:)`. See [Codable Records] for more information:
|
||||
|
||||
```swift
|
||||
// That's all
|
||||
@@ -2480,7 +2486,7 @@ extension Place : MutablePersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
When your record type adopts the standard Encodable protocol, you don't have to provide the implementation for `encode(to:)`. See [Codable Records](#codable-records) for more information:
|
||||
When your record type adopts the standard Encodable protocol, you don't have to provide the implementation for `encode(to:)`. See [Codable Records] for more information:
|
||||
|
||||
```swift
|
||||
// That's all
|
||||
@@ -2602,39 +2608,18 @@ 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.
|
||||
Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements:
|
||||
|
||||
> :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].
|
||||
- A property prefers its database representation when it has one (all [values](#values) that adopt the [DatabaseValueConvertible](#custom-value-types) protocol).
|
||||
- You can customize the encoding and decoding of dates and uuids.
|
||||
- Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON.
|
||||
|
||||
For more information about Codable records, see:
|
||||
|
||||
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<Player> {
|
||||
return filter(CodingKeys.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
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 and UUID Coding Strategies]
|
||||
- [The userInfo Dictionary]
|
||||
- [Tip: Use Coding Keys as Columns](#tip-use-coding-keys-as-columns)
|
||||
|
||||
|
||||
### JSON Columns
|
||||
@@ -2647,9 +2632,8 @@ enum AchievementColor: String, Codable {
|
||||
}
|
||||
|
||||
struct Achievement: Codable {
|
||||
var name: String
|
||||
var color: AchievementColor
|
||||
var date: Date
|
||||
var name: String
|
||||
var color: AchievementColor
|
||||
}
|
||||
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
@@ -2658,14 +2642,15 @@ struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var achievements: [Achievement] // stored in a JSON column
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try! dbQueue.write { db in
|
||||
// INSERT INTO player (name, score, achievements)
|
||||
// VALUES (
|
||||
// 'Arthur',
|
||||
// 100,
|
||||
// '[{"color":"gold","name":"Use Codable Records"}]')
|
||||
let achievement = Achievement(name: "Use Codable Records", color: .gold)
|
||||
try Player(name: "Arthur", score: 100, achievements: [achievement]).insert(db)
|
||||
let player = Player(name: "Arthur", score: 100, achievements: [achievement])
|
||||
try player.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -2683,37 +2668,38 @@ protocol MutablePersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
For example, here is how the Player type can customize the json format of its "achievements" JSON column:
|
||||
> :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 and UUID Coding Strategies
|
||||
|
||||
By default, [Codable Records] encode and decode their Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters.
|
||||
|
||||
To sum up: dates encode themselves in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
|
||||
|
||||
Those behaviors can be overridden:
|
||||
|
||||
```swift
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var name: String
|
||||
var score: Int
|
||||
var achievements: [Achievement] // stored in a JSON column
|
||||
|
||||
static func databaseJSONDecoder(for column: String) -> JSONDecoder {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
return decoder
|
||||
}
|
||||
|
||||
static func databaseJSONEncoder(for column: String) -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .iso8601
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
return encoder
|
||||
}
|
||||
protocol FetchableRecord {
|
||||
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
|
||||
}
|
||||
|
||||
protocol MutablePersistableRecord {
|
||||
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
|
||||
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable, and this helps [Record Comparison] yield the expected results.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/3.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
|
||||
|
||||
|
||||
### The userInfo Dictionary
|
||||
|
||||
Your [Codable records](#codable-records) can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context.
|
||||
Your [Codable Records] can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of `Decodable.init(from:)` and `Encodable.encode(to:)`, depending on the context.
|
||||
|
||||
The recommended way to provide such context is the `userInfo` dictionary. Implement those properties:
|
||||
The standard way to provide such context is the `userInfo` dictionary. Implement those properties:
|
||||
|
||||
```swift
|
||||
protocol FetchableRecord {
|
||||
@@ -2725,7 +2711,7 @@ protocol MutablePersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
For example, here is how the Player type can customize its decoding:
|
||||
For example, here is a Player type that customizes its decoding:
|
||||
|
||||
```swift
|
||||
// A key that holds a decoder's name
|
||||
@@ -2734,25 +2720,90 @@ let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
|
||||
struct Player: FetchableRecord, Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
// Print the decoder name
|
||||
print(decoder.userInfo[decoderName])
|
||||
let decoderName = decoder.userInfo[decoderName] as? String
|
||||
print("Decoded from \(decoderName ?? "unknown decoder")")
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
// prints "JSON"
|
||||
You can have a specific decoding from JSON...
|
||||
|
||||
```swift
|
||||
// prints "Decoded from JSON"
|
||||
let decoder = JSONDecoder()
|
||||
decoder.userInfo = [decoderName: "JSON"]
|
||||
let player = try decoder.decode(Player.self, from: ...)
|
||||
let player = try decoder.decode(Player.self, from: jsonData)
|
||||
```
|
||||
|
||||
... and another one from database rows:
|
||||
|
||||
```swift
|
||||
extension Player: FetchableRecord {
|
||||
// Customize the decoder name when decoding a database row
|
||||
static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"]
|
||||
static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "database row"]
|
||||
}
|
||||
|
||||
// prints "Database"
|
||||
// prints "Decoded from database row"
|
||||
let player = try Player.fetchOne(db, ...)
|
||||
```
|
||||
|
||||
> :point_up: **Note**: make sure the `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties are explicitly declared as `[CodingUserInfoKey: Any]`. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo.
|
||||
|
||||
|
||||
### Tip: Use Coding Keys as Columns
|
||||
|
||||
If you declare an explicit `CodingKeys` enum ([what is this?](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)), you can instruct GRDB to use those coding keys as database columns:
|
||||
|
||||
```swift
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
// Add ColumnExpression conformance
|
||||
private enum CodingKeys: String, CodingKey, ColumnExpression {
|
||||
case name, score
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This allows your record to build requests with the [query interface](#the-query-interface):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(CodingKeys.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(CodingKeys.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those requests can both fetch...
|
||||
|
||||
```swift
|
||||
// Fetch values
|
||||
try dbQueue.read { db in
|
||||
// SELECT * FROM player WHERE name = 'Arthur'
|
||||
let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player?
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maxScore = try Player.maximumScore.fetchOne(db) // Int?
|
||||
}
|
||||
```
|
||||
|
||||
... and feed database observation tools such as [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// Observe changes
|
||||
Player.maximumScore.rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { maxScore: Int? in
|
||||
print("The maximum score has changed")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Record Class
|
||||
|
||||
@@ -2891,14 +2942,18 @@ For an efficient algorithm which synchronizes the content of a database table wi
|
||||
|
||||
GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs:
|
||||
|
||||
- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`.
|
||||
- [Customizing the Persistence Methods]: define what happens when you call a persistance method such as `player.insert(db)`
|
||||
- [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index.
|
||||
- [The Implicit RowID Primary Key]: all about the special `rowid` column.
|
||||
- [JSON Columns]: control the format of JSON columns.
|
||||
- [The userInfo Dictionary]: adapt your Codable implementation for the database.
|
||||
- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`.
|
||||
- [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story.
|
||||
|
||||
[Codable Records] have a few extra options:
|
||||
|
||||
- [JSON Columns]: control the format of JSON columns.
|
||||
- [Date and UUID Coding Strategies]: control the format of Date and UUID properties in your Codable records.
|
||||
- [The userInfo Dictionary]: adapt your Codable implementation for the database.
|
||||
|
||||
|
||||
### Conflict Resolution
|
||||
|
||||
@@ -3097,7 +3152,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu
|
||||
|
||||
**Some GRDB users eventually discover that the [FetchableRecord] protocol does not fit all situations.** Use cases that are not well handled by FetchableRecord include:
|
||||
|
||||
- Your application needs polymorphic row decoding: it decodes some class or another, depending on the values contained in a database row.
|
||||
- Your application needs polymorphic row decoding: it decodes some type or another, depending on the values contained in a database row.
|
||||
|
||||
- Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database.
|
||||
|
||||
@@ -3131,7 +3186,7 @@ Each one of the three examples below is correct. You will pick one or the other
|
||||
|
||||
This is the shortest way to define a record type.
|
||||
|
||||
See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records](#codable-records) for more information.
|
||||
See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records] for more information.
|
||||
|
||||
```swift
|
||||
struct Place: Codable {
|
||||
@@ -3847,7 +3902,7 @@ let request = RestrictedPlayer.all()
|
||||
let request = ExtendedPlayer.all()
|
||||
```
|
||||
|
||||
> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ.
|
||||
> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ.
|
||||
|
||||
|
||||
## Expressions
|
||||
@@ -5559,7 +5614,7 @@ PlayerInfo.all()
|
||||
|
||||
### Splitting Rows, the Codable Way
|
||||
|
||||
[Codable Records](#codable-records) build on top of the standard Decodable protocol in order to decode database rows.
|
||||
[Codable Records] build on top of the standard Decodable protocol in order to decode database rows.
|
||||
|
||||
You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code:
|
||||
|
||||
@@ -7637,9 +7692,11 @@ This chapter has been renamed [Beyond FetchableRecord].
|
||||
|
||||
[Associations]: Documentation/AssociationsBasics.md
|
||||
[Beyond FetchableRecord]: #beyond-fetchablerecord
|
||||
[Codable Records]: #codable-records
|
||||
[Columns Selected by a Request]: #columns-selected-by-a-request
|
||||
[Conflict Resolution]: #conflict-resolution
|
||||
[Customizing the Persistence Methods]: #customizing-the-persistence-methods
|
||||
[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies
|
||||
[Fetching from Requests]: #fetching-from-requests
|
||||
[The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key
|
||||
[The userInfo Dictionary]: #the-userinfo-dictionary
|
||||
|
||||
@@ -29,17 +29,6 @@
|
||||
let lefts = Left.select(Left.Columns.id, Left.Columns.name)
|
||||
try Right.insert(lefts)
|
||||
```
|
||||
- [ ] requestselect(..., as:)
|
||||
|
||||
```swift
|
||||
// current
|
||||
request
|
||||
.select(Column("name"))
|
||||
.asRequest(of: String.self)
|
||||
|
||||
// new
|
||||
request.select(Column("name"), as: String.self)
|
||||
```
|
||||
- [ ] select values from a JSON column:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
#if GRDBCIPHER
|
||||
import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
import GRDBCustomSQLite
|
||||
#else
|
||||
import GRDB
|
||||
#endif
|
||||
|
||||
private protocol StrategyProvider {
|
||||
static var strategy: DatabaseDateDecodingStrategy { get }
|
||||
}
|
||||
|
||||
private enum StrategyDeferredToDate: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .deferredToDate
|
||||
}
|
||||
|
||||
private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .timeIntervalSinceReferenceDate
|
||||
}
|
||||
|
||||
private enum StrategyTimeIntervalSince1970: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
|
||||
}
|
||||
|
||||
private enum StrategyMillisecondsSince1970: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970
|
||||
}
|
||||
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
private enum StrategyIso8601: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .iso8601
|
||||
}
|
||||
|
||||
private enum StrategyFormatted: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .formatted({
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
formatter.dateStyle = .full
|
||||
formatter.timeStyle = .full
|
||||
return formatter
|
||||
}())
|
||||
}
|
||||
|
||||
private enum StrategyCustom: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .custom { _ in
|
||||
return Date(timeIntervalSinceReferenceDate: 123456)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RecordWithDate<Strategy: StrategyProvider>: FetchableRecord, Decodable {
|
||||
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy }
|
||||
var date: Date
|
||||
}
|
||||
|
||||
private struct RecordWithOptionalDate<Strategy: StrategyProvider>: FetchableRecord, Decodable {
|
||||
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { return Strategy.strategy }
|
||||
var date: Date?
|
||||
}
|
||||
|
||||
class DatabaseDateDecodingStrategyTests: GRDBTestCase {
|
||||
/// test the conversion from a database value to a date extracted from a record
|
||||
private func test<T: FetchableRecord>(
|
||||
_ db: Database,
|
||||
record: T.Type,
|
||||
date: (T) -> Date?,
|
||||
databaseValue: DatabaseValueConvertible?,
|
||||
with test: (Date?) -> Void) throws
|
||||
{
|
||||
let request = SQLRequest<Void>("SELECT ? AS date", arguments: [databaseValue])
|
||||
do {
|
||||
// test decoding straight from SQLite
|
||||
let record = try T.fetchOne(db, request)!
|
||||
test(date(record))
|
||||
}
|
||||
do {
|
||||
// test decoding from copied row
|
||||
let record = try T(row: Row.fetchOne(db, request)!)
|
||||
test(date(record))
|
||||
}
|
||||
}
|
||||
|
||||
/// test the conversion from a database value to a date with a given strategy
|
||||
private func test<Strategy: StrategyProvider>(_ db: Database, strategy: Strategy.Type, databaseValue: DatabaseValueConvertible, _ test: (Date) -> Void) throws {
|
||||
try self.test(db, record: RecordWithDate<Strategy>.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) })
|
||||
try self.test(db, record: RecordWithOptionalDate<Strategy>.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) })
|
||||
}
|
||||
|
||||
private func testNullDecoding<Strategy: StrategyProvider>(_ db: Database, strategy: Strategy.Type) throws {
|
||||
try self.test(db, record: RecordWithOptionalDate<Strategy>.self, date: { $0.date }, databaseValue: nil) { date in
|
||||
XCTAssertNil(date)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - deferredToDate
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testDeferredToDate() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyDeferredToDate.self)
|
||||
|
||||
// YMD
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// YMD_HM
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// YMD_HMS
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02:03") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 3)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// YMD_HMSS
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22 01:02:03.00456") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 3)
|
||||
XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal.
|
||||
}
|
||||
|
||||
// Timestamp
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: 1437526920) { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// Iso8601YMD_HM
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 0)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// Iso8601YMD_HMS
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02:03") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 3)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// Iso8601YMD_HMSS
|
||||
try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "2015-07-22T01:02:03.00456") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2015)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 22)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 1)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 2)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 3)
|
||||
XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - timeIntervalSinceReferenceDate
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testTimeIntervalSinceReferenceDate() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyTimeIntervalSinceReferenceDate.self)
|
||||
|
||||
// 0
|
||||
try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 0) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0))
|
||||
}
|
||||
|
||||
// 123.456
|
||||
try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 123.456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - timeIntervalSince1970
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testTimeIntervalSince1970() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyTimeIntervalSince1970.self)
|
||||
|
||||
// 0
|
||||
try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 0) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
|
||||
}
|
||||
|
||||
// 123.456
|
||||
try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 123.456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - millisecondsSince1970
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testMillisecondsSince1970() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyMillisecondsSince1970.self)
|
||||
|
||||
// 0
|
||||
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 0) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
|
||||
}
|
||||
|
||||
// 123.456
|
||||
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123.456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456 / 1000 ))
|
||||
}
|
||||
|
||||
// 123456
|
||||
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.0 / 1000))
|
||||
}
|
||||
|
||||
// 123456.789
|
||||
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456.789) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - iso8601(ISO8601DateFormatter)
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testIso8601() throws {
|
||||
// check ISO8601DateFormatter availabiliity
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
try makeDatabaseQueue().read { db in
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyIso8601.self)
|
||||
|
||||
// Date
|
||||
try test(db, strategy: StrategyIso8601.self, databaseValue: "2018-08-19T17:18:07Z") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2018)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 8)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 19)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 17)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 18)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - formatted(DateFormatter)
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testFormatted() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyFormatted.self)
|
||||
|
||||
// Date
|
||||
try test(db, strategy: StrategyFormatted.self, databaseValue: "Sunday, August 19, 2018 at 5:21:55 PM Greenwich Mean Time") { date in
|
||||
XCTAssertEqual(calendar.component(.year, from: date), 2018)
|
||||
XCTAssertEqual(calendar.component(.month, from: date), 8)
|
||||
XCTAssertEqual(calendar.component(.day, from: date), 19)
|
||||
XCTAssertEqual(calendar.component(.hour, from: date), 17)
|
||||
XCTAssertEqual(calendar.component(.minute, from: date), 21)
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 55)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - custom((DatabaseValue) -> Date?
|
||||
|
||||
extension DatabaseDateDecodingStrategyTests {
|
||||
func testCustom() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
// Null
|
||||
try testNullDecoding(db, strategy: StrategyCustom.self)
|
||||
|
||||
// Date
|
||||
try test(db, strategy: StrategyCustom.self, databaseValue: "whatever") { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import XCTest
|
||||
import Foundation
|
||||
#if GRDBCIPHER
|
||||
@testable import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
@testable import GRDBCustomSQLite
|
||||
#else
|
||||
@testable import GRDB
|
||||
#endif
|
||||
|
||||
private protocol StrategyProvider {
|
||||
static var strategy: DatabaseDateEncodingStrategy { get }
|
||||
}
|
||||
|
||||
private enum StrategyDeferredToDate: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .deferredToDate
|
||||
}
|
||||
|
||||
private enum StrategyTimeIntervalSinceReferenceDate: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .timeIntervalSinceReferenceDate
|
||||
}
|
||||
|
||||
private enum StrategyTimeIntervalSince1970: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
|
||||
}
|
||||
|
||||
private enum StrategySecondsSince1970: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .secondsSince1970
|
||||
}
|
||||
|
||||
private enum StrategyMillisecondsSince1970: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970
|
||||
}
|
||||
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
private enum StrategyIso8601: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .iso8601
|
||||
}
|
||||
|
||||
private enum StrategyFormatted: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .formatted({
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
formatter.dateStyle = .full
|
||||
formatter.timeStyle = .medium
|
||||
return formatter
|
||||
}())
|
||||
}
|
||||
|
||||
private enum StrategyCustom: StrategyProvider {
|
||||
static let strategy: DatabaseDateEncodingStrategy = .custom { _ in "custom" }
|
||||
}
|
||||
|
||||
private struct RecordWithDate<Strategy: StrategyProvider>: PersistableRecord, Encodable {
|
||||
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy }
|
||||
var date: Date
|
||||
}
|
||||
|
||||
private struct RecordWithOptionalDate<Strategy: StrategyProvider>: PersistableRecord, Encodable {
|
||||
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { return Strategy.strategy }
|
||||
var date: Date?
|
||||
}
|
||||
|
||||
class DatabaseDateEncodingStrategyTests: GRDBTestCase {
|
||||
let testedDates = [
|
||||
Date(timeIntervalSince1970: -987654.321),
|
||||
Date(timeIntervalSince1970: 123456.789),
|
||||
Date(timeIntervalSinceReferenceDate: 0),
|
||||
Date(timeIntervalSinceReferenceDate: 123456.789),
|
||||
]
|
||||
|
||||
private func test<T: PersistableRecord>(
|
||||
record: T,
|
||||
expectedStorage: DatabaseValue.Storage)
|
||||
{
|
||||
var container = PersistenceContainer()
|
||||
record.encode(to: &container)
|
||||
if let dbValue = container["date"]?.databaseValue {
|
||||
XCTAssertEqual(dbValue.storage, expectedStorage)
|
||||
} else {
|
||||
XCTAssertEqual(.null, expectedStorage)
|
||||
}
|
||||
}
|
||||
|
||||
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) {
|
||||
test(record: RecordWithDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
|
||||
test(record: RecordWithOptionalDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
|
||||
}
|
||||
|
||||
private func testNullEncoding<Strategy: StrategyProvider>(strategy: Strategy.Type) {
|
||||
test(record: RecordWithOptionalDate<Strategy>(date: nil), expectedStorage: .null)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - deferredToDate
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testDeferredToDate() {
|
||||
testNullEncoding(strategy: StrategyDeferredToDate.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
"1969-12-20 13:39:05.679",
|
||||
"1970-01-02 10:17:36.789",
|
||||
"2001-01-01 00:00:00.000",
|
||||
"2001-01-02 10:17:36.789",
|
||||
]) { test(strategy: StrategyDeferredToDate.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - timeIntervalSinceReferenceDate
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testTimeIntervalSinceReferenceDate() {
|
||||
testNullEncoding(strategy: StrategyTimeIntervalSinceReferenceDate.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
-979294854.321,
|
||||
-978183743.211,
|
||||
0.0,
|
||||
123456.789,
|
||||
]) { test(strategy: StrategyTimeIntervalSinceReferenceDate.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - timeIntervalSince1970
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testTimeIntervalSince1970() {
|
||||
testNullEncoding(strategy: StrategyTimeIntervalSince1970.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
-987654.32099997997,
|
||||
123456.78900003433,
|
||||
978307200.0,
|
||||
978430656.789,
|
||||
]) { test(strategy: StrategyTimeIntervalSince1970.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - secondsSince1970
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testSecondsSince1970() {
|
||||
testNullEncoding(strategy: StrategySecondsSince1970.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
-987655,
|
||||
123456,
|
||||
978307200,
|
||||
978430656,
|
||||
]) { test(strategy: StrategySecondsSince1970.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - millisecondsSince1970
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testMillisecondsSince1970() {
|
||||
testNullEncoding(strategy: StrategyMillisecondsSince1970.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
-987654321,
|
||||
123456789,
|
||||
978307200000,
|
||||
978430656789,
|
||||
] as [Int64]) { test(strategy: StrategyMillisecondsSince1970.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - iso8601(ISO8601DateFormatter)
|
||||
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testIso8601() {
|
||||
// check ISO8601DateFormatter availabiliity
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
testNullEncoding(strategy: StrategyIso8601.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
"1969-12-20T13:39:05Z",
|
||||
"1970-01-02T10:17:36Z",
|
||||
"2001-01-01T00:00:00Z",
|
||||
"2001-01-02T10:17:36Z",
|
||||
]) { test(strategy: StrategyIso8601.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - formatted(DateFormatter)
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testFormatted() {
|
||||
testNullEncoding(strategy: StrategyFormatted.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
"Saturday, December 20, 1969 at 1:39:05 PM",
|
||||
"Friday, January 2, 1970 at 10:17:36 AM",
|
||||
"Monday, January 1, 2001 at 12:00:00 AM",
|
||||
"Tuesday, January 2, 2001 at 10:17:36 AM",
|
||||
]) { test(strategy: StrategyFormatted.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - custom((Date) -> DatabaseValueConvertible?)
|
||||
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testCustom() {
|
||||
testNullEncoding(strategy: StrategyCustom.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
"custom",
|
||||
"custom",
|
||||
"custom",
|
||||
"custom",
|
||||
]) { test(strategy: StrategyCustom.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import XCTest
|
||||
import Foundation
|
||||
#if GRDBCIPHER
|
||||
@testable import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
@testable import GRDBCustomSQLite
|
||||
#else
|
||||
@testable import GRDB
|
||||
#endif
|
||||
|
||||
private protocol StrategyProvider {
|
||||
static var strategy: DatabaseUUIDEncodingStrategy { get }
|
||||
}
|
||||
|
||||
private enum StrategyDeferredToUUID: StrategyProvider {
|
||||
static let strategy: DatabaseUUIDEncodingStrategy = .deferredToUUID
|
||||
}
|
||||
|
||||
private enum StrategyString: StrategyProvider {
|
||||
static let strategy: DatabaseUUIDEncodingStrategy = .string
|
||||
}
|
||||
|
||||
private struct RecordWithUUID<Strategy: StrategyProvider>: PersistableRecord, Encodable {
|
||||
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy }
|
||||
var uuid: UUID
|
||||
}
|
||||
|
||||
private struct RecordWithOptionalUUID<Strategy: StrategyProvider>: PersistableRecord, Encodable {
|
||||
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { return Strategy.strategy }
|
||||
var uuid: UUID?
|
||||
}
|
||||
|
||||
class DatabaseUUIDEncodingStrategyTests: GRDBTestCase {
|
||||
private func test<T: PersistableRecord>(
|
||||
record: T,
|
||||
expectedStorage: DatabaseValue.Storage)
|
||||
{
|
||||
var container = PersistenceContainer()
|
||||
record.encode(to: &container)
|
||||
if let dbValue = container["uuid"]?.databaseValue {
|
||||
XCTAssertEqual(dbValue.storage, expectedStorage)
|
||||
} else {
|
||||
XCTAssertEqual(.null, expectedStorage)
|
||||
}
|
||||
}
|
||||
|
||||
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) {
|
||||
test(record: RecordWithUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
|
||||
test(record: RecordWithOptionalUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
|
||||
}
|
||||
|
||||
private func testNullEncoding<Strategy: StrategyProvider>(strategy: Strategy.Type) {
|
||||
test(record: RecordWithOptionalUUID<Strategy>(uuid: nil), expectedStorage: .null)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - deferredToUUID
|
||||
|
||||
extension DatabaseUUIDEncodingStrategyTests {
|
||||
func testDeferredToUUID() {
|
||||
testNullEncoding(strategy: StrategyDeferredToUUID.self)
|
||||
|
||||
test(
|
||||
strategy: StrategyDeferredToUUID.self,
|
||||
encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!,
|
||||
as: "abcdefghijklmnop".data(using: .utf8)!)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - string
|
||||
|
||||
extension DatabaseUUIDEncodingStrategyTests {
|
||||
func testString() {
|
||||
testNullEncoding(strategy: StrategyString.self)
|
||||
|
||||
test(
|
||||
strategy: StrategyString.self,
|
||||
encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!,
|
||||
as: "61626364-6566-6768-696A-6B6C6D6E6F70")
|
||||
|
||||
test(
|
||||
strategy: StrategyString.self,
|
||||
encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!,
|
||||
as: "56E7D8D3-E9E4-48B6-968E-8D102833AF00")
|
||||
|
||||
let uuid = UUID()
|
||||
test(
|
||||
strategy: StrategyString.self,
|
||||
encodesUUID: uuid,
|
||||
as: uuid.uuidString.uppercased()) // Assert stable casing
|
||||
}
|
||||
}
|
||||
@@ -8,47 +8,51 @@ import XCTest
|
||||
#endif
|
||||
|
||||
class FoundationNSUUIDTests: GRDBTestCase {
|
||||
|
||||
func testNSUUIDDatabaseRoundTrip() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
func roundTrip(_ value: NSUUID) throws -> Bool {
|
||||
guard let back = try dbQueue.inDatabase({ try NSUUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else {
|
||||
XCTFail()
|
||||
return false
|
||||
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
if let expectedUUID = expectedUUID {
|
||||
let decodedUUID = try NSUUID.fetchOne(db, "SELECT ?", arguments: [value])
|
||||
XCTAssertEqual(decodedUUID, expectedUUID)
|
||||
} else if value == nil {
|
||||
let decodedUUID = try Optional<NSUUID>.fetchAll(db, "SELECT NULL")[0]
|
||||
XCTAssertNil(decodedUUID)
|
||||
}
|
||||
return back == value
|
||||
}
|
||||
|
||||
XCTAssertTrue(try roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
|
||||
XCTAssertTrue(try roundTrip(NSUUID()))
|
||||
let decodedUUID = NSUUID.fromDatabaseValue(value?.databaseValue ?? .null)
|
||||
XCTAssertEqual(decodedUUID, expectedUUID)
|
||||
}
|
||||
|
||||
func testNSUUIDDatabaseValueRoundTrip() {
|
||||
|
||||
func roundTrip(_ value: NSUUID) -> Bool {
|
||||
let dbValue = value.databaseValue
|
||||
guard let back = NSUUID.fromDatabaseValue(dbValue) else {
|
||||
XCTFail("Failed to convert from DatabaseValue to NSUUID")
|
||||
return false
|
||||
}
|
||||
return back.isEqual(value)
|
||||
private func assertRoundTrip(_ uuid: UUID) throws {
|
||||
let string = uuid.uuidString
|
||||
var uuid_t = uuid.uuid
|
||||
let data = withUnsafeBytes(of: &uuid_t) {
|
||||
Data(bytes: $0.baseAddress!, count: $0.count)
|
||||
}
|
||||
|
||||
XCTAssertTrue(roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
|
||||
XCTAssertTrue(roundTrip(NSUUID()))
|
||||
try assert(string, isDecodedAs: uuid as NSUUID)
|
||||
try assert(string.lowercased(), isDecodedAs: uuid as NSUUID)
|
||||
try assert(string.uppercased(), isDecodedAs: uuid as NSUUID)
|
||||
try assert(uuid, isDecodedAs: uuid as NSUUID)
|
||||
try assert(uuid as NSUUID, isDecodedAs: uuid as NSUUID)
|
||||
try assert(data, isDecodedAs: uuid as NSUUID)
|
||||
}
|
||||
|
||||
func testNSUUIDFromDatabaseValueFailure() {
|
||||
let databaseValue_Null = DatabaseValue.null
|
||||
let databaseValue_Int64 = Int64(1).databaseValue
|
||||
let databaseValue_Double = Double(100000.1).databaseValue
|
||||
let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue
|
||||
let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue
|
||||
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Null))
|
||||
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Int64))
|
||||
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Double))
|
||||
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_String))
|
||||
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_badBlob))
|
||||
func testSuccess() throws {
|
||||
try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)
|
||||
try assertRoundTrip(UUID())
|
||||
try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: NSUUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70"))
|
||||
}
|
||||
|
||||
func testFailure() throws {
|
||||
try assert(nil, isDecodedAs: nil)
|
||||
try assert(DatabaseValue.null, isDecodedAs: nil)
|
||||
try assert(1, isDecodedAs: nil)
|
||||
try assert(100000.1, isDecodedAs: nil)
|
||||
try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil)
|
||||
try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil)
|
||||
try assert("foo", isDecodedAs: nil)
|
||||
try assert("bar".data(using: .utf8)!, isDecodedAs: nil)
|
||||
try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil)
|
||||
try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import XCTest
|
||||
import Foundation
|
||||
#if GRDBCIPHER
|
||||
import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
@@ -8,47 +9,51 @@ import XCTest
|
||||
#endif
|
||||
|
||||
class FoundationUUIDTests: GRDBTestCase {
|
||||
|
||||
func testUUIDDatabaseRoundTrip() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
func roundTrip(_ value: UUID) throws -> Bool {
|
||||
guard let back = try dbQueue.inDatabase({ try UUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else {
|
||||
XCTFail()
|
||||
return false
|
||||
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
if let expectedUUID = expectedUUID {
|
||||
let decodedUUID = try UUID.fetchOne(db, "SELECT ?", arguments: [value])
|
||||
XCTAssertEqual(decodedUUID, expectedUUID)
|
||||
} else if value == nil {
|
||||
let decodedUUID = try Optional<UUID>.fetchAll(db, "SELECT NULL")[0]
|
||||
XCTAssertNil(decodedUUID)
|
||||
}
|
||||
return back == value
|
||||
}
|
||||
|
||||
XCTAssertTrue(try roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
|
||||
XCTAssertTrue(try roundTrip(UUID()))
|
||||
let decodedUUID = UUID.fromDatabaseValue(value?.databaseValue ?? .null)
|
||||
XCTAssertEqual(decodedUUID, expectedUUID)
|
||||
}
|
||||
|
||||
func testUUIDDatabaseValueRoundTrip() {
|
||||
|
||||
func roundTrip(_ value: UUID) -> Bool {
|
||||
let dbValue = value.databaseValue
|
||||
guard let back = UUID.fromDatabaseValue(dbValue) else {
|
||||
XCTFail("Failed to convert from DatabaseValue to UUID")
|
||||
return false
|
||||
}
|
||||
return back == value
|
||||
private func assertRoundTrip(_ uuid: UUID) throws {
|
||||
let string = uuid.uuidString
|
||||
var uuid_t = uuid.uuid
|
||||
let data = withUnsafeBytes(of: &uuid_t) {
|
||||
Data(bytes: $0.baseAddress!, count: $0.count)
|
||||
}
|
||||
|
||||
XCTAssertTrue(roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
|
||||
XCTAssertTrue(roundTrip(UUID()))
|
||||
try assert(string, isDecodedAs: uuid)
|
||||
try assert(string.lowercased(), isDecodedAs: uuid)
|
||||
try assert(string.uppercased(), isDecodedAs: uuid)
|
||||
try assert(uuid, isDecodedAs: uuid)
|
||||
try assert(uuid as NSUUID, isDecodedAs: uuid)
|
||||
try assert(data, isDecodedAs: uuid)
|
||||
}
|
||||
|
||||
func testUUIDFromDatabaseValueFailure() {
|
||||
let databaseValue_Null = DatabaseValue.null
|
||||
let databaseValue_Int64 = Int64(1).databaseValue
|
||||
let databaseValue_Double = Double(100000.1).databaseValue
|
||||
let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue
|
||||
let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue
|
||||
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Null))
|
||||
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Int64))
|
||||
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Double))
|
||||
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_String))
|
||||
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_badBlob))
|
||||
func testSuccess() throws {
|
||||
try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)
|
||||
try assertRoundTrip(UUID())
|
||||
try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70"))
|
||||
}
|
||||
|
||||
func testFailure() throws {
|
||||
try assert(nil, isDecodedAs: nil)
|
||||
try assert(DatabaseValue.null, isDecodedAs: nil)
|
||||
try assert(1, isDecodedAs: nil)
|
||||
try assert(100000.1, isDecodedAs: nil)
|
||||
try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil)
|
||||
try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil)
|
||||
try assert("foo", isDecodedAs: nil)
|
||||
try assert("bar".data(using: .utf8)!, isDecodedAs: nil)
|
||||
try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil)
|
||||
try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user