From f6e695a21d93281e820370fae88ba8afae67d049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Apr 2023 12:01:26 +0200 Subject: [PATCH 1/9] More explicit any/some --- GRDB/Core/Configuration.swift | 2 +- GRDB/Core/RowAdapter.swift | 2 +- GRDB/Core/Statement.swift | 2 +- .../DatabaseValueConvertible+Decodable.swift | 2 +- GRDB/Fixits.swift | 2 +- Package.swift | 3 + .../DatabaseWriterWritePublisherTests.swift | 2 +- ...sociationBelongsToSQLDerivationTests.swift | 4 +- .../AssociationHasOneSQLDerivationTests.swift | 4 +- ...ationHasOneThroughSQLDerivationTests.swift | 4 +- Tests/GRDBTests/ColumnExpressionTests.swift | 8 +- .../GRDBTests/CompilationProtocolTests.swift | 6 +- .../DatabaseAbortedTransactionTests.swift | 6 +- Tests/GRDBTests/DatabaseAggregateTests.swift | 76 +++++------ .../DatabaseDateDecodingStrategyTests.swift | 10 +- .../DatabaseDateEncodingStrategyTests.swift | 7 +- Tests/GRDBTests/DatabaseReaderTests.swift | 28 ++-- Tests/GRDBTests/DatabaseSavepointTests.swift | 2 +- .../DatabaseUUIDEncodingStrategyTests.swift | 6 +- Tests/GRDBTests/FTS3RecordTests.swift | 2 +- Tests/GRDBTests/FTS4RecordTests.swift | 2 +- .../GRDBTests/FTS5CustomTokenizerTests.swift | 6 +- Tests/GRDBTests/FTS5RecordTests.swift | 2 +- .../GRDBTests/FTS5WrapperTokenizerTests.swift | 8 +- Tests/GRDBTests/FoundationNSUUIDTests.swift | 2 +- Tests/GRDBTests/FoundationUUIDTests.swift | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 24 +++- Tests/GRDBTests/JoinSupportTests.swift | 2 +- .../QueryInterfaceExpressionsTests.swift | 4 +- .../RecordPersistenceConflictPolicy.swift | 4 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 2 +- Tests/GRDBTests/RowFromDictionaryTests.swift | 6 +- Tests/GRDBTests/SQLLiteralTests.swift | 126 ++++++++++++++---- Tests/GRDBTests/SelectStatementTests.swift | 4 +- Tests/GRDBTests/StatementArgumentsTests.swift | 18 +-- Tests/GRDBTests/TableRecordTests.swift | 4 +- .../GRDBTests/TransactionObserverTests.swift | 2 +- Tests/GRDBTests/UpdateStatementTests.swift | 8 +- .../ValueObservationPrintTests.swift | 2 +- .../GRDBTests/ValueObservationRecorder.swift | 2 +- Tests/GRDBTests/ValueObservationTests.swift | 8 +- .../FetchRecordOptimizedTests.swift | 2 +- 42 files changed, 262 insertions(+), 156 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 58889b4bb..18d4736fd 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -182,7 +182,7 @@ public struct Configuration { /// var config = Configuration() /// config.transactionClock = .custom { db in /* return some Date */ } /// ``` - public var transactionClock: TransactionClock = .default + public var transactionClock: any TransactionClock = .default // MARK: - Managing SQLite Connections diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 9ec410a25..a17062460 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -572,7 +572,7 @@ public struct ScopeAdapter: RowAdapter { /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. - public init(_ scopes: [String: RowAdapter]) { + public init(_ scopes: [String: any RowAdapter]) { // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes) } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index dfa19320e..b60c6a54c 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1030,7 +1030,7 @@ public struct StatementArguments: Hashable { /// The result is nil unless all array elements conform to the /// ``DatabaseValueConvertible`` protocol. public init?(_ array: [Any]) { - var values = [DatabaseValueConvertible?]() + var values = [(any DatabaseValueConvertible)?]() for value in array { guard let dbValue = DatabaseValue(value: value) else { return nil diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index 0ac8736c6..e8ec70b8f 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: T.Type) throws -> T where T: Decodable { - if let type = T.self as? DatabaseValueConvertible.Type { + if let type = T.self as? any DatabaseValueConvertible.Type { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows custom database decoding, such as decoding Date from // String, for example. diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 7bd1e3f16..ed82d514d 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -57,7 +57,7 @@ extension DatabaseCursor { extension DatabaseMigrator { @available(*, unavailable, message: "The completion function now accepts one Result argument") public func asyncMigrate( - _ writer: DatabaseWriter, + _ writer: any DatabaseWriter, completion: @escaping (Database, Error?) -> Void) { preconditionFailure() } } diff --git a/Package.swift b/Package.swift index 3372d1313..e5e9ef226 100644 --- a/Package.swift +++ b/Package.swift @@ -10,6 +10,9 @@ var swiftSettings: [SwiftSetting] = [ var cSettings: [CSetting] = [] var dependencies: [PackageDescription.Package.Dependency] = [] +// For Swift 5.8+ +//swiftSettings.append(.enableUpcomingFeature("ExistentialAny")) + // Don't rely on those environment variables. They are ONLY testing conveniences: // $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 791d8201a..1ab142081 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -395,7 +395,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter, iteration: Int) throws { + func test(writer: some DatabaseWriter, iteration: Int) throws { // print(iteration) let scoreSubject = PassthroughSubject() let publisher = scoreSubject diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 49a81fa25..b51ec961e 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -16,12 +16,12 @@ private struct B : TableRecord { private struct RestrictedB : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [SQLSelectable] = [Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("name")] } private struct ExtendedB : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } /// Test SQL generation diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index 9165292b1..932167d5e 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -16,12 +16,12 @@ private struct B : TableRecord { private struct RestrictedB : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [SQLSelectable] = [Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("name")] } private struct ExtendedB : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } /// Test SQL generation diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index a9f4d9f07..630c7aa88 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -19,12 +19,12 @@ private struct C: TableRecord { private struct RestrictedC : TableRecord { static let databaseTableName = "c" - static let databaseSelection: [SQLSelectable] = [Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("name")] } private struct ExtendedC : TableRecord { static let databaseTableName = "c" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } /// Test SQL generation diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index 0cc77811b..b716a0700 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -20,7 +20,7 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] init(row: Row) { // Test row subscript @@ -80,7 +80,7 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] init(row: Row) { // Test row subscript @@ -148,7 +148,7 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] static var testRequest: QueryInterfaceRequest { // Test expression derivation @@ -196,7 +196,7 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score] + static let databaseSelection: [any SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score] static var testRequest: QueryInterfaceRequest { // Test expression derivation diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 589627683..25eebc715 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -27,13 +27,13 @@ private struct UserDatabaseAggregate1 : DatabaseAggregate { let a: Int? init() { a = nil } mutating func step(_ dbValues: [DatabaseValue]) throws { } - func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() } + func finalize() throws -> (any DatabaseValueConvertible)? { preconditionFailure() } } private class UserDatabaseAggregate2 : DatabaseAggregate { required init() { } func step(_ dbValues: [DatabaseValue]) throws { } - func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() } + func finalize() throws -> (any DatabaseValueConvertible)? { preconditionFailure() } } // MARK: - DatabaseValueConvertible @@ -71,7 +71,7 @@ private class UserFTS5CustomTokenizer : FTS5CustomTokenizer { #if SQLITE_ENABLE_FTS5 private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer { static let name: String = "UserFTS5WrapperTokenizer" - var wrappedTokenizer: FTS5Tokenizer { preconditionFailure() } + var wrappedTokenizer: any FTS5Tokenizer { preconditionFailure() } required init(db: Database, arguments: [String]) throws { preconditionFailure() } func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: (String, FTS5TokenFlags) throws -> ()) throws { preconditionFailure() } } diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index 602e8705c..d6229e88d 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -4,7 +4,7 @@ import GRDB class DatabaseAbortedTransactionTests : GRDBTestCase { func testReadTransactionAbortedByInterrupt() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -46,7 +46,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } func testReadTransactionAbortedByInterruptDoesNotPreventFurtherRead() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -316,7 +316,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { do { try dbReader.unsafeRead { db in try db.inTransaction { diff --git a/Tests/GRDBTests/DatabaseAggregateTests.swift b/Tests/GRDBTests/DatabaseAggregateTests.swift index e07a827db..3a881b90e 100644 --- a/Tests/GRDBTests/DatabaseAggregateTests.swift +++ b/Tests/GRDBTests/DatabaseAggregateTests.swift @@ -18,7 +18,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningNull() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { nil } + func finalize() -> (any DatabaseValueConvertible)? { nil } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -31,7 +31,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningInt64() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { Int64(1) } + func finalize() -> (any DatabaseValueConvertible)? { Int64(1) } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -45,7 +45,7 @@ class DatabaseAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { 1e100 } + func finalize() -> (any DatabaseValueConvertible)? { 1e100 } } try dbQueue.inDatabase { db in let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self) @@ -57,7 +57,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningString() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { "foo" } + func finalize() -> (any DatabaseValueConvertible)? { "foo" } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -70,7 +70,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningData() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { + func finalize() -> (any DatabaseValueConvertible)? { "foo".data(using: .utf8) } } @@ -85,7 +85,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateReturningCustomValueType() throws { struct Aggregate : DatabaseAggregate { func step(_ values: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { CustomValueType() } + func finalize() -> (any DatabaseValueConvertible)? { CustomValueType() } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -99,11 +99,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentNil() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = dbValues[0].isNull } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -120,11 +120,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentInt64() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = Int64.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -138,11 +138,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentDouble() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = Double.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -156,11 +156,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentString() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = String.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -173,11 +173,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentBlob() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = Data.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -191,11 +191,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateArgumentCustomValueType() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = CustomValueType.fromDatabaseValue(dbValues[0]) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -211,7 +211,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateWithoutArgument() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { "foo" } + func finalize() -> (any DatabaseValueConvertible)? { "foo" } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -232,11 +232,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateOfOneArgument() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = String.fromDatabaseValue(dbValues[0])?.uppercased() } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -259,12 +259,12 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateOfTwoArguments() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } result = ints.reduce(0, +) } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -285,11 +285,11 @@ class DatabaseAggregateTests: GRDBTestCase { func testVariadicFunction() throws { struct Aggregate : DatabaseAggregate { - var result: DatabaseValueConvertible? + var result: (any DatabaseValueConvertible)? mutating func step(_ dbValues: [DatabaseValue]) { result = dbValues.count } - func finalize() -> DatabaseValueConvertible? { result } + func finalize() -> (any DatabaseValueConvertible)? { result } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -308,7 +308,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(message: "custom error message") } - func finalize() -> DatabaseValueConvertible? { fatalError() } + func finalize() -> (any DatabaseValueConvertible)? { fatalError() } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -329,7 +329,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(resultCode: ResultCode(rawValue: 123)) } - func finalize() -> DatabaseValueConvertible? { fatalError() } + func finalize() -> (any DatabaseValueConvertible)? { fatalError() } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -350,7 +350,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message") } - func finalize() -> DatabaseValueConvertible? { fatalError() } + func finalize() -> (any DatabaseValueConvertible)? { fatalError() } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -371,7 +371,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"]) } - func finalize() -> DatabaseValueConvertible? { fatalError() } + func finalize() -> (any DatabaseValueConvertible)? { fatalError() } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -394,7 +394,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateResultThrowingDatabaseErrorWithMessage() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() throws -> DatabaseValueConvertible? { + func finalize() throws -> (any DatabaseValueConvertible)? { throw DatabaseError(message: "custom error message") } } @@ -415,7 +415,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateResultThrowingDatabaseErrorWithCode() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() throws -> DatabaseValueConvertible? { + func finalize() throws -> (any DatabaseValueConvertible)? { throw DatabaseError(resultCode: ResultCode(rawValue: 123)) } } @@ -436,7 +436,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateResultThrowingDatabaseErrorWithMessageAndCode() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() throws -> DatabaseValueConvertible? { + func finalize() throws -> (any DatabaseValueConvertible)? { throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message") } } @@ -457,7 +457,7 @@ class DatabaseAggregateTests: GRDBTestCase { func testAggregateResultThrowingCustomError() throws { struct Aggregate : DatabaseAggregate { func step(_ dbValues: [DatabaseValue]) { } - func finalize() throws -> DatabaseValueConvertible? { + func finalize() throws -> (any DatabaseValueConvertible)? { throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"]) } } @@ -487,7 +487,7 @@ class DatabaseAggregateTests: GRDBTestCase { sum = (sum ?? 0) + int } } - func finalize() throws -> DatabaseValueConvertible? { sum } + func finalize() throws -> (any DatabaseValueConvertible)? { sum } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -505,7 +505,7 @@ class DatabaseAggregateTests: GRDBTestCase { sum = (sum ?? 0) + int } } - func finalize() throws -> DatabaseValueConvertible? { sum } + func finalize() throws -> (any DatabaseValueConvertible)? { sum } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -526,7 +526,7 @@ class DatabaseAggregateTests: GRDBTestCase { init() { Aggregate.onInit?() } deinit { Aggregate.onDeinit?() } func step(_ dbValues: [DatabaseValue]) { } - func finalize() -> DatabaseValueConvertible? { nil } + func finalize() -> (any DatabaseValueConvertible)? { nil } } var allocationCount = 0 var aliveCount = 0 @@ -559,7 +559,7 @@ class DatabaseAggregateTests: GRDBTestCase { func step(_ dbValues: [DatabaseValue]) throws { throw DatabaseError(message: "boo") } - func finalize() -> DatabaseValueConvertible? { fatalError() } + func finalize() -> (any DatabaseValueConvertible)? { fatalError() } } var allocationCount = 0 var aliveCount = 0 @@ -590,7 +590,7 @@ class DatabaseAggregateTests: GRDBTestCase { init() { Aggregate.onInit?() } deinit { Aggregate.onDeinit?() } func step(_ dbValues: [DatabaseValue]) { } - func finalize() throws -> DatabaseValueConvertible? { + func finalize() throws -> (any DatabaseValueConvertible)? { throw DatabaseError(message: "boo") } } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index fb97465bc..5f920fe73 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -62,7 +62,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase { _ db: Database, record: T.Type, date: (T) -> Date?, - databaseValue: DatabaseValueConvertible?, + databaseValue: (any DatabaseValueConvertible)?, with test: (Date?) -> Void) throws { let request = SQLRequest(sql: "SELECT ? AS date", arguments: [databaseValue]) @@ -79,7 +79,13 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase { } /// test the conversion from a database value to a date with a given strategy - private func test(_ db: Database, strategy: Strategy.Type, databaseValue: DatabaseValueConvertible, _ test: (Date) -> Void) throws { + private func test( + _ db: Database, + strategy: Strategy.Type, + databaseValue: some DatabaseValueConvertible, + _ test: (Date) -> Void) + throws + { try self.test(db, record: RecordWithDate.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) }) try self.test(db, record: RecordWithOptionalDate.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) }) } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index c58ed207f..06d11d07b 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -87,7 +87,12 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase { } } - private func test(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) throws { + private func test( + strategy: Strategy.Type, + encodesDate date: Date, + as value: some DatabaseValueConvertible) + throws + { try test(record: RecordWithDate(date: date), expectedStorage: value.databaseValue.storage) try test(record: RecordWithOptionalDate(date: date), expectedStorage: value.databaseValue.storage) } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 81496473b..df99cf9cc 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -18,7 +18,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let count = try dbReader.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") } @@ -41,7 +41,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) async throws { + func test(_ dbReader: some DatabaseReader) async throws { let count = try await dbReader.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") } @@ -57,7 +57,7 @@ class DatabaseReaderTests : GRDBTestCase { } func testReadPreventsDatabaseModification() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { do { try dbReader.read { db in try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") @@ -77,7 +77,7 @@ class DatabaseReaderTests : GRDBTestCase { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadPreventsDatabaseModification() async throws { - func test(_ dbReader: DatabaseReader) async throws { + func test(_ dbReader: some DatabaseReader) async throws { do { try await dbReader.read { db in try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") @@ -104,7 +104,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let count = try dbReader.unsafeRead { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") } @@ -127,7 +127,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) async throws { + func test(_ dbReader: some DatabaseReader) async throws { let count = try await dbReader.unsafeRead { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") } @@ -151,7 +151,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let count = try dbReader.unsafeReentrantRead { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") } @@ -167,7 +167,7 @@ class DatabaseReaderTests : GRDBTestCase { } func testUnsafeReentrantReadIsReentrant() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { try dbReader.unsafeReentrantRead { db1 in try dbReader.unsafeReentrantRead { db2 in try dbReader.unsafeReentrantRead { db3 in @@ -187,7 +187,7 @@ class DatabaseReaderTests : GRDBTestCase { } func testUnsafeReentrantReadIsReentrantFromWrite() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db1 in try dbWriter.unsafeReentrantRead { db2 in try dbWriter.unsafeReentrantRead { db3 in @@ -205,7 +205,7 @@ class DatabaseReaderTests : GRDBTestCase { // MARK: - AsyncRead func testAsyncRead() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) var count: Int? @@ -234,7 +234,7 @@ class DatabaseReaderTests : GRDBTestCase { } func testAsyncReadPreventsDatabaseModification() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbReader.asyncRead { dbResult in @@ -265,7 +265,7 @@ class DatabaseReaderTests : GRDBTestCase { // MARK: - Function func testAddFunction() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let value = try dbReader.read { db -> Int? in let f = DatabaseFunction("f", argumentCount: 0, pure: true) { _ in 0 } db.add(function: f) @@ -285,7 +285,7 @@ class DatabaseReaderTests : GRDBTestCase { // MARK: - Collation func testAddCollation() throws { - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let value = try dbReader.read { db -> Int? in let collation = DatabaseCollation("c") { _, _ in .orderedSame } db.add(collation: collation) @@ -311,7 +311,7 @@ class DatabaseReaderTests : GRDBTestCase { } return dbWriter } - func test(_ source: DatabaseReader) throws { + func test(_ source: some DatabaseReader) throws { let dest = try makeDatabaseQueue(configuration: Configuration()) try source.backup(to: dest) let count = try dest.read { db in diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index b1858773f..1483d1a68 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -5,7 +5,7 @@ func insertItem(_ db: Database, name: String) throws { try db.execute(sql: "INSERT INTO items (name) VALUES (?)", arguments: [name]) } -func fetchAllItemNames(_ dbReader: DatabaseReader) throws -> [String] { +func fetchAllItemNames(_ dbReader: some DatabaseReader) throws -> [String] { try dbReader.read { db in try String.fetchAll(db, sql: "SELECT * FROM items ORDER BY name") } diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index bba11e1f1..2245a8be6 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -53,7 +53,11 @@ class DatabaseUUIDEncodingStrategyTests: GRDBTestCase { } } - private func test(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) throws { + private func test( + strategy: Strategy.Type, + encodesUUID uuid: UUID, + as value: any DatabaseValueConvertible) + throws { try test(record: RecordWithUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) try test(record: RecordWithOptionalUUID(uuid: uuid), expectedStorage: value.databaseValue.storage) } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 036fb5da4..b37c08bb5 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -19,7 +19,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { container[.rowID] = id diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index f6c2eb6f0..646c3852e 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -19,7 +19,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { container[.rowID] = id diff --git a/Tests/GRDBTests/FTS5CustomTokenizerTests.swift b/Tests/GRDBTests/FTS5CustomTokenizerTests.swift index cc89a3487..0c665b2b8 100644 --- a/Tests/GRDBTests/FTS5CustomTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5CustomTokenizerTests.swift @@ -6,7 +6,7 @@ import GRDB // A custom tokenizer that ignores some tokens private final class StopWordsTokenizer : FTS5CustomTokenizer { static let name = "stopWords" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer let ignoredTokens: [String] init(db: Database, arguments: [String]) throws { @@ -62,7 +62,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer { // A custom tokenizer that converts tokens to NFKC so that "fi" can match "fi" (U+FB01: LATIN SMALL LIGATURE FI) private final class NFKCTokenizer : FTS5CustomTokenizer { static let name = "nfkc" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { if arguments.isEmpty { @@ -119,7 +119,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer { // A custom tokenizer that defines synonyms private final class SynonymsTokenizer : FTS5CustomTokenizer { static let name = "synonyms" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer let synonyms: [Set] init(db: Database, arguments: [String]) throws { diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index eac65c0a2..b25b0a013 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -20,7 +20,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { container[.rowID] = id diff --git a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift index b7861e525..78330fcfc 100644 --- a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift @@ -6,7 +6,7 @@ import GRDB // A custom wrapper tokenizer that ignores some tokens private final class StopWordsTokenizer : FTS5WrapperTokenizer { static let name = "stopWords" - var wrappedTokenizer: FTS5Tokenizer + var wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { if arguments.isEmpty { @@ -29,7 +29,7 @@ private final class StopWordsTokenizer : FTS5WrapperTokenizer { // A custom wrapper tokenizer that converts tokens to LatinAscii so that "fi" can match "fi" (U+FB01: LATIN SMALL LIGATURE FI), "ß", "ss", and "æ", "ae". private final class LatinAsciiTokenizer : FTS5WrapperTokenizer { static let name = "latinascii" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { wrappedTokenizer = try db.makeTokenizer(.unicode61()) @@ -46,7 +46,7 @@ private final class LatinAsciiTokenizer : FTS5WrapperTokenizer { // A custom wrapper tokenizer that defines synonyms private final class SynonymsTokenizer : FTS5WrapperTokenizer { static let name = "synonyms" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer let synonyms: [Set] = [["first", "1st"]] init(db: Database, arguments: [String]) throws { @@ -87,7 +87,7 @@ private final class SynonymsTokenizer : FTS5WrapperTokenizer { class CustomizedUnicode61WrappingTokenizer: FTS5WrapperTokenizer { static let name = "custom_unicode61" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer required init(db: Database, arguments: [String]) throws { wrappedTokenizer = try db.makeTokenizer(.unicode61(diacritics: .removeLegacy, separators: ["X"])) diff --git a/Tests/GRDBTests/FoundationNSUUIDTests.swift b/Tests/GRDBTests/FoundationNSUUIDTests.swift index 8cac824f7..cc7243ce8 100644 --- a/Tests/GRDBTests/FoundationNSUUIDTests.swift +++ b/Tests/GRDBTests/FoundationNSUUIDTests.swift @@ -2,7 +2,7 @@ import XCTest import GRDB class FoundationNSUUIDTests: GRDBTestCase { - private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws { + private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: NSUUID?) throws { try makeDatabaseQueue().read { db in if let expectedUUID { let decodedUUID = try NSUUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) diff --git a/Tests/GRDBTests/FoundationUUIDTests.swift b/Tests/GRDBTests/FoundationUUIDTests.swift index 4f0280500..9adfc228a 100644 --- a/Tests/GRDBTests/FoundationUUIDTests.swift +++ b/Tests/GRDBTests/FoundationUUIDTests.swift @@ -3,7 +3,7 @@ import Foundation import GRDB class FoundationUUIDTests: GRDBTestCase { - private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws { + private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: UUID?) throws { try makeDatabaseQueue().read { db in if let expectedUUID { let decodedUUID = try UUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 6ea977a0d..7192b9320 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -147,19 +147,37 @@ class GRDBTestCase: XCTestCase { } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + func assertEqualSQL( + _ db: Database, + _ request: some FetchRequest, + _ sql: String, + file: StaticString = #file, + line: UInt = #line) + throws + { try request.makeStatement(db).makeCursor().next() assertEqualSQL(lastSQLQuery!, sql, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + func assertEqualSQL( + _ databaseReader: some DatabaseReader, + _ request: some FetchRequest, + _ sql: String, + file: StaticString = #file, + line: UInt = #line) + throws + { try databaseReader.unsafeRead { db in try assertEqualSQL(db, request, sql, file: file, line: line) } } - func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { + func sql( + _ databaseReader: some DatabaseReader, + _ request: some FetchRequest) + -> String + { try! databaseReader.unsafeRead { db in try request.makeStatement(db).makeCursor().next() return lastSQLQuery! diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 812ab716b..b2ae7eeea 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -50,7 +50,7 @@ private struct T2: Codable, FetchableRecord, TableRecord { private struct T3: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t3" - static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("t1id"), Column("name")] var t1id: Int64 var name: String } diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 3462bf23c..c4fc94e47 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -185,7 +185,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") // Sequence.contains(): IN operator @@ -239,7 +239,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") // Sequence.contains(): IN operator diff --git a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift index 38f4e1ec5..0ed1a00e9 100644 --- a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift +++ b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift @@ -14,14 +14,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase { func testDefaultPersistenceConflictPolicy() { let record = RecordWithoutPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy + let policy = type(of: record).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .abort) XCTAssertEqual(policy.conflictResolutionForUpdate, .abort) } func testConfigurablePersistenceConflictPolicy() { let record = RecordWithPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy + let policy = type(of: record).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .fail) XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 3bb0562ed..07ce9f3ce 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -27,7 +27,7 @@ private class Person : Record, Hashable { // Record - override static var databaseSelection: [SQLSelectable] { + override static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index c4a8362c6..08ddca00f 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -27,7 +27,7 @@ class RowFromDictionaryTests : RowTestCase { } func testRowValueAtIndex() { - let dictionary: [String: DatabaseValueConvertible?] = ["a": 0, "b": 1, "c": 2] + let dictionary: [String: (any DatabaseValueConvertible)?] = ["a": 0, "b": 1, "c": 2] let row = Row(dictionary) let aIndex = dictionary.distance(from: dictionary.startIndex, to: dictionary.index(forKey: "a")!) @@ -123,7 +123,7 @@ class RowFromDictionaryTests : RowTestCase { } func testRowDatabaseValueAtIndex() throws { - let dictionary: [String: DatabaseValueConvertible?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] + let dictionary: [String: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] let row = Row(dictionary) let nullIndex = dictionary.distance(from: dictionary.startIndex, to: dictionary.index(forKey: "null")!) @@ -140,7 +140,7 @@ class RowFromDictionaryTests : RowTestCase { } func testRowDatabaseValueNamed() throws { - let dictionary: [String: DatabaseValueConvertible?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] + let dictionary: [String: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] let row = Row(dictionary) guard case .null = (row["null"] as DatabaseValue).storage else { XCTFail(); return } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 14434c777..d1c04b7d4 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -220,7 +220,7 @@ extension SQLLiteralTests { do { // Existential let query: SQL = """ - SELECT \(AllColumns() as SQLSelectable) + SELECT \(AllColumns() as any SQLSelectable) FROM player """ @@ -234,7 +234,7 @@ extension SQLLiteralTests { do { // Existential let query: SQL = """ - SELECT \(nil as SQLSelectable?) + SELECT \(nil as (any SQLSelectable)?) """ let (sql, arguments) = try query.build(db) @@ -293,7 +293,7 @@ extension SQLLiteralTests { do { // Existential let query: SQL = """ - INSERT INTO \(tableOf: Player() as TableRecord) DEFAULT VALUES + INSERT INTO \(tableOf: Player() as any TableRecord) DEFAULT VALUES """ let (sql, arguments) = try query.build(db) @@ -309,7 +309,7 @@ extension SQLLiteralTests { try makeDatabaseQueue().inDatabase { db in struct Player: TableRecord { } struct AltPlayer: TableRecord { - static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] } do { let query: SQL = """ @@ -499,7 +499,7 @@ extension SQLLiteralTests { try makeDatabaseQueue().inDatabase { db in let set: Set = [1] let array = ["foo", "bar", "baz"] - let expressions: [SQLExpressible] = [Column("a"), Column("b") + 2] + let expressions: [any SQLExpressible] = [Column("a"), Column("b") + 2] let query: SQL = """ SELECT * FROM player WHERE teamId IN \(set) @@ -742,8 +742,21 @@ extension SQLLiteralTests { do { // Here we test that users can define functions that return - // literal expressions. - func date(_ value: SQLExpressible) -> SQLExpression { + // literal expressions (existential variant). + func date(_ value: any SQLExpressible) -> SQLExpression { + SQL("DATE(\(value))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } + + do { + // Here we test that users can define functions that return + // literal expressions (generic variant). + func date(_ value: some SQLExpressible) -> SQLExpression { SQL("DATE(\(value))").sqlExpression } let createdAt = Column("createdAt") @@ -756,8 +769,22 @@ extension SQLLiteralTests { do { // Here we test that users can still define functions that // return literal expressions with the previously - // supported technique. - func date(_ value: SQLExpressible) -> SQLExpression { + // supported technique (existential variant). + func date(_ value: any SQLExpressible) -> SQLExpression { + SQL("DATE(\(value.sqlExpression))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } + + do { + // Here we test that users can still define functions that + // return literal expressions with the previously + // supported technique (generic variant). + func date(_ value: some SQLExpressible) -> SQLExpression { SQL("DATE(\(value.sqlExpression))").sqlExpression } let createdAt = Column("createdAt") @@ -800,10 +827,15 @@ extension SQLLiteralTests { func testProtocolResolution() throws { // SQL can feed ordering, selection, and expressions. - acceptOrderingTerm(SQL("")) - acceptSelectable(SQL("")) - acceptSpecificExpressible(SQL("")) - acceptExpressible(SQL("")) + acceptOrderingTerm_generic(SQL("")) + acceptSelectable_generic(SQL("")) + acceptSpecificExpressible_generic(SQL("")) + acceptExpressible_generic(SQL("")) + + acceptOrderingTerm_existential(SQL("")) + acceptSelectable_existential(SQL("")) + acceptSpecificExpressible_existential(SQL("")) + acceptExpressible_existential(SQL("")) // SQL can build complex expressions and orderings _ = SQL("") + 1 @@ -812,18 +844,24 @@ extension SQLLiteralTests { // Swift String literals are interpreted as String, even when SQL // is an accepted type. // - // should not compile: XCTAssertEqual(acceptOrderingTerm(""), String(describing: String.self)) - // should not compile: XCTAssertEqual(acceptSelectable(""), String(describing: String.self)) - // should not compile: XCTAssertEqual(acceptSpecificExpressible(""), String(describing: String.self)) - XCTAssertEqual(acceptExpressible(""), String(describing: String.self)) - + // should not compile: XCTAssertEqual(acceptOrderingTerm_generic(""), String(describing: String.self)) + // should not compile: XCTAssertEqual(acceptSelectable_generic(""), String(describing: String.self)) + // should not compile: XCTAssertEqual(acceptSpecificExpressible_generic(""), String(describing: String.self)) + XCTAssertEqual(acceptExpressible_generic(""), String(describing: String.self)) + // should not compile: XCTAssertEqual(acceptOrderingTerm_existential(""), String(describing: String.self)) + // should not compile: XCTAssertEqual(acceptSelectable_existential(""), String(describing: String.self)) + // should not compile: XCTAssertEqual(acceptSpecificExpressible_existential(""), String(describing: String.self)) + XCTAssertEqual(acceptExpressible_existential(""), String(describing: String.self)) + // When a literal can be interpreted as an ordering, a selection, or an // expression, then the expression interpretation is favored. // This test targets TableAlias subscript. // - // should not compile: XCTAssertEqual(overloaded(""), "a") - XCTAssertEqual(overloaded(SQL("")), "SQLSpecificExpressible") - + // should not compile: XCTAssertEqual(overloaded_generic(""), "a") + XCTAssertEqual(overloaded_generic(SQL("")), "SQLSpecificExpressible") + // should not compile: XCTAssertEqual(overloaded_existential(""), "a") + XCTAssertEqual(overloaded_existential(SQL("")), "SQLSpecificExpressible") + // In practice: try makeDatabaseQueue().write { db in struct Player: TableRecord { } @@ -850,33 +888,65 @@ extension SQLLiteralTests { // Support for testProtocolResolution() @discardableResult -private func acceptOrderingTerm(_ x: SQLOrderingTerm) -> String { +private func acceptOrderingTerm_generic(_ x: some SQLOrderingTerm) -> String { String(describing: type(of: x)) } @discardableResult -private func acceptSelectable(_ x: SQLSelectable) -> String { +private func acceptSelectable_generic(_ x: some SQLSelectable) -> String { String(describing: type(of: x)) } @discardableResult -private func acceptSpecificExpressible(_ x: SQLSpecificExpressible) -> String { +private func acceptSpecificExpressible_generic(_ x: some SQLSpecificExpressible) -> String { String(describing: type(of: x)) } @discardableResult -private func acceptExpressible(_ x: SQLExpressible) -> String { +private func acceptExpressible_generic(_ x: some SQLExpressible) -> String { String(describing: type(of: x)) } -private func overloaded(_ x: SQLOrderingTerm) -> String { +private func overloaded_generic(_ x: some SQLOrderingTerm) -> String { "SQLOrderingTerm" } -private func overloaded(_ x: SQLSelectable) -> String { +private func overloaded_generic(_ x: some SQLSelectable) -> String { "SQLSelectable" } -private func overloaded(_ x: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String { +private func overloaded_generic(_ x: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String { + "SQLSpecificExpressible" +} + +@discardableResult +private func acceptOrderingTerm_existential(_ x: any SQLOrderingTerm) -> String { + String(describing: type(of: x)) +} + +@discardableResult +private func acceptSelectable_existential(_ x: any SQLSelectable) -> String { + String(describing: type(of: x)) +} + +@discardableResult +private func acceptSpecificExpressible_existential(_ x: any SQLSpecificExpressible) -> String { + String(describing: type(of: x)) +} + +@discardableResult +private func acceptExpressible_existential(_ x: any SQLExpressible) -> String { + String(describing: type(of: x)) +} + +private func overloaded_existential(_ x: any SQLOrderingTerm) -> String { + "SQLOrderingTerm" +} + +private func overloaded_existential(_ x: any SQLSelectable) -> String { + "SQLSelectable" +} + +private func overloaded_existential(_ x: any SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String { "SQLSpecificExpressible" } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 959a1d4f4..b3263d651 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -98,7 +98,7 @@ class SelectStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") - let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] + let ageDicts: [[String: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] let counts = try ageDicts.map { dic -> Int in // Make sure we don't trigger a failible initializer let arguments: StatementArguments = StatementArguments(dic) @@ -112,7 +112,7 @@ class SelectStatementTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age") - let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] + let ageDicts: [[String: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]] let counts = try ageDicts.map { ageDict -> Int in statement.arguments = StatementArguments(ageDict) return try Int.fetchOne(statement)! diff --git a/Tests/GRDBTests/StatementArgumentsTests.swift b/Tests/GRDBTests/StatementArgumentsTests.swift index b1275191b..41f873d0e 100644 --- a/Tests/GRDBTests/StatementArgumentsTests.swift +++ b/Tests/GRDBTests/StatementArgumentsTests.swift @@ -81,7 +81,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) + let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") updateStatement.arguments = arguments @@ -101,7 +101,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) + let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") try updateStatement.setArguments(arguments) @@ -139,7 +139,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?]) + let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)") updateStatement.setUncheckedArguments(arguments) @@ -232,7 +232,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") updateStatement.arguments = arguments @@ -252,7 +252,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") try updateStatement.setArguments(arguments) @@ -290,7 +290,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)") updateStatement.setUncheckedArguments(arguments) @@ -392,7 +392,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") updateStatement.arguments = arguments @@ -412,7 +412,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") try updateStatement.setArguments(arguments) @@ -450,7 +450,7 @@ class StatementArgumentsTests: GRDBTestCase { try dbQueue.inDatabase { db in let name = "Arthur" let age = 42 - let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?]) + let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?]) let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)") updateStatement.setUncheckedArguments(arguments) diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index d463ba265..f022e7888 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase { func testExtendedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -116,7 +116,7 @@ class TableRecordTests: GRDBTestCase { func testRestrictedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" - static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] + static let databaseSelection: [any SQLSelectable] = [Column("a"), Column("b")] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 386bbe21d..730edc103 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -121,7 +121,7 @@ extension Artwork : FetchableRecord, PersistableRecord { } class TransactionObserverTests: GRDBTestCase { - private func setupArtistDatabase(in dbWriter: DatabaseWriter) throws { + private func setupArtistDatabase(in dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: """ CREATE TABLE artists ( diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index c5feaf226..c14e8c6dd 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -52,7 +52,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") - let persons: [[DatabaseValueConvertible?]] = [ + let persons: [[(any DatabaseValueConvertible)?]] = [ ["Arthur", 41], ["Barbara", nil], ] @@ -79,7 +79,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)") - let persons: [[DatabaseValueConvertible?]] = [ + let persons: [[(any DatabaseValueConvertible)?]] = [ ["Arthur", 41], ["Barbara", nil], ] @@ -107,7 +107,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") - let persons: [[String: DatabaseValueConvertible?]] = [ + let persons: [[String: (any DatabaseValueConvertible)?]] = [ ["name": "Arthur", "age": 41], ["name": "Barbara", "age": nil], ] @@ -134,7 +134,7 @@ class UpdateStatementTests : GRDBTestCase { try dbQueue.inTransaction { db in let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)") - let persons: [[String: DatabaseValueConvertible?]] = [ + let persons: [[String: (any DatabaseValueConvertible)?]] = [ ["name": "Arthur", "age": 41], ["name": "Barbara", "age": nil], ] diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index d5085dcc9..1cb60f364 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -11,7 +11,7 @@ class ValueObservationPrintTests: GRDBTestCase { } /// Helps dealing with various SQLite versions - private func region(sql: String, in dbReader: DatabaseReader) throws -> String { + private func region(sql: String, in dbReader: some DatabaseReader) throws -> String { try dbReader.read { db in try db .makeStatement(sql: sql) diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 297d54662..217d1d115 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -567,7 +567,7 @@ extension GRDBTestCase { func assertValueObservation( _ observation: ValueObservation, - fails testFailure: (Failure, DatabaseWriter) throws -> Void, + fails testFailure: (Failure, any DatabaseWriter) throws -> Void, setup: (Database) throws -> Void, file: StaticString = #file, line: UInt = #line) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 51570a3c5..45a0cffa1 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -542,7 +542,7 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and deallocate cancellable after second change - var cancellable: DatabaseCancellable? + var cancellable: (any DatabaseCancellable)? cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, @@ -588,7 +588,7 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and cancel cancellable after second change - var cancellable: DatabaseCancellable! + var cancellable: (any DatabaseCancellable)! cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, @@ -626,7 +626,7 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: DatabaseCancellable? = nil + var cancellable: (any DatabaseCancellable)? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning var shouldStopObservation = false let observation = ValueObservation( @@ -670,7 +670,7 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: DatabaseCancellable? = nil + var cancellable: (any DatabaseCancellable)? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning var shouldStopObservation = false let observation = ValueObservation( diff --git a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift index 9921c19d8..3195e3003 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift @@ -29,7 +29,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord { i9 = row[9] } - static let databaseSelection: [SQLSelectable] = [ + static let databaseSelection: [any SQLSelectable] = [ Column("i0"), Column("i1"), Column("i2"), From 77d8a46039d4e58cc7b2024be37f190ab7599197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Apr 2023 12:30:55 +0200 Subject: [PATCH 2/9] Remove obsolete TODOs --- GRDB/QueryInterface/Schema/TableDefinition.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 51fae27e6..fc21127ec 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -2,7 +2,6 @@ extension Database { // MARK: - Database Schema - // TODO: deprecate just before GRDB 6 /// Creates a database table. /// /// For example: @@ -321,7 +320,6 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } - // TODO: deprecate just before GRDB 6 /// Creates an index. /// /// For example: From 54007a9ce141bf8cec5a3083b5c4ce6bb59af4b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Apr 2023 11:37:22 +0200 Subject: [PATCH 3/9] Refactor demo apps for enhanced configuration management --- .../xcschemes/GRDBAsyncDemo.xcscheme | 7 ++ .../GRDBAsyncDemo/AppDatabase.swift | 88 ++++++++++++++++-- .../GRDBAsyncDemo/Persistence.swift | 35 ++++---- .../GRDBAsyncDemoTests/AppDatabaseTests.swift | 16 ++-- .../PlayerRequestTests.swift | 4 +- .../GRDBAsyncDemoTests/PlayerTests.swift | 10 +-- .../xcschemes/GRDBCombineDemo.xcscheme | 7 ++ .../GRDBCombineDemo/AppDatabase.swift | 89 ++++++++++++++++--- .../GRDBCombineDemo/Persistence.swift | 35 ++++---- .../AppDatabaseTests.swift | 16 ++-- .../PlayerRequestTests.swift | 4 +- .../GRDBCombineDemoTests/PlayerTests.swift | 10 +-- .../xcschemes/GRDBDemoiOS.xcscheme | 7 ++ .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 82 +++++++++++++++-- .../GRDBDemoiOS/GRDBDemoiOS/Persistence.swift | 29 +++--- .../GRDBDemoiOSTests/AppDatabaseTests.swift | 16 ++-- .../GRDBDemoiOSTests/PlayerTests.swift | 10 +-- 17 files changed, 355 insertions(+), 110 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme index f62d0a386..aeb65e487 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme @@ -61,6 +61,13 @@ ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj"> + + + + +/// It applies the practices recommended at +/// . +/// +/// You create an `AppDatabase` with a connection to an SQLite database +/// (see ). +/// +/// Create those connections with a configuration returned from +/// `AppDatabase/makeConfiguration(_:)`. +/// +/// For example: +/// +/// ```swift +/// // Create an in-memory AppDatabase +/// let config = AppDatabase.makeConfiguration() +/// let dbQueue = try DatabaseQueue(configuration: config) +/// let appDatabase = try AppDatabase(dbQueue) +/// ``` struct AppDatabase { - /// Creates an `AppDatabase`, and make sure the database schema is ready. + /// Creates an `AppDatabase`, and makes sure the database schema + /// is ready. + /// + /// - important: Create the `DatabaseWriter` with a configuration + /// returned by ``makeConfiguration(_:)``. init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) @@ -19,18 +39,67 @@ struct AppDatabase { /// /// See private let dbWriter: any DatabaseWriter +} + +// MARK: - Database Configuration + +extension AppDatabase { + private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") + /// Returns a database configuration suited for `PlayerRepository`. + /// + /// SQL statements are logged if the `SQL_TRACE` environment variable + /// is set. + /// + /// - parameter base: A base configuration. + public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { + var config = base + + // An opportunity to add required custom SQL functions or + // collations, if needed: + // config.prepareDatabase { db in + // db.add(function: ...) + // } + + // Log SQL statements if the `SQL_TRACE` environment variable is set. + // See + if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { + config.prepareDatabase { db in + db.trace { + // It's ok to log statements publicly. Sensitive + // information (statement arguments) are not logged + // unless config.publicStatementArguments is set + // (see below). + os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) + } + } + } + +#if DEBUG + // Protect sensitive information by enabling verbose debugging in + // DEBUG builds only. + // See + config.publicStatementArguments = true +#endif + + return config + } +} + +// MARK: - Database Migrations + +extension AppDatabase { /// The DatabaseMigrator that defines the database schema. /// /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - #if DEBUG +#if DEBUG // Speed up development by nuking the database when migrations change // See migrator.eraseDatabaseOnSchemaChange = true - #endif +#endif migrator.registerMigration("createPlayer") { db in // Create a table @@ -52,6 +121,7 @@ struct AppDatabase { } // MARK: - Database Access: Writes +// The write methods execute invariant-preserving database transactions. extension AppDatabase { /// A validation error that prevents some players from being saved into @@ -127,8 +197,8 @@ extension AppDatabase { } } } - - static let uiTestPlayers = [ + + private static let uiTestPlayers = [ Player(id: nil, name: "Arthur", score: 5), Player(id: nil, name: "Barbara", score: 6), Player(id: nil, name: "Craig", score: 8), @@ -137,7 +207,7 @@ extension AppDatabase { Player(id: nil, name: "Frederik", score: 2), Player(id: nil, name: "Gilbert", score: 7), Player(id: nil, name: "Henriette", score: 3)] - + func createPlayersForUITests() throws { try dbWriter.write { db in try AppDatabase.uiTestPlayers.forEach { player in diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift index 7670af424..05b011578 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift @@ -7,26 +7,31 @@ extension AppDatabase { private static func makeShared() -> AppDatabase { do { - // Pick a folder for storing the SQLite database, as well as - // the various temporary files created during normal database - // operations (https://sqlite.org/tempfiles.html). - let fileManager = FileManager() - let folderURL = try fileManager - .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - .appendingPathComponent("database", isDirectory: true) - + // Apply recommendations from + // + // + // Create the "Application Support/Database" directory if needed + let fileManager = FileManager.default + let appSupportURL = try fileManager.url( + for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true) + // Support for tests: delete the database if requested if CommandLine.arguments.contains("-reset") { - try? fileManager.removeItem(at: folderURL) + try? fileManager.removeItem(at: directoryURL) } // Create the database folder if needed - try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - // Connect to a database on disk - // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections - let dbURL = folderURL.appendingPathComponent("db.sqlite") - let dbPool = try DatabasePool(path: dbURL.path) + // Open or create the database + let databaseURL = directoryURL.appendingPathComponent("db.sqlite") + NSLog("Database stored at \(databaseURL.path)") + let dbPool = try DatabasePool( + path: databaseURL.path, + // Use default AppDatabase configuration + configuration: AppDatabase.makeConfiguration()) // Create the AppDatabase let appDatabase = try AppDatabase(dbPool) @@ -59,7 +64,7 @@ extension AppDatabase { static func empty() -> AppDatabase { // Connect to an in-memory database // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections - let dbQueue = try! DatabaseQueue() + let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration()) return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index 29de329fe..b736e9077 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() async throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_updates() async throws { // Given a players database that contains a player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = try await dbQueue.write { db in try Player(id: nil, name: "Arthur", score: 100).inserted(db) @@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() async throws { // Given a players database that contains four players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) let playerIds: [Int64] = try await dbQueue.write { db in _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) @@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase { func test_deleteAllPlayers() async throws { // Given a players database that contains players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) try await dbQueue.write { db in _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) @@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase { func test_refreshPlayers_populates_an_empty_database() async throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we refresh players @@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -127,7 +127,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift index 914a24173..2675f82d5 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift @@ -5,7 +5,7 @@ import GRDB class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byName_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) @@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift index 3b9df1506..edd872684 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme index 2f5334935..0cbf7bf5c 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme @@ -61,6 +61,13 @@ ReferencedContainer = "container:GRDBCombineDemo.xcodeproj"> + + + + +/// It applies the practices recommended at +/// . +/// +/// You create an `AppDatabase` with a connection to an SQLite database +/// (see ). +/// +/// Create those connections with a configuration returned from +/// `AppDatabase/makeConfiguration(_:)`. +/// +/// For example: +/// +/// ```swift +/// // Create an in-memory AppDatabase +/// let config = AppDatabase.makeConfiguration() +/// let dbQueue = try DatabaseQueue(configuration: config) +/// let appDatabase = try AppDatabase(dbQueue) +/// ``` struct AppDatabase { - /// Creates an `AppDatabase`, and make sure the database schema is ready. + /// Creates an `AppDatabase`, and makes sure the database schema + /// is ready. + /// + /// - important: Create the `DatabaseWriter` with a configuration + /// returned by ``makeConfiguration(_:)``. init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) @@ -20,18 +39,67 @@ struct AppDatabase { /// /// See private let dbWriter: any DatabaseWriter +} + +// MARK: - Database Configuration + +extension AppDatabase { + private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") + /// Returns a database configuration suited for `PlayerRepository`. + /// + /// SQL statements are logged if the `SQL_TRACE` environment variable + /// is set. + /// + /// - parameter base: A base configuration. + public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { + var config = base + + // An opportunity to add required custom SQL functions or + // collations, if needed: + // config.prepareDatabase { db in + // db.add(function: ...) + // } + + // Log SQL statements if the `SQL_TRACE` environment variable is set. + // See + if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { + config.prepareDatabase { db in + db.trace { + // It's ok to log statements publicly. Sensitive + // information (statement arguments) are not logged + // unless config.publicStatementArguments is set + // (see below). + os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) + } + } + } + +#if DEBUG + // Protect sensitive information by enabling verbose debugging in + // DEBUG builds only. + // See + config.publicStatementArguments = true +#endif + + return config + } +} + +// MARK: - Database Migrations + +extension AppDatabase { /// The DatabaseMigrator that defines the database schema. /// /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - #if DEBUG +#if DEBUG // Speed up development by nuking the database when migrations change // See migrator.eraseDatabaseOnSchemaChange = true - #endif +#endif migrator.registerMigration("createPlayer") { db in // Create a table @@ -53,6 +121,7 @@ struct AppDatabase { } // MARK: - Database Access: Writes +// The write methods execute invariant-preserving database transactions. extension AppDatabase { /// A validation error that prevents some players from being saved into @@ -128,8 +197,8 @@ extension AppDatabase { } } } - - static let uiTestPlayers = [ + + private static let uiTestPlayers = [ Player(id: nil, name: "Arthur", score: 5), Player(id: nil, name: "Barbara", score: 6), Player(id: nil, name: "Craig", score: 8), @@ -138,7 +207,7 @@ extension AppDatabase { Player(id: nil, name: "Frederik", score: 2), Player(id: nil, name: "Gilbert", score: 7), Player(id: nil, name: "Henriette", score: 3)] - + func createPlayersForUITests() throws { try dbWriter.write { db in try AppDatabase.uiTestPlayers.forEach { player in diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift index 7670af424..05b011578 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift @@ -7,26 +7,31 @@ extension AppDatabase { private static func makeShared() -> AppDatabase { do { - // Pick a folder for storing the SQLite database, as well as - // the various temporary files created during normal database - // operations (https://sqlite.org/tempfiles.html). - let fileManager = FileManager() - let folderURL = try fileManager - .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - .appendingPathComponent("database", isDirectory: true) - + // Apply recommendations from + // + // + // Create the "Application Support/Database" directory if needed + let fileManager = FileManager.default + let appSupportURL = try fileManager.url( + for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true) + // Support for tests: delete the database if requested if CommandLine.arguments.contains("-reset") { - try? fileManager.removeItem(at: folderURL) + try? fileManager.removeItem(at: directoryURL) } // Create the database folder if needed - try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - // Connect to a database on disk - // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections - let dbURL = folderURL.appendingPathComponent("db.sqlite") - let dbPool = try DatabasePool(path: dbURL.path) + // Open or create the database + let databaseURL = directoryURL.appendingPathComponent("db.sqlite") + NSLog("Database stored at \(databaseURL.path)") + let dbPool = try DatabasePool( + path: databaseURL.path, + // Use default AppDatabase configuration + configuration: AppDatabase.makeConfiguration()) // Create the AppDatabase let appDatabase = try AppDatabase(dbPool) @@ -59,7 +64,7 @@ extension AppDatabase { static func empty() -> AppDatabase { // Connect to an in-memory database // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections - let dbQueue = try! DatabaseQueue() + let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration()) return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift index b1f82c589..f9343671e 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_updates() throws { // Given a players database that contains a player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in @@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() throws { // Given a players database that contains four players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase { func test_deleteAllPlayers() throws { // Given a players database that contains players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase { func test_refreshPlayers_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we refresh players @@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift index 403d325ae..151d8e41e 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift @@ -5,7 +5,7 @@ import GRDB class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byName_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) @@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase { func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { // Given a players database that contains two players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 1000) diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift index bb732c60f..4262d8023 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme index 9f0ec648b..20c4615d2 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme @@ -61,6 +61,13 @@ ReferencedContainer = "container:GRDBDemoiOS.xcodeproj"> + + + + -final class AppDatabase { - /// Creates an `AppDatabase`, and make sure the database schema is ready. +/// . +/// +/// You create an `AppDatabase` with a connection to an SQLite database +/// (see ). +/// +/// Create those connections with a configuration returned from +/// `AppDatabase/makeConfiguration(_:)`. +/// +/// For example: +/// +/// ```swift +/// // Create an in-memory AppDatabase +/// let config = AppDatabase.makeConfiguration() +/// let dbQueue = try DatabaseQueue(configuration: config) +/// let appDatabase = try AppDatabase(dbQueue) +/// ``` +struct AppDatabase { + /// Creates an `AppDatabase`, and makes sure the database schema + /// is ready. + /// + /// - important: Create the `DatabaseWriter` with a configuration + /// returned by ``makeConfiguration(_:)``. init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) @@ -18,18 +38,67 @@ final class AppDatabase { /// /// See private let dbWriter: any DatabaseWriter +} + +// MARK: - Database Configuration + +extension AppDatabase { + private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") + /// Returns a database configuration suited for `PlayerRepository`. + /// + /// SQL statements are logged if the `SQL_TRACE` environment variable + /// is set. + /// + /// - parameter base: A base configuration. + public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { + var config = base + + // An opportunity to add required custom SQL functions or + // collations, if needed: + // config.prepareDatabase { db in + // db.add(function: ...) + // } + + // Log SQL statements if the `SQL_TRACE` environment variable is set. + // See + if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { + config.prepareDatabase { db in + db.trace { + // It's ok to log statements publicly. Sensitive + // information (statement arguments) are not logged + // unless config.publicStatementArguments is set + // (see below). + os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) + } + } + } + +#if DEBUG + // Protect sensitive information by enabling verbose debugging in + // DEBUG builds only. + // See + config.publicStatementArguments = true +#endif + + return config + } +} + +// MARK: - Database Migrations + +extension AppDatabase { /// The DatabaseMigrator that defines the database schema. /// /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - #if DEBUG +#if DEBUG // Speed up development by nuking the database when migrations change // See migrator.eraseDatabaseOnSchemaChange = true - #endif +#endif migrator.registerMigration("createPlayer") { db in // Create a table @@ -51,6 +120,7 @@ final class AppDatabase { } // MARK: - Database Access: Writes +// The write methods execute invariant-preserving database transactions. extension AppDatabase { /// Saves (inserts or updates) a player. When the method returns, the diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift index 0b0c44c33..96267e684 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift @@ -7,19 +7,24 @@ extension AppDatabase { private static func makeShared() -> AppDatabase { do { - // Create a folder for storing the SQLite database, as well as - // the various temporary files created during normal database - // operations (https://sqlite.org/tempfiles.html). - let fileManager = FileManager() - let folderURL = try fileManager - .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - .appendingPathComponent("database", isDirectory: true) - try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) + // Apply recommendations from + // + // + // Create the "Application Support/Database" directory if needed + let fileManager = FileManager.default + let appSupportURL = try fileManager.url( + for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - // Connect to a database on disk - // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections - let dbURL = folderURL.appendingPathComponent("db.sqlite") - let dbPool = try DatabasePool(path: dbURL.path) + // Open or create the database + let databaseURL = directoryURL.appendingPathComponent("db.sqlite") + NSLog("Database stored at \(databaseURL.path)") + let dbPool = try DatabasePool( + path: databaseURL.path, + // Use default AppDatabase configuration + configuration: AppDatabase.makeConfiguration()) // Create the AppDatabase let appDatabase = try AppDatabase(dbPool) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift index 9815727ac..2c359a898 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift @@ -5,7 +5,7 @@ import GRDB class AppDatabaseTests: XCTestCase { func test_database_schema() throws { // Given an empty database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) // When we instantiate an AppDatabase _ = try AppDatabase(dbQueue) @@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_inserts() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we save a new player @@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase { func test_savePlayer_updates() throws { // Given a players database that contains a player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in @@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase { func test_deletePlayers() throws { // Given a players database that contains four players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase { func test_deleteAllPlayers() throws { // Given a players database that contains players - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player1 = Player(id: nil, name: "Arthur", score: 100) var player2 = Player(id: nil, name: "Barbara", score: 200) @@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase { func test_refreshPlayers_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we refresh players @@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) // When we create random players @@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase { func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { // Given a players database that contains one player - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) let appDatabase = try AppDatabase(dbQueue) var player = Player(id: nil, name: "Arthur", score: 100) try dbQueue.write { db in diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift index 506f5dfbc..64d1c1d2b 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift @@ -8,7 +8,7 @@ class PlayerTests: XCTestCase { func testInsert() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player @@ -23,7 +23,7 @@ class PlayerTests: XCTestCase { func testRoundtrip() throws { // Given an empty players database - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) // When we insert a player and fetch the player with the same id @@ -42,7 +42,7 @@ class PlayerTests: XCTestCase { func testOrderedByScore() throws { // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -64,7 +64,7 @@ class PlayerTests: XCTestCase { func testOrderedByScoreSortsIdenticalScoresByName() throws { // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) @@ -86,7 +86,7 @@ class PlayerTests: XCTestCase { func testOrderedByName() throws { // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue() + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) _ = try AppDatabase(dbQueue) var player1 = Player(id: 1, name: "Arthur", score: 100) var player2 = Player(id: 2, name: "Barbara", score: 200) From 52a3d6ba236b95c80135088ab6244466206355be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Apr 2023 16:30:11 +0200 Subject: [PATCH 4/9] Move the "Recommended Practices for Designing Record Types" to DocC --- Documentation/AssociationsBasics.md | 6 +- .../GRDBAsyncDemo/AppDatabase.swift | 3 - .../GRDBAsyncDemo/GRDBAsyncDemo/Player.swift | 3 +- .../DemoApps/GRDBAsyncDemo/README.md | 2 +- .../GRDBCombineDemo/AppDatabase.swift | 3 - .../GRDBCombineDemo/Player.swift | 3 +- .../DemoApps/GRDBCombineDemo/README.md | 2 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 3 - .../GRDBDemoiOS/GRDBDemoiOS/Player.swift | 3 +- Documentation/DemoApps/GRDBDemoiOS/README.md | 2 +- .../GoodPracticesForDesigningRecordTypes.md | 834 +----------------- Documentation/QueryInterfaceOrganization.md | 2 +- Documentation/WhyAdoptGRDB.md | 4 +- GRDB/Documentation.docc/Documentation.md | 3 +- .../RecordRecommendedPractices.md | 538 +++++++++++ README.md | 6 +- 16 files changed, 556 insertions(+), 861 deletions(-) create mode 100644 GRDB/Documentation.docc/RecordRecommendedPractices.md diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index ccd1e2832..1ba5a8c4d 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -2000,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco - [Decoding a Joined Request with a Decodable Record] - [Decoding a Joined Request with FetchableRecord] - [Debugging Request Decoding] -- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter. +- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter. ## The Structure of a Joined Request @@ -2860,7 +2860,7 @@ extension DerivableRequest { } ``` -See [Good Practices for Designing Record Types] for more information. +See [Recommended Practices for Designing Record Types] for more information. ## Known Issues @@ -2999,7 +2999,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter [query interface requests]: ../README.md#requests [TableRecord]: ../README.md#tablerecord-protocol -[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md +[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices [regular aggregating methods]: ../README.md#fetching-aggregated-values [Record class]: ../README.md#record-class [EncodableRecord]: ../README.md#persistablerecord-protocol diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift index 30ffb5d1e..e19cc7af7 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift @@ -4,9 +4,6 @@ import os.log /// A database of players. /// -/// It applies the practices recommended at -/// . -/// /// You create an `AppDatabase` with a connection to an SQLite database /// (see ). /// diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift index 8513cd480..7876b049d 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift @@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// Define some player requests used by the application. /// -/// See -/// See +/// See extension DerivableRequest { /// A request of players ordered by name. /// diff --git a/Documentation/DemoApps/GRDBAsyncDemo/README.md b/Documentation/DemoApps/GRDBAsyncDemo/README.md index 6fc5a85e2..0bcc10917 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/README.md +++ b/Documentation/DemoApps/GRDBAsyncDemo/README.md @@ -14,7 +14,7 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). - How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation). -- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). +- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). - How to feed SwiftUI previews with a transient database. **Files of interest:** diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index 671b92a78..c4b5a5e92 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -4,9 +4,6 @@ import os.log /// A database of players. /// -/// It applies the practices recommended at -/// . -/// /// You create an `AppDatabase` with a connection to an SQLite database /// (see ). /// diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 8513cd480..7876b049d 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// Define some player requests used by the application. /// -/// See -/// See +/// See extension DerivableRequest { /// A request of players ordered by name. /// diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md index 5bb162284..6b2ccec0f 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/README.md +++ b/Documentation/DemoApps/GRDBCombineDemo/README.md @@ -14,7 +14,7 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). - How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers. -- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). +- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). - How to feed SwiftUI previews with a transient database. **Files of interest:** diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 2ff556dd3..8c38cd2a7 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -3,9 +3,6 @@ import os.log /// `AppDatabase` lets the application access the database. /// -/// It applies the pratices recommended at -/// . -/// /// You create an `AppDatabase` with a connection to an SQLite database /// (see ). /// diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 7c82fe2cf..82204b62c 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -68,8 +68,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { /// Define some player requests used by the application. /// -/// See -/// See +/// See extension DerivableRequest { /// A request of players ordered by name. /// diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index 098f37d79..ab854697c 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -14,7 +14,7 @@ The topics covered in this demo are: - How to setup a database in an iOS app. - How to define a simple [Codable Record](../../../README.md#codable-records). - How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation). -- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). +- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). **Files of interest:** diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 60f4e73eb..1bcdbd223 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -1,836 +1,4 @@ Good Practices for Designing Record Types ========================================= -This guide aims at helping you leverage the best of GRDB [records] and [associations]. - -Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application. - -To support this guide, we'll design a simple library application that lets the user crawl through books and their authors. - -- [Trust SQLite More Than Yourself] -- [Persistable Record Types are Responsible for Their Tables] -- [Record Types Hide Intimate Database Details] -- [Singleton Records] -- [Define Record Requests] -- [Compose Records] -- [How to Design Database Managers] -- [Observe the Database and Refetch when Needed] - - -## Trust SQLite More Than Yourself - -It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same. - -This is why we recommend defining a **robust database schema** even before playing with record types. - -SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk. - -This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data. - -For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write: - -```swift -var migrator = DatabaseMigrator() - -migrator.registerMigration("createLibrary") { db in - try db.create(table: "author") { t in // (1) - t.autoIncrementedPrimaryKey("id") // (2) - t.column("name", .text).notNull() // (3) - t.column("country", .text) // (4) - } - - try db.create(table: "book") { t in - t.autoIncrementedPrimaryKey("id") - t.column("title", .text).notNull() // (5) - t.column("authorId", .integer) // (6) - .notNull() // (7) - .indexed() // (8) - .references("author", onDelete: .cascade) // (9) - } -} - -try migrator.migrate(dbQueue) -``` - -1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. -2. Each author has a unique id. -3. An author must have a name. -4. The country of an author is not always known. -5. A book must have a title. -6. The `book.authorId` column is used to link a book to the author it belongs to. -7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. -8. The `book.authorId` column is indexed in order to ease the selection of an author's books. -9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. - -Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc. - -> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema. -> -> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations]. -> -> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**: -> -> ```swift -> migrator.registerMigration("createLibrary") { db in -> // RECOMMENDED -> try db.create(table: "author") { t in -> t.autoIncrementedPrimaryKey("id") -> ... -> } -> -> // NOT RECOMMENDED -> try db.create(table: Author.databaseTableName) { t in -> t.autoIncrementedPrimaryKey(Author.Columns.id.name) -> ... -> } -> } -> ``` -> -> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application. -> -> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**. - - -## Persistable Record Types are Responsible for Their Tables - -Define one record type per database table, and make it adopt a [PersistableRecord] protocol. - -In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records. - -```swift -struct Author: Codable, Identifiable { - var id: Int64? - var name: String - var country: String? -} - -struct Book: Codable, Identifiable { - var id: Int64? - var authorId: Int64 - var title: String -} -``` - -We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method: - -```swift -// Add Database access - -extension Author: FetchableRecord, MutablePersistableRecord { - // Update auto-incremented id upon successful insertion - mutating func didInsert(_ inserted: InsertionSuccess) { - id = inserted.rowID - } -} - -extension Book: FetchableRecord, MutablePersistableRecord { - // Update auto-incremented id upon successful insertion - mutating func didInsert(_ inserted: InsertionSuccess) { - id = inserted.rowID - } -} -``` - -That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. - -> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property. -> -> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method: -> -> ```swift -> try dbQueue.write { db in -> var author = Author(id: nil, name: "Hermann Melville", country: "United States") -> try author.insert(db) -> print(author.id!) // Guaranteed non-nil id -> } -> ``` -> -> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods: -> -> ```swift -> let authorID: Int64 = ... -> let author: Author? = try dbQueue.read { db in -> try Author.fetchOne(db, id: authorID) -> } -> ``` - -Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table! - - -## Record Types Hide Intimate Database Details - -The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.) - -Sometimes, it happens that raw database column names and types are not a very good fit for the application. - -Let's look at three examples: - -1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.): - - ```swift - try db.create(table: "book") { t in - ... - t.column("kind", .text).notNull() - } - ``` - - In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead: - - ```swift - struct Book: Codable { - enum Kind: String, Codable { - case novel, poems, essay, play - } - var id: Int64? - var authorId: Int64 - var title: String - var kind: Kind - } - ``` - - In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance: - - ```swift - extension Book.Kind: DatabaseValueConvertible { } - ``` - - > :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database. - -2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. - - When this happens, keep column properties private, and provide sensible accessors instead: - - ```swift - struct Place: Codable { - var id: Int64? - var name: String - private var latitude: CLLocationDegrees - private var longitude: CLLocationDegrees - - var coordinate: CLLocationCoordinate2D { - get { - CLLocationCoordinate2D(latitude: latitude, longitude: longitude) - } - set { - latitude = newValue.latitude - longitude = newValue.longitude - } - } - } - ``` - - > :bulb: Private properties make it possible to hide raw columns from the rest of the application. - -3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices. - - ```swift - struct Product: Codable { - var id: Int64? - var name: String - private var priceCents: Int - - var price: Decimal { - get { Decimal(priceCents) / 100 } - set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue } - } - } - ``` - - > :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface. - -**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database. - - -## Singleton Records - -**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row. - -The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done! - - -## Define Record Requests - -Now that we have record types that are able to read and write in the database, we'd like to put them to good use. - -> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc. - -When your record type is a [Codable Record], derive columns from the [CodingKeys] enum: - -```swift -// For a codable record -extension Author { - // Define database columns from CodingKeys - enum Columns { - static let id = Column(CodingKeys.id) - static let name = Column(CodingKeys.name) - static let country = Column(CodingKeys.country) - } -} -``` - -Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol: - -```swift -// For a non-codable record -extension Author { - // Define database columns as an enum - enum Columns: String, ColumnExpression { - case id, name, country - } -} -``` - -Those columns let you define requests: - -```swift -try dbQueue.read { db in - // Order authors by name, in a localized case-insensitive fashion - let sortedAuthors: [Author] = try Author.all() - .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) - .fetchAll(db) - - // French authors - let frenchAuthors: [Author] = try Author.all() - .filter(Author.Columns.country == "France") - .fetchAll(db) -} -``` - -> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol. - -When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift). - -To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc: - -```swift -// Author requests -extension DerivableRequest { - /// Order authors by name, in a localized case-insensitive fashion - func orderByName() -> Self { - let name = Author.Columns.name - return order(name.collating(.localizedCaseInsensitiveCompare)) - } - - /// Filters authors from a country - func filter(country: String) -> Self { - filter(Author.Columns.country == country) - } - - /// Filters authors with at least one book - func havingBooks() -> Self { - having(Author.books.isEmpty == false) - } -} -``` - -Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style: - -```swift -try dbQueue.read { db in - let sortedAuthors: [Author] = try Author.all() - .orderByName() - .fetchAll(db) - - let frenchAuthors: [Author] = try Author.all() - .filter(country: "France") - .fetchAll(db) - - let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all() - .filter(country: "Spain") - .havingBooks() - .orderByName() - .fetchAll(db) -} -``` - -Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors: - -```swift -// Book requests -extension DerivableRequest { - /// Filters books by kind - func filter(kind: Book.Kind) -> Self { - filter(Book.Columns.kind == kind) - } - - /// Filters books from a country - func filter(authorCountry: String) -> Self { - // Books do not have any country column. But their author has one. - // A book is from a country if it can be joined to an author from this country: - joining(required: Book.author.filter(country: authorCountry)) - } -} - -try dbQueue.read { db in - let italianNovels: [Book] = try Book.all() - .filter(kind: .novel) - .filter(authorCountry: "Italy") - .fetchAll(db) -} -``` - -Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example: - -```swift -// Author requests -extension QueryInterfaceRequest { - // Selects author ids - func selectId() -> QueryInterfaceRequest { - selectPrimaryKey(as: Int64.self) - } -} - -// IDs of French authors -let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db) -``` - -## Compose Records - -We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author. - -GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations: - -```swift -extension Author { - static let books = hasMany(Book.self) -} - -extension Book { - static let author = belongsTo(Author.self) -} -``` - -Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example: - -```swift -// Fetch all authors and their number of books -struct AuthorInfo: Decodable, FetchableRecord { - var author: Author - var bookCount: Int -} -let authorInfos: [AuthorInfo] = try dbQueue.read { db in - let request = Author.annotated(with: Author.books.count) - return try AuthorInfo.fetchAll(db, request) -} - -// Fetch all Colombian books and their authors: -struct Authorship: Decodable, FetchableRecord { - var book: Book - var author: Author -} -let authorships: [Authorship] = try dbQueue.read { db in - let request = Book.including(required: Book.author.filter(country: "Colombia")) - return try Authorship.fetchAll(db, request) -} -``` - -As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze. - -Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables]. - -> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they? -> -> That is because other ORMs perform lazy loading: -> -> ```ruby -> # Ruby's Active Record -> author = Author.find(123) # fetch author -> book_count = author.books.count # lazily counts books on demand -> ``` -> -> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. -> -> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information. - -Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below: - -1. Prepare the application screen that lists all authors: - - ```swift - let authors: [Author] = try dbQueue.read { db in - try Author.all().orderByName().fetchAll(db) - } - ``` - -2. Prepare the application screen that displays an author and her books: - - ```swift - struct AuthorInfo: Codable, FetchableRecord { - var author: Author - var books: [Book] - } - let authorId = 123 - let authorInfo: AuthorInfo? = try dbQueue.read { db in - let request = Author - .filter(id: authorId) - .including(all: Author.books) - return try AuthorInfo.fetchOne(db, request) - } - ``` - -3. Prepare the application screen that displays a book information: - - ```swift - struct BookInfo: Decodable, FetchableRecord { - var book: Book - var author: Author - } - let bookId = 123 - let bookInfo: BookInfo? = try dbQueue.read { db in - let request = Book - .filter(id: bookId) - .including(required: Book.author) - return try BookInfo.fetchOne(db, request) - } - ``` - -> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less. - -A last extension on your record types will further help navigation from records to associated ones: - -```swift -extension Author { - /// The request for the author's books - var books: QueryInterfaceRequest { - request(for: Author.books) - } -} - -extension Book { - /// The request for the author of the book - var author: QueryInterfaceRequest { - request(for: Book.author) - } -} -``` - -Those properties provide an alternative way to feed our application: - -1. Prepare the application screen that displays an author and her books: - - ```swift - struct AuthorInfo { - var author: Author - var books: [Book] - } - let authorId = 123 - let authorInfo: AuthorInfo? = try dbQueue.read { db in - guard let author = try Author.fetchOne(db, id: authorId) else { - return nil - } - let books = try author.books.fetchAll(db) - return AuthorInfo( - author: author, - books: books) - } - ``` - -2. Prepare the application screen that displays a book information: - - ```swift - struct BookInfo { - var book: Book - var author: Author - } - let bookId = 123 - let bookInfo: BookInfo? = try dbQueue.read { db in - guard let book = try Book.fetchOne(db, id: bookId) else { - return nil - } - guard let author = try book.author.fetchOne(db) else { - return nil - } - return BookInfo(book: book, author: author) - } - ``` - - -## How to Design Database Managers - -Many developers want to hide GRDB database queues and pools inside "database managers": - -```swift -// LibraryManager grants access to the library database. -class LibraryManager { - private let dbQueue: DatabaseQueue - init(dbQueue: DatabaseQueue) { - self.dbQueue = dbQueue - } -} -``` - -> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example. - -Design your database managers with the [GRDB concurrency rules] in mind. - -Practically, let's start with a naive example, and gradually improve it: - -```swift -// A naive manager that we will improve -class NaiveLibraryManager { - private let dbQueue: DatabaseQueue - init(dbQueue: DatabaseQueue) { - self.dbQueue = dbQueue - } - - func author(id: Int64) -> Author? { - do { - return try dbQueue.read { db in - try Author.fetchOne(db, id: id) - } - } catch { - return nil - } - } - - func book(id: Int64) -> Book? { - do { - return try dbQueue.read { db in - try Book.fetchOne(db, id: id) - } - } catch { - return nil - } - } - - func books(writtenBy author: Author) -> [Book] { - do { - return try dbQueue.read { db in - try author.books.fetchAll(db) - } - } catch { - return [] - } - } -} -``` - -**This manager can be improved in two ways.** - -- [Embrace Errors] -- [Thread-Safety is also an Application Concern] - -### Embrace Errors - -Have database managers throw database errors instead of catching them. - -Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle: - -Exposing errors will help you building your application: - -- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning. -- You will be able to opt in for advanced OS features like [data protection]. - -> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them. - -This gives the improved manager below. And it has less code, which means less bugs :bowtie: - -```swift -// An improved manager that does not hide errors -class ImprovedLibraryManager { - private let dbQueue: DatabaseQueue - init(dbQueue: DatabaseQueue) { - self.dbQueue = dbQueue - } - - func author(id: Int64) throws -> Author? { - try dbQueue.read { db in - try Author.fetchOne(db, id: id) - } - } - - func book(id: Int64) throws -> Book? { - try dbQueue.read { db in - try Book.fetchOne(db, id: id) - } - } - - func books(writtenBy author: Author) throws -> [Book] { - try dbQueue.read { db in - try author.books.fetchAll(db) - } - } -} -``` - - -### Thread-Safety is also an Application Concern - -Now, let's make our database manager **thread-safe**. - -This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application. - -For example, in the screen that displays an author and her books, we would write: - -```swift -let authorId = 123 -if let author = libraryManager.author(id: authorId) { - let books = libraryManager.books(writtenBy: author) - // Use author and books -} -``` - -This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen. - -Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss. - -Fortunately, GRDB has all the tools you need to prevent such nasty data races: - -> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**. - -This gives a much safer manager: - -```swift -// A manager that actually manages -class LibraryManager { - private let dbQueue: DatabaseQueue - init(dbQueue: DatabaseQueue) { - self.dbQueue = dbQueue - } -} - -// Feeds the list of authors -extension LibraryManager { - struct AuthorListItem: Decodable, FetchableRecord { - let author: Author - let bookCount: Int - } - - func authorList() throws -> [AuthorListItem] { - try dbQueue.read { db in - let request = Author - .annotated(with: Author.books.count) - .orderByName() - return try AuthorListItem.fetchAll(db, request) - } - } -} - -// Feeds a book screen -extension LibraryManager { - struct BookInfo { - var book: Book - var author: Author - } - - func bookInfo(bookId: Int64) throws -> BookInfo? { - try dbQueue.read { db in - guard let book = try Book.fetchOne(db, id: bookId) else { - return nil - } - guard let author = try book.author.fetchOne(db) else { - return nil - } - return BookInfo(book: book, author: author) - } - } -} - -// Feeds an author screen -extension LibraryManager { - struct AuthorInfo { - var author: Author - var books: [Book] - } - - func authorInfo(authorId: Int64) throws -> AuthorInfo? { - try dbQueue.read { db in - guard let author = try Author.fetchOne(db, id: authorId) else { - return nil - } - let books = try author.books.fetchAll(db) - return AuthorInfo(author: author, books: books) - } - } -} -``` - -The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views. - -When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation]. - -In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe. - -> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony: -> -> ```ruby -> # Ruby's Active Record -> book = Book.find(123) # fetch book -> author = book.author # fetch author -> # use book and author -> ``` -> -> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests. -> -> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others. -> -> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`. -> -> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale. - - -## Observe the Database and Refetch when Needed - -We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application. - -Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content. - -It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content. - -This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways. - -Instead, have a look at [Database Observation]: - -> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes. -> -> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way. -> -> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way. -> -> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs. -> -> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones. - -[records]: ../README.md#records -[associations]: AssociationsBasics.md -[FMDB]: https://github.com/ccgus/fmdb -[Core Data]: https://developer.apple.com/documentation/coredata -[Realm]: https://realm.io -[Active Record]: http://guides.rubyonrails.org/active_record_basics.html -[Django]: https://docs.djangoproject.com/en/2.0/topics/db/ -[record protocols]: ../README.md#record-protocols-overview -[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns -[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth -[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule -[Why Adopt GRDB?]: WhyAdoptGRDB.md -[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems) -[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations -[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations -[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions -[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency -[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency -[PersistableRecord]: ../README.md#persistablerecord-protocol -[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation -[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation -[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB -[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver -[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself -[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables -[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details -[Singleton Records]: #singleton-records -[Define Record Requests]: #define-record-requests -[Compose Records]: #compose-records -[How to Design Database Managers]: #how-to-design-database-managers -[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed -[query interface]: ../README.md#the-query-interface -[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation -[data protection]: ../README.md#data-protection -[Embrace Errors]: #embrace-errors -[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern -[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema -[Association Aggregates]: AssociationsBasics.md#association-aggregates -[Codable Record]: ../README.md#codable-records -[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types -[Combine Support]: Combine.md -[Value]: ../README.md#values -[Identifiable]: https://developer.apple.com/documentation/swift/identifiable +This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index f1c27f714..e78e652a0 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -195,7 +195,7 @@ protocol DerivableRequest: AggregatingRequest, FilteredRequest, - `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)` - `TableRequest` provides table targeting methods such as `aliased(tableAlias)` -DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md). +DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md). ### FetchRequest diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 86fd94b1c..8ce463636 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages. -See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice. +See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice. ### Allow database records to cross threads @@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and For detailed information about GRDB concurrency, check the [Concurrency Guide]. -For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md). +For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). ### Never pay for using raw SQL diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index 5fa411950..862520228 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -27,12 +27,13 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD - - -- ### Records and the Query Interface - +- - +- ### Responding to Database Changes diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md new file mode 100644 index 000000000..92f3fb18c --- /dev/null +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -0,0 +1,538 @@ +# Recommended Practices for Designing Record Types + +Leverage the best of record types and associations. + +## Overview + +GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Core Data], so you may face questions when designing the model layer of your application. + +This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors. + +- +- +- +- +- +- + +## Trust SQLite More Than Yourself + +Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed. + +This is why it is recommended to define a **robust database schema** even before playing with record types. + +This is important because SQLite is very robust, whereas we developers write bugs. The more responsibility we give to SQLite, the less code we have to write, and the fewer defects we will ship on our users' devices, affecting their precious data. + +For example, if we were to define that configure a database made of books and their authors, we could write: + +```swift +var migrator = DatabaseMigrator() + +migrator.registerMigration("createLibrary") { db in + try db.create(table: "author") { t in // (1) + t.autoIncrementedPrimaryKey("id") // (2) + t.column("name", .text).notNull() // (3) + t.column("countryCode", .text) // (4) + } + + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text).notNull() // (5) + t.column("authorId", .integer) // (6) + .notNull() // (7) + .indexed() // (8) + .references("author", onDelete: .cascade) // (9) + } +} + +try migrator.migrate(dbQueue) +``` + +1. Our database tables follow the : table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. +2. Each author has a unique id. +3. An author must have a name. +4. The country of an author is not always known. +5. A book must have a title. +6. The `book.authorId` column is used to link a book to the author it belongs to. +7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. +8. The `book.authorId` column is indexed in order to ease the selection of an author's books. +9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information. + +Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc. + +> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.** +> +> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantee the quality of users data, as long as enough energy is put in the proper definition of the database schema. + +> Tip: **Plan early for future versions of your application**: use . + +## Persistable Record Types are Responsible for Their Tables + +**Define one record type per database table.** This record type will be responsible for writing in this table. + +**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows. + +```swift +struct Author: Codable, Identifiable { + var id: Int64? + var name: String + var countryCode: String? +} + +struct Book: Codable, Identifiable { + var id: Int64? + var authorId: Int64 + var title: String +} +``` + +**We add database powers to our types with record protocols.** + +The `author` and `book` tables have an auto-incremented id. We want inserted records to learn about their id after a successful insertion. That's why we have them conform to the ``MutablePersistableRecord`` protocol, and implement ``MutablePersistableRecord/didInsert(_:)-109jm``. Other kinds of record types would just use ``PersistableRecord``, and ignore `didInsert`. + +On the reading side, we use ``FetchableRecord``, the protocol that can decode database rows. + +This gives: + +```swift +// Add Database access +extension Author: FetchableRecord, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } +} + +extension Book: FetchableRecord, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } +} +``` + +That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`: + +```swift +try dbQueue.write { db in + // Insert and set author's id + var author = Author(name: "Herman Melville", countryCode: "US") + try author.insert(db) + + // Insert and set book's id + var book = Book(authorId: author.id!, title: "Moby-Dick") + try book.insert(db) +} + +let books = try dbQueue.read { db in + try Book.fetchAll(db) +} +``` + +The `Book` and `Author` are independent structs that don't know each other. There is no `books` property in the `Author` struct, and there is no `author` property in the `Book` struct. Each type is fully responsible for its own table. + +The relationship between author and books will be detailed below, in the section. + +> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare: +> +> ```swift +> try db.create(table: "author") { t in +> t.autoIncrementedPrimaryKey("id") +> t.column("name", .text).notNull() // Can't be NULL +> t.column("countryCode", .text) // Can be NULL +> } +> +> struct Author: Codable, Identifiable { +> var id: Int64? +> var name: String // Not optional +> var countryCode: String? // Optional +> } +> ``` +> +> There are exceptions to this rule. +> +> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids! +> +> Another exception to this rule is described in , where the creation date of a record is never NULL in the database, but optional in the Swift type. + +> Tip: When the database table has a single-column primary key, have the record type adopt the standard [`Identifiable`] protocol. This allows GRDB to define extra methods based on record ids: +> +> ```swift +> let authorID: Int64 = 42 +> let author: Author = try dbQueue.read { db in +> try Author.find(db, id: authorID) +> } +> ``` + +## Record Types Hide Intimate Database Details + +In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.) + +But it happens that raw database column names, or raw column types, are not a very good fit for the application. + +When this happens, it's time to **distinguish the Swift and database representations**. Record types are the dedicated place where raw database values can be transformed into Swift types that are well-suited for the rest of the application. + +Let's look at three examples. + +### First Example: Enums + +Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database: + +```swift +try db.create(table: "book") { t in + ... + t.column("kind", .text).notNull() +} +``` + +In Swift, it is not a good practice to use `String` for the type of the `kind` property. We prefer an enum instead: + +```swift +struct Book: Codable { + enum Kind: String, Codable { + case essay, novel, poetry, theater + } + var id: Int64? + var authorId: Int64 + var title: String + var kind: Kind +} +``` + +Thanks to its enum property, the `Book` record prevents invalid book kinds from being stored into the database. + +In order to use `Book.Kind` in database requests for books (see below), we add the ``DatabaseValueConvertible`` conformance to `Book.Kind`: + +```swift +extension Book.Kind: DatabaseValueConvertible { } + +// Fetch all novels +let novels = try dbQueue.read { db in + try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db) +} +``` + +### Second Example: GPS Coordinates + +GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. + +When this happens, keep column properties private, and provide sensible accessors instead: + +```swift +try db.create(table: "place") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + t.column("latitude", .double).notNull() + t.column("longitude", .double).notNull() +} + +struct Place: Codable { + var id: Int64? + var name: String + private var latitude: CLLocationDegrees + private var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } +} +``` + +Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique. + +### Third Example: Money Amounts + +Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency). + +SQLite only supports two kinds of numbers: integers and doubles, so we'll store amounts as integers. $12.00 will be represented by 1200, a quantity of cents. This allows SQLite to compute exact sums of price, for example. + +On the other side, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit. + +That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column: + +```swift +try db.create(table: "product") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + t.column("priceCents", .integer).notNull() +} + +struct Product: Codable { + var id: Int64? + var name: String + private var priceCents: Int + + var price: Decimal { + get { + Decimal(priceCents) / 100 + } + set { + priceCents = Self.cents(for: newValue) + } + } + + private static func cents(for value: Decimal) -> Int { + Int(Double(truncating: NSDecimalNumber(decimal: value * 100))) + } +} +``` + +## Singleton Records + +Singleton Records are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row. + +The recommended setup for such records is described in the guide. + +## Record Requests + +Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records. + +### Define Columns and Perform Requests + +Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum: + +```swift +// HOW TO define columns for a Codable record +extension Author { + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let countryCode = Column(CodingKeys.countryCode) + } +} +``` + +For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol: + +```swift +// HOW TO define columns for a non-Codable record +extension Author { + enum Columns: String, ColumnExpression { + case id, name, countryCode + } +} +``` + +From those columns it is possible to define requests of type ``QueryInterfaceRequest``: + +```swift +try dbQueue.read { db in + // Fetch all authors, ordered by name, + // in a localized case-insensitive fashion + let sortedAuthors: [Author] = try Author.all() + .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) + .fetchAll(db) + + // Count French authors + let frenchAuthorCount: Int = try Author.all() + .filter(Author.Columns.countryCode == "FR") + .fetchCount(db) +} +``` + +### Turn Commonly-Used Requests into Methods + +An application can define reusable request methods that extend the built-in GRDB apis. Those methods avoid code repetition, ease refactoring, and foster testability. + +Define those methods in extensions of the ``DerivableRequest`` protocol, as below: + +```swift +// Author requests +extension DerivableRequest { + /// Order authors by name, in a localized case-insensitive fashion + func orderByName() -> Self { + let name = Author.Columns.name + return order(name.collating(.localizedCaseInsensitiveCompare)) + } + + /// Filters authors from a country + func filter(countryCode: String) -> Self { + filter(Author.Columns.countryCode == countryCode) + } +} + +// Book requests +extension DerivableRequest { + /// Filters books by kind + func filter(kind: Book.Kind) -> Self { + filter(Book.Columns.kind == kind) + } +} +``` + +Those methods define a fluent and legible api that encapsulates intimate database details: + +```swift +try dbQueue.read { db in + let sortedSpanishAuthors: [Author] = try Author.all() + .filter(countryCode: "ES") + .orderByName() + .fetchAll(db) + + let novelCount: Int = try Book.all() + .filter(kind: .novel) + .fetchCount(db) +} +``` + +Extensions to the `DerivableRequest` protocol can not change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below: + +```swift +extension QueryInterfaceRequest { + // Selects author ids + func selectId() -> QueryInterfaceRequest { + selectPrimaryKey(as: Int64.self) + } +} + +// The ids of French authors +let ids: Set = try Author.all() + .filter(countryCode: "FR") + .selectId() + .fetchSet(db) +``` + +## Associations + +So far, the `Book` and `Author` types don't know each other. The only meeting point is the `Book.authorId` property. + +Associations help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books: + +```swift +extension Book { + static let author = belongsTo(Author.self) +} + +extension Author { + static let books = hasMany(Book.self) +} +``` + +Those associations have many uses, so let's just give a few examples. The [Associations Guide] gives the full picture. + +### More Reusable Requests + +Associations make it possible to define more convenience request methods, similar to those seen in the section above: + +```swift +extension DerivableRequest { + /// Filters authors with at least one book + func havingBooks() -> Self { + having(Author.books.isEmpty == false) + } +} + +extension DerivableRequest { + /// Filters books from a country + func filter(authorCountryCode countryCode: String) -> Self { + // Books do not have any country column. But their author has one! + // Return books that can be joined to an author from this country: + joining(required: Book.author.filter(countryCode: countryCode)) + } +} + +try dbQueue.read { db in + let nonLazyAuthors: [Author] = try Author.all() + .havingBooks() + .fetchAll(db) + + let italianNovels: [Book] = try Book.all() + .filter(kind: .novel) + .filter(authorCountryCode: "IT") + .fetchAll(db) +} +``` + +### Composed Records + +Associations can also compose records together into richer types: + +```swift +// Fetch all authors along with their number of books +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var bookCount: Int +} +let authorInfos: [AuthorInfo] = try dbQueue.read { db in + try Author + .annotated(with: Author.books.count) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +} +``` + +```swift +// Fetch the careers of French authors, sorted by name +struct Career: Codable, FetchableRecord { + var author: Author + var books: [Book] +} +let authorId = 123 +let careers: [Career] = try dbQueue.read { db in + try Author + .filter(countryCode: "FR") + .orderByName() + .including(all: Author.books) + .asRequest(of: Career.self) + .fetchAll(db) +} +``` + +```swift +// Fetch all Colombian books and their authors +struct Authorship: Decodable, FetchableRecord { + var book: Book + var author: Author +} +let authorships: [Authorship] = try dbQueue.read { db in + try Book.all() + .including(required: Book.author.filter(countryCode: "CO")) + .asRequest(of: Authorship.self) + .fetchAll(db) + + // Equivalent alternative + try Book.all() + .filter(countryAuthorCode: "CO") + .including(required: Book.author) + .asRequest(of: Authorship.self) + .fetchAll(db) +} +``` + +In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `Career`, and `Authorship`. + +Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. All database writes are performed from persistable record instances of type `Author` or `Book`. + +For more information about associations, see the [Associations Guide]. + +> Note: +> +> The additional record types in the previous sample code may look superfluous. There exist other database libraries that are able to navigate in complex graphs of records without additional types. +> +> That is because those libraries perform lazy loading: +> +> ```ruby +> # Ruby's Active Record +> author = Author.find(123) # Fetch author +> book_count = author.books.count # Lazily count books on demand +> ``` +> +> **GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the guide for more information. + +[Active Record]: http://guides.rubyonrails.org/active_record_basics.html +[`Codable`]: https://developer.apple.com/documentation/swift/Codable +[Core Data]: https://developer.apple.com/documentation/coredata +[`Decimal`]: https://developer.apple.com/documentation/foundation/decimal +[`Decodable`]: https://developer.apple.com/documentation/swift/Decodable +[Django]: https://docs.djangoproject.com/en/4.2/topics/db/ +[`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable +[isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems) +[Associations Guide]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md diff --git a/README.md b/README.md index eec0f7993..27f8c4427 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,7 @@ Documentation #### General Guides & Good Practices -- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) +- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) - :bulb: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) - :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) - :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) @@ -1706,7 +1706,7 @@ Extending structs with record protocols is more "swifty". Subclassing the Record > **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. > -> :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. +> :bulb: **Tip**: after you have read this chapter, check the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) Guide. > > :bulb: **Tip**: see the [Demo Applications] for sample apps that uses records. @@ -2828,7 +2828,7 @@ extension Player: FetchableRecord, PersistableRecord { } ``` -See the [query interface](#the-query-interface) and [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) for further information. +See the [query interface](#the-query-interface) and [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for further information. ## Record Class From 17c3f82f50aa578915d51b57739e73e16bd24614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 10 Apr 2023 10:18:01 +0200 Subject: [PATCH 5/9] Remove weird Xcode error regarding the Scripts "project" --- GRDB.xcodeproj/project.pbxproj | 10 ---------- GRDBCustom.xcodeproj/project.pbxproj | 2 -- 2 files changed, 12 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 43c7d6af6..1a7807a61 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -512,7 +512,6 @@ 56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = ""; }; 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = ""; }; 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = ""; }; - 5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; @@ -1113,13 +1112,6 @@ path = GRDBCombineTests; sourceTree = ""; }; - 564390D42414FC2C00BA61E6 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; 5653EABF20944B1300F46237 /* Association */ = { isa = PBXGroup; children = ( @@ -1588,8 +1580,6 @@ DC37742D19C8CC90004FCF85 /* GRDB */, DC10500F19C904DD00D8CA30 /* Tests */, DC3773F419C8CBB3004FCF85 /* Products */, - 564390D42414FC2C00BA61E6 /* Frameworks */, - 5643676D272EDF2400C718C7 /* Scripts */, ); indentWidth = 4; sourceTree = ""; diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 84a9f56a3..1eead3f88 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -522,7 +522,6 @@ 56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = ""; }; 56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = ""; }; - 5643676E272EDF3700C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; @@ -1584,7 +1583,6 @@ DC37742D19C8CC90004FCF85 /* GRDB */, F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */, DC10500F19C904DD00D8CA30 /* Tests */, - 5643676E272EDF3700C718C7 /* Scripts */, DC3773F419C8CBB3004FCF85 /* Products */, ); indentWidth = 4; From 1add9a975205a0f4eb1fbbb9756419b65980729d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 10 Apr 2023 11:17:04 +0200 Subject: [PATCH 6/9] Fix incorrect test --- Tests/GRDBTests/ValueObservationPrintTests.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 1cb60f364..51f57f5b6 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -436,13 +436,17 @@ class ValueObservationPrintTests: GRDBTestCase { onChange: { _ in expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(logger.strings, [ - "start", - "fetch", - "value: nil", + // Order of events may not be stable, because the first + // "value: nil" is notified concurrently (from the reduce queue) + // with the first "database did change" (from the writer queue). + // That's why we test the sorted output. + XCTAssertEqual(logger.strings.sorted(), [ "database did change", "fetch", + "fetch", + "start", "tracked region: \(expectedRegion)", + "value: nil", "value: nil"]) } } From f2ea4e91db9ec288fb673e44c9e46c41f353dba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 10 Apr 2023 11:31:05 +0200 Subject: [PATCH 7/9] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c6297bc9..ccb1a97cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC. +- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration. + ## 6.10.1 Released April 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1) From 859a1d6184c19282c33751538b70d0765515fed7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 10 Apr 2023 11:36:23 +0200 Subject: [PATCH 8/9] Enhance Recommended Practices for Designing Record Types --- .../RecordRecommendedPractices.md | 179 +++++++++++------- 1 file changed, 111 insertions(+), 68 deletions(-) diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md index 92f3fb18c..2588c7704 100644 --- a/GRDB/Documentation.docc/RecordRecommendedPractices.md +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -8,13 +8,6 @@ GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Cor This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors. -- -- -- -- -- -- - ## Trust SQLite More Than Yourself Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed. @@ -66,7 +59,9 @@ Thanks to this database schema, the application will always process *consistent > Tip: **Plan early for future versions of your application**: use . -## Persistable Record Types are Responsible for Their Tables +## Record Types + +### Persistable Record Types are Responsible for Their Tables **Define one record type per database table.** This record type will be responsible for writing in this table. @@ -129,10 +124,6 @@ let books = try dbQueue.read { db in } ``` -The `Book` and `Author` are independent structs that don't know each other. There is no `books` property in the `Author` struct, and there is no `author` property in the `Book` struct. Each type is fully responsible for its own table. - -The relationship between author and books will be detailed below, in the section. - > Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare: > > ```swift @@ -164,7 +155,7 @@ The relationship between author and books will be detailed below, in the } > ``` -## Record Types Hide Intimate Database Details +### Record Types Hide Intimate Database Details In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.) @@ -174,7 +165,7 @@ When this happens, it's time to **distinguish the Swift and database representat Let's look at three examples. -### First Example: Enums +#### First Example: Enums Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database: @@ -212,7 +203,7 @@ let novels = try dbQueue.read { db in } ``` -### Second Example: GPS Coordinates +#### Second Example: GPS Coordinates GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. @@ -248,7 +239,7 @@ struct Place: Codable { Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique. -### Third Example: Money Amounts +#### Third Example: Money Amounts Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency). @@ -285,17 +276,11 @@ struct Product: Codable { } ``` -## Singleton Records - -Singleton Records are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row. - -The recommended setup for such records is described in the guide. - ## Record Requests Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records. -### Define Columns and Perform Requests +### Columns Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum: @@ -361,6 +346,12 @@ extension DerivableRequest { // Book requests extension DerivableRequest { + /// Order books by title, in a localized case-insensitive fashion + func orderByTitle() -> Self { + let title = Book.Columns.title + return order(title.collating(.localizedCaseInsensitiveCompare)) + } + /// Filters books by kind func filter(kind: Book.Kind) -> Self { filter(Book.Columns.kind == kind) @@ -393,18 +384,16 @@ extension QueryInterfaceRequest { } } -// The ids of French authors +// The ids of Japanese authors let ids: Set = try Author.all() - .filter(countryCode: "FR") + .filter(countryCode: "JP") .selectId() .fetchSet(db) ``` ## Associations -So far, the `Book` and `Author` types don't know each other. The only meeting point is the `Book.authorId` property. - -Associations help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books: +[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books: ```swift extension Book { @@ -416,20 +405,22 @@ extension Author { } ``` -Those associations have many uses, so let's just give a few examples. The [Associations Guide] gives the full picture. - -### More Reusable Requests - -Associations make it possible to define more convenience request methods, similar to those seen in the section above: +With associations, you can fetch a book's author, or an author's books: ```swift -extension DerivableRequest { - /// Filters authors with at least one book - func havingBooks() -> Self { - having(Author.books.isEmpty == false) - } +// Fetch all novels from an author +try dbQueue.read { db in + let author: Author = ... + let novels: [Book] = try author.request(for: Author.books) + .filter(kind: .novel) + .orderByTitle() + .fetchAll(db) } +``` +Associations also make it possible to define more convenience request methods: + +```swift extension DerivableRequest { /// Filters books from a country func filter(authorCountryCode countryCode: String) -> Self { @@ -439,11 +430,8 @@ extension DerivableRequest { } } +// Fetch all Italian novels try dbQueue.read { db in - let nonLazyAuthors: [Author] = try Author.all() - .havingBooks() - .fetchAll(db) - let italianNovels: [Book] = try Book.all() .filter(kind: .novel) .filter(authorCountryCode: "IT") @@ -451,9 +439,15 @@ try dbQueue.read { db in } ``` -### Composed Records +With associations, you can also process graphs of authors and books, as described in the next section. -Associations can also compose records together into richer types: +### How to Model Graphs of Objects + +Since the beginning of this article, the `Book` and `Author` are independent structs that don't know each other. The only "meeting point" is the `Book.authorId` property. + +Record types don't know each other on purpose: one does not need to know the author of a book when it's time to update the title of a book, for example. + +When an application wants to process authors and books together, it defines dedicated types that model the desired view on the graph of related objects. For example: ```swift // Fetch all authors along with their number of books @@ -470,18 +464,17 @@ let authorInfos: [AuthorInfo] = try dbQueue.read { db in ``` ```swift -// Fetch the careers of French authors, sorted by name -struct Career: Codable, FetchableRecord { +// Fetch the literary careers of German authors, sorted by name +struct LiteraryCareer: Codable, FetchableRecord { var author: Author var books: [Book] } -let authorId = 123 -let careers: [Career] = try dbQueue.read { db in +let careers: [LiteraryCareer] = try dbQueue.read { db in try Author - .filter(countryCode: "FR") + .filter(countryCode: "DE") .orderByName() .including(all: Author.books) - .asRequest(of: Career.self) + .asRequest(of: LiteraryCareer.self) .fetchAll(db) } ``` @@ -500,32 +493,81 @@ let authorships: [Authorship] = try dbQueue.read { db in // Equivalent alternative try Book.all() - .filter(countryAuthorCode: "CO") + .filter(authorCountryCode: "CO") .including(required: Book.author) .asRequest(of: Authorship.self) .fetchAll(db) } ``` -In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `Career`, and `Authorship`. +In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`. -Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. All database writes are performed from persistable record instances of type `Author` or `Book`. +Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`). -For more information about associations, see the [Associations Guide]. +For more information about associations, see the [Associations] guide. -> Note: -> -> The additional record types in the previous sample code may look superfluous. There exist other database libraries that are able to navigate in complex graphs of records without additional types. -> -> That is because those libraries perform lazy loading: -> -> ```ruby -> # Ruby's Active Record -> author = Author.find(123) # Fetch author -> book_count = author.books.count # Lazily count books on demand -> ``` -> -> **GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the guide for more information. +### Lazy and Eager Loading: Comparison with Other Database Libraries + +The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types. + +For example, [Core Data] and Ruby's [Active Record] uses **lazy loading**. This means that relationships are lazily fetched on demand: + +```ruby +# Lazy loading with Active Record +author = Author.first # Fetch first author +puts author.name +author.books.each do |book| # Lazily fetch books on demand + puts book.title +end +``` + +**GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the guide for more information. + +Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested: + +```swift +// Eager loading with Fluent +let query = Author.query(on: db) + .with(\.$books) // <- Explicit request for books + .first() + +// Fetch first author and its books in one stroke +if let author = query.get() { + print(author.name) + for book in author.books { print(book.title) } +} +``` + +One must take care of fetching relationships, though, or Fluent raises a fatal error: + +```swift +// Oops, the books relation is not explicitly requested +let query = Author.query(on: db).first() +if let author = query.get() { + // fatal error: Children relation not eager loaded. + for book in author.books { print(book.title) } +} +``` + +**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides full compile and runtime safety: + +```swift +// Eager loading with GRDB +struct LiteraryCareer: Codable, FetchableRecord { + var author: Author + var books: [Book] +} + +let request = Author.all() + .including(all: Author.books) // <- Explicit request for books + .asRequest(of: LiteraryCareer.self) + +// Fetch first author and its books in one stroke +if let career = try request.fetchOne(db) { + print(career.author.name) + for book in career.books { print(book.title) } +} +``` [Active Record]: http://guides.rubyonrails.org/active_record_basics.html [`Codable`]: https://developer.apple.com/documentation/swift/Codable @@ -533,6 +575,7 @@ For more information about associations, see the [Associations Guide]. [`Decimal`]: https://developer.apple.com/documentation/foundation/decimal [`Decodable`]: https://developer.apple.com/documentation/swift/Decodable [Django]: https://docs.djangoproject.com/en/4.2/topics/db/ +[Fluent]: https://docs.vapor.codes/fluent/overview/ [`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable [isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems) -[Associations Guide]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md +[Associations]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md From 065ca718769961c034593e2d0c0a57d49faad325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 10 Apr 2023 14:16:41 +0200 Subject: [PATCH 9/9] v6.10.2 --- CHANGELOG.md | 6 ++++-- GRDB.swift.podspec | 2 +- README.md | 4 ++-- Support/Info.plist | 2 +- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccb1a97cf..47ed9cf34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases -- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) +- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102) - `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692) - `6.8.x` Releases - [6.8.0](#680) - `6.7.x` Releases - [6.7.0](#670) @@ -108,7 +108,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 6.10.2 + +Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2) - **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC. - **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration. diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index d842649f5..fc292e48f 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.10.1' + s.version = '6.10.2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index 27f8c4427..d36ef93bb 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: April 1, 2023 • [version 6.10.1](https://github.com/groue/GRDB.swift/tree/v6.10.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: April 10, 2023 • [version 6.10.2](https://github.com/groue/GRDB.swift/tree/v6.10.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.10.1** | +| **Swift 5.7+** | **v6.10.2** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | diff --git a/Support/Info.plist b/Support/Info.plist index 8b6e8ec35..ec1e4cdc9 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.10.1 + 6.10.2 CFBundleSignature ???? CFBundleVersion