From 22dd8e1c3a4d74131dceec93a9b3a035852c9742 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 9 Dec 2015 08:53:08 +0100 Subject: [PATCH 01/67] Introduce DatabasePersistable that grants CRUD methods to any type --- GRDB Tests/GRDBTestCase.swift | 6 +- .../Record/MinimalPrimaryKeyRowIDTests.swift | 24 +-- .../Record/MinimalPrimaryKeySingleTests.swift | 24 +-- .../Record/PrimaryKeyMultipleTests.swift | 24 +-- .../Public/Record/PrimaryKeyRowIDTests.swift | 24 +-- .../Public/Record/PrimaryKeySingleTests.swift | 24 +-- ...leWithReplaceConflictResolutionTests.swift | 24 +-- GRDB.xcodeproj/project.pbxproj | 12 +- .../Protocols/DatabasePersistable.swift} | 153 +++++++++++++++--- GRDB/Record/Record.swift | 75 +++------ 10 files changed, 238 insertions(+), 152 deletions(-) rename GRDB/{Record/DatabaseStorable.swift => Core/Protocols/DatabasePersistable.swift} (61%) diff --git a/GRDB Tests/GRDBTestCase.swift b/GRDB Tests/GRDBTestCase.swift index 509919b28..598e3ef41 100644 --- a/GRDB Tests/GRDBTestCase.swift +++ b/GRDB Tests/GRDBTestCase.swift @@ -33,12 +33,8 @@ class GRDBTestCase: XCTestCase { func assertNoError(@noescape test: (Void) throws -> Void) { do { try test() - } catch let error as DatabaseError { - XCTFail(error.description) - } catch let error as RecordError { - XCTFail(error.description) } catch { - XCTFail("error: \(error)") + XCTFail("unexpected error: \(error)") } } } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift index ca39c8281..163fc5bd2 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift @@ -124,9 +124,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { record.id = 123456 do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -159,9 +159,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -299,9 +299,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { record.id = 123456 do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -334,9 +334,9 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift index e201a3c6c..4deeee304 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift @@ -121,9 +121,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { record.UUID = "theUUID" do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -158,9 +158,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -297,9 +297,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { record.UUID = "theUUID" do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -334,9 +334,9 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift index dacbd816d..c61cbe2fa 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -140,9 +140,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { let record = Citizenship(personName: "Arthur", countryName: "France", native: true) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -176,9 +176,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -310,9 +310,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { let record = Citizenship(personName: "Arthur", countryName: "France", native: true) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -346,9 +346,9 @@ class PrimaryKeyMultipleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift index ca9098f01..6455b62aa 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -193,9 +193,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { let record = Person(id: 123456, name: "Arthur") do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -229,9 +229,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -369,9 +369,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { let record = Person(id: 123456, name: "Arthur") do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -405,9 +405,9 @@ class PrimaryKeyRowIDTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift index ed51c8565..c62c3afed 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift @@ -133,9 +133,9 @@ class PrimaryKeySingleTests: GRDBTestCase { let record = Pet(UUID: "BobbyUUID", name: "Bobby") do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -169,9 +169,9 @@ class PrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -303,9 +303,9 @@ class PrimaryKeySingleTests: GRDBTestCase { let record = Pet(UUID: "BobbyUUID", name: "Bobby") do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -339,9 +339,9 @@ class PrimaryKeySingleTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift index 0fc3dbd1b..211dcc949 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -131,9 +131,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { record.email = "me@domain.com" do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -168,9 +168,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.delete(db) do { try record.update(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -307,9 +307,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { record.email = "me@domain.com" do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } @@ -344,9 +344,9 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { try record.delete(db) do { try record.reload(db) - XCTFail("Expected RecordError.RecordNotFound") - } catch RecordError.RecordNotFound { - // Expected RecordError.RecordNotFound + XCTFail("Expected PersistenceError.NotFound") + } catch PersistenceError.NotFound { + // Expected PersistenceError.NotFound } } } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 3ab5ecd9f..b95780bba 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -29,6 +29,8 @@ 5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; }; 5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; }; 5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; + 56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; }; + 56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; }; 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; @@ -137,8 +139,6 @@ 56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */; }; 56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238981B9C752B0082EB20 /* RowConvertible.swift */; }; 56A2389E1B9C752B0082EB20 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238981B9C752B0082EB20 /* RowConvertible.swift */; }; - 56A238A21B9C753B0082EB20 /* DatabaseStorable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */; }; - 56A238A31B9C753B0082EB20 /* DatabaseStorable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */; }; 56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 56A238A51B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 56A238AA1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A91B9C7E540082EB20 /* StatementArguments+Foundation.swift */; }; @@ -304,6 +304,7 @@ 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; + 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; 565B0FF71BBC7FE90098DE03 /* RowConvertible+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Foundation.swift"; sourceTree = ""; }; @@ -359,7 +360,6 @@ 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = ""; }; 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 56A238981B9C752B0082EB20 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; - 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStorable.swift; sourceTree = ""; }; 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; 56A238A91B9C7E540082EB20 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; 56A238AC1B9C90090082EB20 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; @@ -700,6 +700,7 @@ 56A238951B9C752B0082EB20 /* Protocols */ = { isa = PBXGroup; children = ( + 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */, 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */, 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */, 56A238981B9C752B0082EB20 /* RowConvertible.swift */, @@ -711,7 +712,6 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( - 56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, ); path = Record; @@ -1203,6 +1203,7 @@ buildActionMask = 2147483647; files = ( 56A238901B9C75030082EB20 /* UpdateStatement.swift in Sources */, + 56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */, 56E589201BBA5D5400CC0140 /* NSURL.swift in Sources */, 56A2388E1B9C75030082EB20 /* StatementArguments.swift in Sources */, 56A2380A1B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */, @@ -1224,7 +1225,6 @@ 56B7F4271BE1491700E39BBF /* CGFloat.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, - 56A238A31B9C753B0082EB20 /* DatabaseStorable.swift in Sources */, 56A2388A1B9C75030082EB20 /* SelectStatement.swift in Sources */, 56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */, 56A238801B9C75030082EB20 /* DatabaseChanges.swift in Sources */, @@ -1360,6 +1360,7 @@ buildActionMask = 2147483647; files = ( 56A238AD1B9C90090082EB20 /* NSNull.swift in Sources */, + 56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */, 56E5891F1BBA5D5400CC0140 /* NSURL.swift in Sources */, 56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */, 56A2388D1B9C75030082EB20 /* StatementArguments.swift in Sources */, @@ -1389,7 +1390,6 @@ 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, - 56A238A21B9C753B0082EB20 /* DatabaseStorable.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 56B7F4341BE4BF1600E39BBF /* DatabaseCoder.swift in Sources */, 56A2380C1B9C6E440082EB20 /* NSData.swift in Sources */, diff --git a/GRDB/Record/DatabaseStorable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift similarity index 61% rename from GRDB/Record/DatabaseStorable.swift rename to GRDB/Core/Protocols/DatabasePersistable.swift index 8dd6fe6cd..6e6c840b5 100644 --- a/GRDB/Record/DatabaseStorable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -1,22 +1,139 @@ -// MARK: - DatabaseStorable +// MARK: - PersistenceError -protocol DatabaseStorable : DatabaseTableMapping { +/// An error thrown by a type that adopts DatabasePersistable. +public enum PersistenceError: ErrorType { + + /// Thrown by DatabasePersistable.update() when no matching row could be + /// found in the database. + case NotFound(DatabasePersistable) +} + +extension PersistenceError : CustomStringConvertible { + /// A textual representation of `self`. + public var description: String { + switch self { + case .NotFound(let persistable): + return "Not found: \(persistable)" + } + } +} + +// MARK: - DatabasePersistable + +/// Types that adopt DatabasePersistable can be inserted, updated, and deleted. +public protocol DatabasePersistable : DatabaseTableMapping { + + /// Returns the values that should be stored in the database. + /// + /// Keys of the returned dictionary must match the column names of the + /// target database table (see DatabaseTableMapping.databaseTableName()). + /// + /// In particular, primary key columns, if any, must be included. + /// + /// struct Person : DatabasePersistable { + /// var id: Int64? + /// var name: String? + /// + /// var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + /// return ["id": id, "name": name] + /// } + /// } var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } + + /// If the underlying database table has an INTEGER PRIMARY KEY, this method + /// is called after a successful insertion. Adopting type may implement this + /// method and update their primary key accordingly. + /// + /// This method is optional: the default implementation does nothing. + /// + /// struct Person : DatabasePersistable { + /// var id: Int64? + /// var name: String? + /// + /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { + /// self.id = rowID + /// } + /// } + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) +} + +public extension DatabasePersistable { + + /// The default implementation does nothing. + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { + } + + // MARK: - CRUD + + /// Executes an INSERT statement. + /// + /// On success, this method sets the *databaseEdited* flag to false. + /// + /// This method is guaranteed to have inserted a row in the database if it + /// returns without error. + /// + /// When the table has an INTEGER PRIMARY KEY, the + /// didInsertWithRowID(:forColumn:) method is called upon successful + /// insertion. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs. + mutating func insert(db: Database) throws { + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if case .Managed(let rowIDColumnName) = dataMapper.primaryKey { + didInsertWithRowID(changes.insertedRowID!, forColumn: rowIDColumnName) + } + } + + /// Executes an UPDATE statement. + /// + /// This method is guaranteed to have updated a row in the database if it + /// returns without error. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(db: Database) throws { + let changes = try DataMapper(db, self).updateStatement().execute() + if changes.changedRowCount == 0 { + throw PersistenceError.NotFound(self) + } + } + + /// Executes a DELETE statement. + /// + /// - parameter db: A Database. + /// - returns: Whether a database row was deleted. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + func delete(db: Database) throws -> Bool { + return try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 + } + + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// - parameter db: A Database. + /// - returns: Whether the primary key matches a row in the database. + func exists(db: Database) -> Bool { + return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) + } } // MARK: - DataMapper -/// DataMapper takes care of DatabaseStorable CRUD +/// DataMapper takes care of DatabasePersistable CRUD final class DataMapper { /// The database let db: Database - /// The storable - let storable: DatabaseStorable + /// The persistable + let persistable: DatabasePersistable - /// DataMapper keeps a copy the storable's storedDatabaseDictionary, so + /// DataMapper keeps a copy the persistable's storedDatabaseDictionary, so /// that this dictionary is built once whatever the database operation. /// It is guaranteed to have at least one (key, value) pair. let storedDatabaseDictionary: [String: DatabaseValueConvertible?] @@ -30,7 +147,7 @@ final class DataMapper { /// An excerpt from storedDatabaseDictionary whose keys are primary key /// columns. /// - /// It is nil when storable has no primary key. + /// It is nil when persistable has no primary key. lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in let columns = self.primaryKey.columns guard columns.count > 0 else { @@ -86,25 +203,25 @@ final class DataMapper { // MARK: - Initializer - init(_ db: Database, _ storable: DatabaseStorable) { + init(_ db: Database, _ persistable: DatabasePersistable) { // Fail early if databaseTable is nil - guard let databaseTableName = storable.dynamicType.databaseTableName() else { - fatalError("Nil returned from \(storable.dynamicType).databaseTableName()") + guard let databaseTableName = persistable.dynamicType.databaseTableName() else { + fatalError("Nil returned from \(persistable.dynamicType).databaseTableName()") } // Fail early if database table does not exist. guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { - fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(storable.dynamicType).databaseTableName()") + fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(persistable.dynamicType).databaseTableName()") } // Fail early if storedDatabaseDictionary is empty - let storedDatabaseDictionary = storable.storedDatabaseDictionary + let storedDatabaseDictionary = persistable.storedDatabaseDictionary guard storedDatabaseDictionary.count > 0 else { - fatalError("Invalid empty dictionary returned from \(storable.dynamicType).storedDatabaseDictionary") + fatalError("Invalid empty dictionary returned from \(persistable.dynamicType).storedDatabaseDictionary") } self.db = db - self.storable = storable + self.persistable = persistable self.storedDatabaseDictionary = storedDatabaseDictionary self.databaseTableName = databaseTableName self.primaryKey = primaryKey @@ -122,7 +239,7 @@ final class DataMapper { func updateStatement() -> UpdateStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") + fatalError("Invalid primary key in \(persistable)") } // Don't update primary key columns @@ -153,7 +270,7 @@ final class DataMapper { func deleteStatement() -> UpdateStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") + fatalError("Invalid primary key in \(persistable)") } // Delete @@ -165,7 +282,7 @@ final class DataMapper { func reloadStatement() -> SelectStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") + fatalError("Invalid primary key in \(persistable)") } // Fetch @@ -179,7 +296,7 @@ final class DataMapper { func existsStatement() -> SelectStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { - fatalError("Invalid primary key in \(storable)") + fatalError("Invalid primary key in \(persistable)") } // Fetch diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index cb253fbc2..8e67e7788 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -9,7 +9,7 @@ /// - updateFromRow /// - databaseTable /// - storedDatabaseDictionary -public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { +public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable { // MARK: - Initializers @@ -148,6 +148,11 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { public func updateFromRow(row: Row) { } + /// TODO + final public func didInsertWithRowID(rowID: Int64, forColumn name: String) { + updateFromRow(Row(dictionary: [name: rowID])) + } + // MARK: - Copy @@ -242,7 +247,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { // MARK: - CRUD - /// Executes an INSERT statement to insert the record. + /// Executes an INSERT statement. /// /// On success, this method sets the *databaseEdited* flag to false. /// @@ -256,16 +261,12 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. public func insert(db: Database) throws { - let dataMapper = DataMapper(db, self) - let changes = try dataMapper.insertStatement().execute() - if case .Managed(let rowIDColumnName) = dataMapper.primaryKey { - // Update RowID - updateFromRow(Row(dictionary: [rowIDColumnName: changes.insertedRowID])) - } + var storable: DatabasePersistable = self + try storable.insert(db) databaseEdited = false } - /// Executes an UPDATE statement to update the record. + /// Executes an UPDATE statement. /// /// On success, this method sets the *databaseEdited* flag to false. /// @@ -274,13 +275,10 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// /// - parameter db: A Database. /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. - /// RecordError.RecordNotFound is thrown if the primary key does not match + /// PersistenceError.NotFound is thrown if the primary key does not match /// any row in the database and record could not be updated. public func update(db: Database) throws { - let changes = try DataMapper(db, self).updateStatement().execute() - if changes.changedRowCount == 0 { - throw RecordError.RecordNotFound(self) - } + try (self as DatabasePersistable).update(db) databaseEdited = false } @@ -310,12 +308,16 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { do { try update(db) - } catch RecordError.RecordNotFound { + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Subclasses could override update() and update another object + // which may be the one throwing this error. try insert(db) } } - /// Executes a DELETE statement to delete the record. + /// Executes a DELETE statement. /// /// On success, this method sets the *databaseEdited* flag to true. /// @@ -323,38 +325,29 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabaseStorable { /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. public func delete(db: Database) throws -> Bool { - let changes = try DataMapper(db, self).deleteStatement().execute() - // Future calls to update() will throw RecordNotFound. Make the user + let deleted = try (self as DatabasePersistable).delete(db) + // Future calls to update() will throw NotFound. Make the user // a favor and make sure this error is thrown even if she checks the // databaseEdited flag: databaseEdited = true - return changes.changedRowCount > 0 + return deleted } - /// Executes a SELECT statetement to reload the record. + /// Executes a SELECT statetement. /// /// On success, this method sets the *databaseEdited* flag to false. /// /// - parameter db: A Database. - /// - throws: RecordError.RecordNotFound is thrown if the primary key does + /// - throws: PersistenceError.NotFound is thrown if the primary key does /// not match any row in the database and record could not be reloaded. public func reload(db: Database) throws { let statement = DataMapper(db, self).reloadStatement() guard let row = Row.fetchOne(statement) else { - throw RecordError.RecordNotFound(self) + throw PersistenceError.NotFound(self) } updateFromRow(row) awakeFromFetch(row) } - - /// Returns true if and only if the primary key matches a row in - /// the database. - /// - /// - parameter db: A Database. - /// - returns: Whether the primary key matches a row in the database. - final public func exists(db: Database) -> Bool { - return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) - } } @@ -375,23 +368,3 @@ extension Record : CustomStringConvertible { + ">" } } - - -// MARK: - RecordError - -/// A Record-specific error -public enum RecordError: ErrorType { - - /// No matching row could be found in the database. - case RecordNotFound(Record) -} - -extension RecordError : CustomStringConvertible { - /// A textual representation of `self`. - public var description: String { - switch self { - case .RecordNotFound(let record): - return "Record not found: \(record)" - } - } -} From 8ed4f47f829931d5ba0426bf6db7b016c2cd6e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 9 Dec 2015 08:57:07 +0100 Subject: [PATCH 02/67] Remove reference to the databaseEdited flag from the DatabasePersistable documentation. --- GRDB/Core/Protocols/DatabasePersistable.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 6e6c840b5..dc4606eef 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -67,8 +67,6 @@ public extension DatabasePersistable { /// Executes an INSERT statement. /// - /// On success, this method sets the *databaseEdited* flag to false. - /// /// This method is guaranteed to have inserted a row in the database if it /// returns without error. /// From 00b052bddf7713537d33c1e4ffc4109780f5cc53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 08:03:34 +0100 Subject: [PATCH 03/67] Record.playground update --- Playgrounds/Record.playground/contents.xcplayground | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Playgrounds/Record.playground/contents.xcplayground b/Playgrounds/Record.playground/contents.xcplayground index a204ba673..06828af92 100644 --- a/Playgrounds/Record.playground/contents.xcplayground +++ b/Playgrounds/Record.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file From cc59f624204da442ddff2c4aaf0157c4c00eaa99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 08:09:36 +0100 Subject: [PATCH 04/67] Refactor DatabasePersistable so that all CRUD methods are dynamically dispatched. The protocol exposes default implementation for CRUD methods as statically dispatched method that are available for adopting types in their own implementations of CRUD methods. Introduce DatabasePersistable.save() (#12) --- GRDB/Core/Protocols/DatabasePersistable.swift | 187 +++++++++++++++--- GRDB/Record/Record.swift | 27 +-- 2 files changed, 167 insertions(+), 47 deletions(-) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index dc4606eef..55834431d 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -55,13 +55,6 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// } /// } mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) -} - -public extension DatabasePersistable { - - /// The default implementation does nothing. - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { - } // MARK: - CRUD @@ -74,9 +67,121 @@ public extension DatabasePersistable { /// didInsertWithRowID(:forColumn:) method is called upon successful /// insertion. /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of insert(). In their implementation, it is recommended + /// that they invoke the performInsert() method. + /// /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. + mutating func insert(db: Database) throws + + /// Executes an UPDATE statement. + /// + /// This method is guaranteed to have updated a row in the database if it + /// returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of update(). In their implementation, it is recommended + /// that they invoke the performUpdate() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(db: Database) throws + + /// Saves `self` in the database. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// This method is guaranteed to have inserted or updated a row in the + /// database if it returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of save(). In their implementation, it is recommended + /// that they invoke the performSave() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs, or errors + /// thrown by update(). + mutating func save(db: Database) throws + + /// Executes a DELETE statement. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of delete(). In their implementation, it is recommended + /// that they invoke the performDelete() method. + /// + /// - parameter db: A Database. + /// - returns: Whether a database row was deleted. + /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. + func delete(db: Database) throws -> Bool + + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of exists(). In their implementation, it is recommended + /// that they invoke the performExists() method. + /// + /// - parameter db: A Database. + /// - returns: Whether the primary key matches a row in the database. + func exists(db: Database) -> Bool +} + +public extension DatabasePersistable { + + /// The default implementation does nothing. + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { + } + + + // MARK: - CRUD + + /// The default implementation for insert(). It invokes performInsert(). mutating func insert(db: Database) throws { + try performInsert(db) + } + + /// The default implementation for update(). It invokes performUpdate(). + func update(db: Database) throws { + try performUpdate(db) + } + + /// The default implementation for save(). It invokes performSave(). + mutating func save(db: Database) throws { + try performSave(db) + } + + /// The default implementation for delete(). It invokes performDelete(). + func delete(db: Database) throws -> Bool { + return try performDelete(db) + } + + /// The default implementation for exists(). It invokes performExists(). + func exists(db: Database) -> Bool { + return performExists(db) + } + + + // MARK: - CRUD Internals + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performInsert() provides the default implementation for insert(). Types + /// that adopt DatabasePersistable can invoke performInsert() in their + /// implementation of insert(). They should not provide their own + /// implementation of performInsert(). + mutating func performInsert(db: Database) throws { let dataMapper = DataMapper(db, self) let changes = try dataMapper.insertStatement().execute() if case .Managed(let rowIDColumnName) = dataMapper.primaryKey { @@ -84,39 +189,69 @@ public extension DatabasePersistable { } } - /// Executes an UPDATE statement. + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. /// - /// This method is guaranteed to have updated a row in the database if it - /// returns without error. - /// - /// - parameter db: A Database. - /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. - /// PersistenceError.NotFound is thrown if the primary key does not - /// match any row in the database. - func update(db: Database) throws { + /// performUpdate() provides the default implementation for update(). Types + /// that adopt DatabasePersistable can invoke performUpdate() in their + /// implementation of update(). They should not provide their own + /// implementation of performUpdate(). + func performUpdate(db: Database) throws { let changes = try DataMapper(db, self).updateStatement().execute() if changes.changedRowCount == 0 { throw PersistenceError.NotFound(self) } } - /// Executes a DELETE statement. + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. /// - /// - parameter db: A Database. - /// - returns: Whether a database row was deleted. - /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. - func delete(db: Database) throws -> Bool { + /// performSave() provides the default implementation for save(). Types + /// that adopt DatabasePersistable can invoke performSave() in their + /// implementation of save(). They should not provide their own + /// implementation of performSave(). + mutating func performSave(db: Database) throws { + // Make sure we call self.insert and self.update so that classes that + // override insert or save have opportunity to perform their custom job. + + if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { + try insert(db) + return + } + + do { + try update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update another + // object which may be the one throwing this error. + try insert(db) + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performDelete() provides the default implementation for deelte(). Types + /// that adopt DatabasePersistable can invoke performDelete() in their + /// implementation of delete(). They should not provide their own + /// implementation of performDelete(). + func performDelete(db: Database) throws -> Bool { return try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 } - /// Returns true if and only if the primary key matches a row in - /// the database. + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. /// - /// - parameter db: A Database. - /// - returns: Whether the primary key matches a row in the database. - func exists(db: Database) -> Bool { + /// performExists() provides the default implementation for exists(). Types + /// that adopt DatabasePersistable can invoke performExists() in their + /// implementation of exists(). They should not provide their own + /// implementation of performExists(). + func performExists(db: Database) -> Bool { return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) } + } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 8e67e7788..bcd11c4d1 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -261,8 +261,8 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. public func insert(db: Database) throws { - var storable: DatabasePersistable = self - try storable.insert(db) + var persistable = self as DatabasePersistable + try persistable.performInsert(db) databaseEdited = false } @@ -278,7 +278,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// PersistenceError.NotFound is thrown if the primary key does not match /// any row in the database and record could not be updated. public func update(db: Database) throws { - try (self as DatabasePersistable).update(db) + try performUpdate(db) databaseEdited = false } @@ -298,23 +298,8 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - throws: A DatabaseError whenever a SQLite error occurs, or errors /// thrown by update(). final public func save(db: Database) throws { - // Make sure we call self.insert and self.update so that classes that - // override insert or save have opportunity to perform their custom job. - - if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { - try insert(db) - return - } - - do { - try update(db) - } catch PersistenceError.NotFound { - // TODO: check that the not persisted objet is self - // - // Why? Subclasses could override update() and update another object - // which may be the one throwing this error. - try insert(db) - } + var persistable = self as DatabasePersistable + try persistable.performSave(db) } /// Executes a DELETE statement. @@ -325,7 +310,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever a SQLite error occurs. public func delete(db: Database) throws -> Bool { - let deleted = try (self as DatabasePersistable).delete(db) + let deleted = try performDelete(db) // Future calls to update() will throw NotFound. Make the user // a favor and make sure this error is thrown even if she checks the // databaseEdited flag: From c4fa174fadd6555e391d592b6073805a08ec5e24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 08:14:36 +0100 Subject: [PATCH 05/67] DatabasePersistable documentation (#12) --- GRDB/Core/Protocols/DatabasePersistable.swift | 25 ++++++++++++++----- GRDB/Record/Record.swift | 3 ++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 55834431d..e40df1f73 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -92,7 +92,8 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// match any row in the database. func update(db: Database) throws - /// Saves `self` in the database. + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. @@ -146,27 +147,39 @@ public extension DatabasePersistable { // MARK: - CRUD - /// The default implementation for insert(). It invokes performInsert(). + /// Executes an INSERT statement. + /// + /// The default implementation for insert() invokes performInsert(). mutating func insert(db: Database) throws { try performInsert(db) } - /// The default implementation for update(). It invokes performUpdate(). + /// Executes an UPDATE statement. + /// + /// The default implementation for update() invokes performUpdate(). func update(db: Database) throws { try performUpdate(db) } - /// The default implementation for save(). It invokes performSave(). + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// The default implementation for save() invokes performSave(). mutating func save(db: Database) throws { try performSave(db) } - /// The default implementation for delete(). It invokes performDelete(). + /// Executes a DELETE statement. + /// + /// The default implementation for delete() invokes performDelete(). func delete(db: Database) throws -> Bool { return try performDelete(db) } - /// The default implementation for exists(). It invokes performExists(). + /// Returns true if and only if the primary key matches a row in + /// the database. + /// + /// The default implementation for exists() invokes performExists(). func exists(db: Database) -> Bool { return performExists(db) } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index bcd11c4d1..48841a59d 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -282,7 +282,8 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable databaseEdited = false } - /// Saves the record in the database. + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. /// /// If the record has a non-nil primary key and a matching row in the /// database, this method performs an update. From 4e183439b5e7e7b60b5b16052995bfc0577c322d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 09:06:00 +0100 Subject: [PATCH 06/67] DatabasePersistable.didInsertWithRowID(_:forColumn:) is called even when there is no INTEGER PRIMARY KEY column. DatabaseTableMapping no longer extends RowConvertible. (#12) --- GRDB/Core/Protocols/DatabasePersistable.swift | 26 ++-- .../Core/Protocols/DatabaseTableMapping.swift | 5 +- GRDB/Record/Record.swift | 13 +- README.md | 142 ++++++++++++++++-- TODO.md | 2 +- 5 files changed, 162 insertions(+), 26 deletions(-) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index e40df1f73..320ac4dec 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -40,9 +40,9 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// } var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } - /// If the underlying database table has an INTEGER PRIMARY KEY, this method - /// is called after a successful insertion. Adopting type may implement this - /// method and update their primary key accordingly. + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. /// /// This method is optional: the default implementation does nothing. /// @@ -50,11 +50,11 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// var id: Int64? /// var name: String? /// - /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { + /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { /// self.id = rowID /// } /// } - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) // MARK: - CRUD @@ -63,9 +63,9 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// This method is guaranteed to have inserted a row in the database if it /// returns without error. /// - /// When the table has an INTEGER PRIMARY KEY, the - /// didInsertWithRowID(:forColumn:) method is called upon successful - /// insertion. + /// Upon successful insertion, the didInsertWithRowID(:forColumn:) method + /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own @@ -141,7 +141,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { public extension DatabasePersistable { /// The default implementation does nothing. - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String) { + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { } @@ -197,8 +197,12 @@ public extension DatabasePersistable { mutating func performInsert(db: Database) throws { let dataMapper = DataMapper(db, self) let changes = try dataMapper.insertStatement().execute() - if case .Managed(let rowIDColumnName) = dataMapper.primaryKey { - didInsertWithRowID(changes.insertedRowID!, forColumn: rowIDColumnName) + if let rowID = changes.insertedRowID { + if case .Managed(let columnName) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: columnName) + } else { + didInsertWithRowID(rowID, forColumn: nil) + } } } diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index 70230e062..a0f68cd4e 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -8,11 +8,12 @@ /// Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship? /// /// DatabaseTableMapping is adopted by Record. -public protocol DatabaseTableMapping : RowConvertible { +public protocol DatabaseTableMapping { + /// The name of the database table. static func databaseTableName() -> String? } -extension DatabaseTableMapping { +extension RowConvertible where Self: DatabaseTableMapping { // MARK: - Single-Column Primary Key diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 48841a59d..8f73dc3fc 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -148,9 +148,16 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable public func updateFromRow(row: Row) { } - /// TODO - final public func didInsertWithRowID(rowID: Int64, forColumn name: String) { - updateFromRow(Row(dictionary: [name: rowID])) + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// The default implementation calls updateFromRow() if the table has an + /// INTEGER PRIMARY KEY. + public func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + if let name = name { + updateFromRow(Row(dictionary: [name: rowID])) + } } diff --git a/README.md b/README.md index c3522684f..0fbc98281 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,8 @@ Documentation - [Migrations](#migrations): Transform your database as your application evolves. - [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. - [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. - - [Records](#records): CRUD operations and changes tracking. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. + - [Records](#records): the full toolkit, plus changes tracking. - **[Sample Code](#sample-code)** @@ -500,10 +501,10 @@ For example: ```swift dbQueue.inDatabase { db in - // The number of persons with an email ending in @domain.com: + // The number of persons with an email ending in @example.com: let count = Int.fetchOne(db, "SELECT COUNT(*) FROM persons WHERE email LIKE ?", - arguments: ["%@domain.com"])! + arguments: ["%@example.com"])! // The emails of people who own at least two pets: let emails = String.fetch(db, @@ -1230,7 +1231,8 @@ On top of the SQLite API described above, GRDB provides a toolkit for applicatio - [Migrations](#migrations): Transform your database as your application evolves. - [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. - [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. -- [Records](#records): CRUD operations and changes tracking. +- [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. +- [Records](#records): the full toolkit, plus changes tracking. ## Migrations @@ -1488,6 +1490,126 @@ PointOfInterest(dictionary: [ See also the [Record](#records) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. +### Fetching by Key + +**Adopt the `DatabaseTableMapping` protocol** on top of `RowConvertible`: + +```swift +public protocol DatabaseTableMapping { + /// The name of the database table. + static func databaseTableName() -> String? +} +``` + +You are then granted with fetching methods based on database keys: + +```swift +Person.fetch(db, keys: ...) // DatabaseSequence +Person.fetchAll(db, keys: ...) // [Person] +Person.fetchOne(db, key: ...) // Person? +``` + +Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: + +- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread. +- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise). +- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations. + +The order of sequences and arrays returned by the key-based methods is undefined. To specify the order of returned elements, use a raw SQL query. + + +**When the database table has a single column primary key**, you can fetch given key values: + +```swift +// SELECT * FROM persons WHERE id = 1 +Person.fetchOne(db, key: 1) + +// SELECT * FROM persons WHERE id IN (1,2,3) +Person.fetch(db, keys: [1,2,3]) + +// SELECT * FROM countries WHERE isoCode = 'FR' +Country.fetchOne(db, key: "FR") + +// SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') +Country.fetchAll(db, keys: ["FR", "ES", "US"]) +``` + +**For multi-column primary keys and secondary keys**, use a key dictionary: + +```swift +// SELECT * FROM persons WHERE email = 'me@example.com' +Person.fetchOne(db, key: ["email": "me@example.com"]) + +// SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' +Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) +``` + + +## DatabasePersistable Protocol + +**The `DatabasePersistable` protocol grants adopting types with CRUD methods.** + +It has only two mandatory methods: + +```swift +public protocol DatabasePersistable : DatabaseTableMapping { + /// The name of the database table (from DatabaseTableMapping) + static func databaseTableName() -> String? + + /// Returns the values that should be stored in the database. + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } +} +``` + +The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: + +```swift +struct Person { + let id: Int64? + let name: String? + + static func databaseTableName() -> String? { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } +} +``` + +Once `storedDatabaseDictionary` implemented, adopting types are granted with the full CRUD toolkit: + +```swift +try dbQueue.inDatabase { db in + var person = Person(...) + try person.insert(db) // INSERT + try person.update(db) // UPDATE + try person.save(db) // Inserts or updates + try person.delete(db) // DELETE + person.exists(db) // Returns a Bool +} +``` + +Your type may store its rowID after a successful insertion: + +``` +struct Person { + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + self.id = rowID + } +} + +var person = Person(id: nil, name: "Arthur") +person.id // nil +try person.save(db) +person.id // some value +``` + + +TODO: document how to "override" the default CRUD methods. + + ## Records - [Overview](#record-overview) @@ -1644,7 +1766,9 @@ Person overrides `databaseTableName()` to return the name of the table that shou } ``` -Person overrides `storedDatabaseDictionary` to return the dictionary of values that should be stored in the database when a person is saved. `DatabaseValueConvertible` is the protocol adopted by all supported values (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: +Person overrides `storedDatabaseDictionary` to return the dictionary of values that should be stored in the database when a person is saved. + +Person overrides `storedDatabaseDictionary` and returns a dictionary whose keys are column names, and values any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift /// The values stored in the database @@ -1721,10 +1845,10 @@ For example: ```swift dbQueue.inDatabase { db in - // All persons with an email ending in @domain.com: + // All persons with an email ending in @example.com: Person.fetch(db, "SELECT * FROM persons WHERE email LIKE ?", - arguments: ["%@domain.com"]) + arguments: ["%@example.com"]) // All persons who have a single citizenship: Person.fetch(db, @@ -1746,8 +1870,8 @@ dbQueue.inDatabase { db in // SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') Country.fetchAll(db, keys: ["FR", "ES", "US"]) - // SELECT * FROM persons WHERE email = 'me@domain.com' - Person.fetchOne(db, key: ["email": "me@domain.com"]) + // SELECT * FROM persons WHERE email = 'me@example.com' + Person.fetchOne(db, key: ["email": "me@example.com"]) // SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) diff --git a/TODO.md b/TODO.md index 4c09df4ec..ed54aca52 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,7 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ - +- [ ] public class func databaseTableName() -> String? should return a String. Record should fatalError in its implementation. Not sure: From e3b7269f3bf87e54360801367a9e1fd52e74a83e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 09:13:11 +0100 Subject: [PATCH 07/67] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0fbc98281..ac0177b2e 100644 --- a/README.md +++ b/README.md @@ -1593,7 +1593,7 @@ try dbQueue.inDatabase { db in Your type may store its rowID after a successful insertion: -``` +```swift struct Person { mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { self.id = rowID From 52b13da2b3332d630444126a4afe589cb3a64739 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 13:23:45 +0100 Subject: [PATCH 08/67] DatabaseTableMapping.databaseTableName() now returns a non-optional String --- CHANGELOG.md | 12 ++++++ DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift | 2 +- .../GRDBDemoiOS7/GRDBDemoiOS7/Person.swift | 2 +- GRDB Tests/Experimental/MappingTests.swift | 2 +- GRDB Tests/Public/CrashTests.swift | 12 +++--- .../Record/MinimalPrimaryKeyRowIDTests.swift | 2 +- .../Record/MinimalPrimaryKeySingleTests.swift | 2 +- .../Record/PrimaryKeyMultipleTests.swift | 2 +- .../Public/Record/PrimaryKeyNoneTests.swift | 2 +- .../Public/Record/PrimaryKeyRowIDTests.swift | 2 +- .../Public/Record/PrimaryKeySingleTests.swift | 2 +- ...leWithReplaceConflictResolutionTests.swift | 2 +- .../Record/RecordAwakeFromFetchTests.swift | 2 +- .../Record/RecordUpdateFromRowTests.swift | 2 +- GRDB.xcodeproj/project.pbxproj | 2 + GRDB/Core/Protocols/DatabasePersistable.swift | 7 ++-- .../Core/Protocols/DatabaseTableMapping.swift | 21 ++++------ GRDB/Record/Record.swift | 12 +++--- .../Contents.swift | 2 +- Playgrounds/Record.playground/Contents.swift | 2 +- README.md | 39 +++++++++++++++---- 21 files changed, 81 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6468573a..f8e3d81f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,18 @@ Release Notes ============= +## Next Release + +**New** + +- The `DatabasePersistable` protocol grants any adopting type the CRUD methods that used to be reserved to Record subclasses. + +**Breaking Changes** + +- `RecordError` has been renamed `PersistenceError` +- `Record.databaseTableName()` now returns a non-optional String. + + ## 0.32.2 Released December 3, 2015 diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift index d5bce9b25..eb62f83a7 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift @@ -16,7 +16,7 @@ class Person : Record { // MARK: - Record - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift index 855d857a6..f45f1f056 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift @@ -14,7 +14,7 @@ class Person : Record { // MARK: - Record - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/GRDB Tests/Experimental/MappingTests.swift b/GRDB Tests/Experimental/MappingTests.swift index 4fabae0d1..601020fe7 100644 --- a/GRDB Tests/Experimental/MappingTests.swift +++ b/GRDB Tests/Experimental/MappingTests.swift @@ -114,7 +114,7 @@ class MappedRecord : Record { // Record overrides - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/GRDB Tests/Public/CrashTests.swift b/GRDB Tests/Public/CrashTests.swift index cb8cb3344..362811712 100644 --- a/GRDB Tests/Public/CrashTests.swift +++ b/GRDB Tests/Public/CrashTests.swift @@ -11,19 +11,19 @@ import GRDB class RecordWithoutDatabaseTableName: Record { } class RecordWithInexistingDatabaseTable: Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "foo" } } class RecordWithEmptyStoredDatabaseDictionary : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } } class RecordWithNilPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -33,7 +33,7 @@ class RecordWithNilPrimaryKey : Record { } class RecordForTableWithoutPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -43,7 +43,7 @@ class RecordForTableWithoutPrimaryKey : Record { } class RecordForTableWithMultipleColumnsPrimaryKey : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } @@ -53,7 +53,7 @@ class RecordForTableWithMultipleColumnsPrimaryKey : Record { } class RecordWithRowIDPrimaryKeyNotExposedInStoredDatabaseDictionary : Record { - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "records" } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift index 163fc5bd2..53a476352 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift @@ -6,7 +6,7 @@ import GRDB class MinimalRowID: Record { var id: Int64! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "minimalRowIDs" } diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift index 4deeee304..f27df4340 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift @@ -6,7 +6,7 @@ import GRDB class MinimalSingle: Record { var UUID: String! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "minimalSingles" } diff --git a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift index c61cbe2fa..c9de37246 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift @@ -7,7 +7,7 @@ class Citizenship: Record { var countryName: String! var native: Bool! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "citizenships" } diff --git a/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift b/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift index 55059916d..e2ed89383 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift @@ -5,7 +5,7 @@ import GRDB class Item: Record { var name: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "items" } diff --git a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift index 6455b62aa..bacccd596 100644 --- a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -8,7 +8,7 @@ class Person: Record { var age: Int? var creationDate: NSDate! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift index c62c3afed..8d0d77392 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift @@ -6,7 +6,7 @@ class Pet: Record { var UUID: String! var name: String! - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "pets" } diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift index 211dcc949..28e7f459d 100644 --- a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -5,7 +5,7 @@ class Email : Record { var email: String! var label: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "emails" } diff --git a/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift b/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift index ec19c3591..7a08defa0 100644 --- a/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift +++ b/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift @@ -5,7 +5,7 @@ class EventRecorder : Record { var id: Int64? var awakeFromFetchCount = 0 - override static func databaseTableName() -> String? { + override static func databaseTableName() -> String { return "eventRecorders" } diff --git a/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift b/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift index f7e9680b5..eeeba50de 100644 --- a/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift +++ b/GRDB Tests/Public/Record/RecordUpdateFromRowTests.swift @@ -25,7 +25,7 @@ class Placemark : Record { super.init() } - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "placemarks" } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b95780bba..adb030893 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -398,6 +398,7 @@ 56CA221B1BB41533009A04C5 /* StephenCelisSQLitePerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StephenCelisSQLitePerformanceTests.swift; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceRecord.swift; sourceTree = ""; }; 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CrashTests.swift; sourceTree = ""; }; + 56DBEC341C19A0020093A2EE /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; 56E1524B1B43FD5B00EE27AA /* TODO.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = TODO.md; sourceTree = ""; }; 56E5891E1BBA5D5400CC0140 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; 56E5D7CA1B4D3FED00430942 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -853,6 +854,7 @@ DC3773E919C8CBB3004FCF85 = { isa = PBXGroup; children = ( + 56DBEC341C19A0020093A2EE /* CHANGELOG.md */, DC37744719C8F50B004FCF85 /* README.md */, 56E1524B1B43FD5B00EE27AA /* TODO.md */, DC37742D19C8CC90004FCF85 /* GRDB */, diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 320ac4dec..642033d09 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -227,6 +227,8 @@ public extension DatabasePersistable { /// that adopt DatabasePersistable can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). + /// + /// This default implementation forwards the job to `update` or `insert`. mutating func performSave(db: Database) throws { // Make sure we call self.insert and self.update so that classes that // override insert or save have opportunity to perform their custom job. @@ -354,10 +356,7 @@ final class DataMapper { // MARK: - Initializer init(_ db: Database, _ persistable: DatabasePersistable) { - // Fail early if databaseTable is nil - guard let databaseTableName = persistable.dynamicType.databaseTableName() else { - fatalError("Nil returned from \(persistable.dynamicType).databaseTableName()") - } + let databaseTableName = persistable.dynamicType.databaseTableName() // Fail early if database table does not exist. guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index a0f68cd4e..a1a004904 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -1,8 +1,8 @@ -/// Types that adopt DatabaseTableMapping can be initialized from rows that come -/// from a particular table. +/// Types that adopt DatabaseTableMapping declare a particular relationship with +/// a database table. /// -/// The protocol comes with built-in methods that allow to fetch instances -/// identified by their primary key, or any other key: +/// Types that adopt both DatabaseTableMapping and RowConvertible are granted +/// with built-in methods that allow to fetch instances identified by key: /// /// Person.fetchOne(db, key: 123) // Person? /// Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship? @@ -10,7 +10,7 @@ /// DatabaseTableMapping is adopted by Record. public protocol DatabaseTableMapping { /// The name of the database table. - static func databaseTableName() -> String? + static func databaseTableName() -> String } extension RowConvertible where Self: DatabaseTableMapping { @@ -67,10 +67,7 @@ extension RowConvertible where Self: DatabaseTableMapping { // // Returns nil if keys is empty. private static func fetchByPrimaryKeyStatement(db: Database, keys: Sequence) -> SelectStatement? { - // Fail early if databaseTable is nil - guard let databaseTableName = databaseTableName() else { - fatalError("Nil returned from \(self).databaseTableName()") - } + let databaseTableName = self.databaseTableName() // Fail early if database table does not exist. guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { @@ -155,11 +152,6 @@ extension RowConvertible where Self: DatabaseTableMapping { // // Returns nil if keys is empty. private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? { - // Fail early if databaseTable is nil - guard let databaseTableName = databaseTableName() else { - fatalError("Nil returned from \(self).databaseTableName()") - } - // Avoid performing useless SELECT guard keys.count > 0 else { return nil @@ -176,6 +168,7 @@ extension RowConvertible where Self: DatabaseTableMapping { whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") } + let databaseTableName = self.databaseTableName() let whereClause = whereClauses.joinWithSeparator(" OR ") let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)" let statement = db.selectStatement(sql) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 8f73dc3fc..13ca164f8 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -73,20 +73,20 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// Returns the name of a database table. /// - /// The insert, update, save, delete, exists and reload methods require it: - /// they raise a fatal error if databaseTableName is nil. + /// This table name is required by the insert, update, save, delete, exists + /// and reload methods. /// /// class Person : Record { - /// override class func databaseTableName() -> String? { + /// override class func databaseTableName() -> String { /// return "persons" /// } /// } /// - /// The implementation of the base class Record returns nil. + /// The implementation of the base class Record raises a fatal error. /// /// - returns: The name of a database table. - public class func databaseTableName() -> String? { - return nil + public class func databaseTableName() -> String { + fatalError("Subclass must override.") } /// Returns the values that should be stored in the database. diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index a9deefd22..05de6d8df 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -30,7 +30,7 @@ class Person : Record { var id: Int64? var name: String? - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index 1deacb36e..af0625661 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -38,7 +38,7 @@ class Person : Record { // Record overrides - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } diff --git a/README.md b/README.md index ac0177b2e..522da871a 100644 --- a/README.md +++ b/README.md @@ -1497,7 +1497,7 @@ See also the [Record](#records) class, which builds on top of RowConvertible and ```swift public protocol DatabaseTableMapping { /// The name of the database table. - static func databaseTableName() -> String? + static func databaseTableName() -> String } ``` @@ -1554,7 +1554,7 @@ It has only two mandatory methods: ```swift public protocol DatabasePersistable : DatabaseTableMapping { /// The name of the database table (from DatabaseTableMapping) - static func databaseTableName() -> String? + static func databaseTableName() -> String /// Returns the values that should be stored in the database. var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } @@ -1568,7 +1568,7 @@ struct Person { let id: Int64? let name: String? - static func databaseTableName() -> String? { + static func databaseTableName() -> String { return "persons" } @@ -1578,7 +1578,7 @@ struct Person { } ``` -Once `storedDatabaseDictionary` implemented, adopting types are granted with the full CRUD toolkit: +Once `storedDatabaseDictionary` is implemented, adopting types are granted with the full CRUD toolkit: ```swift try dbQueue.inDatabase { db in @@ -1607,7 +1607,30 @@ person.id // some value ``` -TODO: document how to "override" the default CRUD methods. +### Customizing the CRUD methods + +Your custom DatabasePersistable type may want to perform extra work when the CRUD methods are invoked. + +For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. + +Do do that, implement your own version of the insert(), update() etc. method, and call the internal performInsert(), performUpdate() etc. methods in your implementation: + +```swift +struct Person : DatabasePersistable { + var uuid: String? + + mutating func insert(db: Database) throws { + if uuid == nil { + uuid = NSUUID().UUIDString + } + try performInsert(db) + } +} +``` + +> :point_up: **Note**: The `performXXX` methods should not be used outside of your custom implementation. +> +> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method, because its default implementation forwards the job to `update` or `insert`. These are the methods that may need custom implementation. ## Records @@ -1690,7 +1713,7 @@ Yet, it does a few things well: ```swift class Record { /// The table name - class func databaseTableName() -> String? + class func databaseTableName() -> String /// The values stored in the database var storedDatabaseDictionary: [String: DatabaseValueConvertible?] @@ -1761,7 +1784,7 @@ Person overrides `databaseTableName()` to return the name of the table that shou ```swift /// The table name - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } ``` @@ -2024,7 +2047,7 @@ class Person : Record { id: Int64? /// The table definition. - override class func databaseTableName() -> String? { + override class func databaseTableName() -> String { return "persons" } From 03d7d494faef4b35656fa4ff6bec352df0ffb623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 13:28:13 +0100 Subject: [PATCH 09/67] TODO.MD --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index ed54aca52..c8337e595 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,7 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ -- [ ] public class func databaseTableName() -> String? should return a String. Record should fatalError in its implementation. +- [ ] Add methods to Database that enable/disable/reset the table info cache. Migrations should run with cache disabled. Not sure: From cfd5abc1a7ce6f2d9a295ae44e4efe344be7553b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 13:28:34 +0100 Subject: [PATCH 10/67] Documentation --- .../Core/Protocols/DatabaseTableMapping.swift | 2 +- README.md | 27 ++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index a1a004904..4ec2e8b4d 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -9,7 +9,7 @@ /// /// DatabaseTableMapping is adopted by Record. public protocol DatabaseTableMapping { - /// The name of the database table. + /// The name of the database table static func databaseTableName() -> String } diff --git a/README.md b/README.md index 522da871a..8a2b34442 100644 --- a/README.md +++ b/README.md @@ -1496,11 +1496,36 @@ See also the [Record](#records) class, which builds on top of RowConvertible and ```swift public protocol DatabaseTableMapping { - /// The name of the database table. + /// The name of the database table static func databaseTableName() -> String } ``` +For example: + +```swift +// CREATE TABLE persons ( +// id INTEGER PRIMARY KEY, +// name TEXT, +// email TEXT UNIQUE COLLATE NOCASE +// ) +struct Person : RowConvertible, DatabaseTableMapping { + var id: Int64? + var name: String? + var email: String? + + static func databaseTableName() -> String { + return "persons" + } + + init(row: Row) { + id = row.value(named: "id") + name = row.value(named: "name") + email = row.value(named: "email") + } +} +``` + You are then granted with fetching methods based on database keys: ```swift From 39ff90474cda9773cb55849d65d335212fcca4f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 13:33:25 +0100 Subject: [PATCH 11/67] DatabasePersistable documentation (#12) --- GRDB/Core/Protocols/DatabasePersistable.swift | 3 +++ README.md | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 642033d09..79239af10 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -54,6 +54,9 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// self.id = rowID /// } /// } + /// + /// - parameter rowID: The inserted rowID. + /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) // MARK: - CRUD diff --git a/README.md b/README.md index 8a2b34442..f8b42c133 100644 --- a/README.md +++ b/README.md @@ -1620,6 +1620,10 @@ Your type may store its rowID after a successful insertion: ```swift struct Person { + /// Optional method that is called upon successful insertion. + /// + /// - parameter rowID: The inserted rowID. + /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { self.id = rowID } From 9b2bd07074a475342ec9988998a787e374258e17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 13:39:30 +0100 Subject: [PATCH 12/67] DatabasePersistable documentation (#12) --- GRDB/Record/Record.swift | 3 +++ README.md | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 13ca164f8..543d223c0 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -154,6 +154,9 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// /// The default implementation calls updateFromRow() if the table has an /// INTEGER PRIMARY KEY. + /// + /// - parameter rowID: The inserted rowID. + /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. public func didInsertWithRowID(rowID: Int64, forColumn name: String?) { if let name = name { updateFromRow(Row(dictionary: [name: rowID])) diff --git a/README.md b/README.md index f8b42c133..bd5811746 100644 --- a/README.md +++ b/README.md @@ -1642,7 +1642,7 @@ Your custom DatabasePersistable type may want to perform extra work when the CRU For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. -Do do that, implement your own version of the insert(), update() etc. method, and call the internal performInsert(), performUpdate() etc. methods in your implementation: +The protocol exposes *special methods* for this exact purpose: `performInsert`, `performUpdate`, `performSave`, `performDelete`, and `performExists`. ```swift struct Person : DatabasePersistable { @@ -1657,9 +1657,9 @@ struct Person : DatabasePersistable { } ``` -> :point_up: **Note**: The `performXXX` methods should not be used outside of your custom implementation. +> :point_up: **Note**: Those special methods are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. > -> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method, because its default implementation forwards the job to `update` or `insert`. These are the methods that may need custom implementation. +> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization. ## Records From 3033868814646048fb885f9679cdead1f407ce42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 14:00:19 +0100 Subject: [PATCH 13/67] README.md --- README.md | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index bd5811746..6438d0450 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ Why GRDB, when we already have the excellent [ccgus/fmdb](https://github.com/ccg **Your SQL skills are rewarded here.** You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. Without losing type safety and all niceties you expect from a real Swift library. +**GRDB provides protocols** that grant database powers to your custom types, and reduce the database noise in your application code. + **GRDB is fast**. As fast, when not faster, than FMDB and SQLite.swift. @@ -28,7 +30,7 @@ Features -------- - **A low-level [SQLite API](#sqlite-api)** that leverages the Swift 2 standard library. -- **A [Record](#records) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations. +- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations. - **[Swift type freedom](#values)**: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types. - **[Database migrations](#migrations)** - **[Database changes observation hooks](#database-changes-observation)** @@ -64,12 +66,14 @@ Documentation - [Raw SQLite Pointers](#raw-sqlite-pointers) -- **[Application Tools](#application-tools)** - - [Migrations](#migrations): Transform your database as your application evolves. - - [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. - - [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. +- **[Migrations](#migrations)**: Transform your database as your application evolves. + +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. + +- **Database protocols, and Record** + - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. - - [Records](#records): the full toolkit, plus changes tracking. + - [Record](#record): The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. - **[Sample Code](#sample-code)** @@ -275,7 +279,7 @@ dbQueue.inDatabase { db in } ``` -**Custom models** are your application objects that can initialize themselves from rows (see the [RowConvertible protocol](#rowconvertible-protocol) and the [Record class](#records)): +**Custom models** are your application objects that can initialize themselves from rows (see the [RowConvertible protocol](#rowconvertible-protocol) and the [Record class](#record)): ```swift dbQueue.inDatabase { db in @@ -560,7 +564,7 @@ They can be [directly fetched](#value-queries) from the database: let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] ``` -Use them as [Record](#records) properties: +Use them as [Record](#record) properties: ```swift class Link : Record { @@ -1228,11 +1232,12 @@ Application Tools On top of the SQLite API described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: -- [Migrations](#migrations): Transform your database as your application evolves. -- [Database Changes Observation](#database-changes-observation): A robust way to perform post-commit and post-rollback actions. -- [RowConvertible Protocol](#rowconvertible-protocol): Turn database rows into handy types, without sacrificing performance. -- [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. -- [Records](#records): the full toolkit, plus changes tracking. +- **[Migrations](#migrations)**: Transform your database as your application evolves. +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. +- **Database protocols, and Record** + - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. +- **[Record](#record)**: The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. ## Migrations @@ -1487,7 +1492,7 @@ PointOfInterest(dictionary: [ "title": "Rome"]) ``` -See also the [Record](#records) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. +See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. ### Fetching by Key From 1330726470241ceb214988f279896a07a35e370c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 14:02:13 +0100 Subject: [PATCH 14/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6438d0450..9628525b7 100644 --- a/README.md +++ b/README.md @@ -1667,7 +1667,7 @@ struct Person : DatabasePersistable { > :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization. -## Records +## Record - [Overview](#record-overview) - [Subclassing Record](#subclassing-record) From e9c55f47c65f7d8fabe105af021bb733247814c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 14:24:55 +0100 Subject: [PATCH 15/67] Database.clearSchemaCache(). Migrations are run with disabled schema cache. --- CHANGELOG.md | 1 + GRDB/Core/Database.swift | 32 ++++++++++++++++++++++++-- GRDB/Migrations/DatabaseMigrator.swift | 6 +++-- TODO.md | 1 - 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8e3d81f7..fe4245265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Release Notes **New** - The `DatabasePersistable` protocol grants any adopting type the CRUD methods that used to be reserved to Record subclasses. +- `Database.clearSchemaCache()` **Breaking Changes** diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 59ac5bc54..63e0e0897 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -453,6 +453,31 @@ public final class Database { // ========================================================================= // MARK: - Database Informations + /// Clears the database schema cache. + /// + /// You may need to clear the cache if you modify the database schema + /// outside of a migration (see DatabaseMigrator). + public func clearSchemaCache() { + assertValidQueue() + columnInfosCache = [:] + } + + /// When false, the schema cache is disabled. + private var schemaCacheIsEnabled: Bool + + func withDisabledSchemaCache(@noescape block:() throws -> ()) rethrows { + assertValidQueue() + + var schemaCacheWasEnabled = schemaCacheIsEnabled + defer { + schemaCacheIsEnabled = schemaCacheWasEnabled + } + + schemaCacheIsEnabled = false + clearSchemaCache() + try block() + } + /// The last error message var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } @@ -574,13 +599,15 @@ public final class Database { // Cache for columnInfosForTable(named:) private var columnInfosCache: [String: [ColumnInfo]] = [:] private func columnInfosForTable(named tableName: String) -> [ColumnInfo] { - if let columnInfos = columnInfosCache[tableName] { + if let columnInfos = columnInfosCache[tableName] where schemaCacheIsEnabled { return columnInfos } else { // This pragma is case-insensitive: PRAGMA table_info("PERSONS") and // PRAGMA table_info("persons") yield the same results. let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - columnInfosCache[tableName] = columnInfos + if schemaCacheIsEnabled { + columnInfosCache[tableName] = columnInfos + } return columnInfos } } @@ -610,6 +637,7 @@ public final class Database { init(path: String, configuration: Configuration) throws { self.configuration = configuration + self.schemaCacheIsEnabled = true // See https://www.sqlite.org/c3ref/open.html var sqliteConnection = SQLiteConnection() diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 6a41e34b1..73324986a 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -85,8 +85,10 @@ public struct DatabaseMigrator { /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(dbQueue: DatabaseQueue) throws { try dbQueue.inDatabase { db in - try self.setupMigrations(db) - try self.runMigrations(db) + try db.withDisabledSchemaCache { + try self.setupMigrations(db) + try self.runMigrations(db) + } } } diff --git a/TODO.md b/TODO.md index c8337e595..8146f42a6 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,6 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ -- [ ] Add methods to Database that enable/disable/reset the table info cache. Migrations should run with cache disabled. Not sure: From 05956f816027c0e9196dd196e8fab5de613e0f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 14:32:29 +0100 Subject: [PATCH 16/67] README.md --- README.md | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9628525b7..d828c04a5 100644 --- a/README.md +++ b/README.md @@ -1608,17 +1608,14 @@ struct Person { } ``` -Once `storedDatabaseDictionary` is implemented, adopting types are granted with the full CRUD toolkit: +Adopting types are granted with the CRUD toolkit: ```swift -try dbQueue.inDatabase { db in - var person = Person(...) - try person.insert(db) // INSERT - try person.update(db) // UPDATE - try person.save(db) // Inserts or updates - try person.delete(db) // DELETE - person.exists(db) // Returns a Bool -} +func insert(db: Database) throws // INSERT +func update(db: Database) throws // UPDATE +func save(db: Database) throws // inserts or updates +func delete(db: Database) throws -> Bool // DELETE +func exists(db: Database) -> Bool // Whether a matching row exists ``` Your type may store its rowID after a successful insertion: From 75ee0d0ae21d5c422e22047b2bc7c935c516ab88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 16:02:28 +0100 Subject: [PATCH 17/67] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d828c04a5..66ca71619 100644 --- a/README.md +++ b/README.md @@ -1594,7 +1594,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift -struct Person { +struct Person : DatabasePersistable { let id: Int64? let name: String? @@ -1621,7 +1621,7 @@ func exists(db: Database) -> Bool // Whether a matching row exists Your type may store its rowID after a successful insertion: ```swift -struct Person { +extension Person { /// Optional method that is called upon successful insertion. /// /// - parameter rowID: The inserted rowID. From de305f9831fd032352ee773a77de0ed3306f921f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 16:12:18 +0100 Subject: [PATCH 18/67] README.md --- README.md | 248 +++++++++++++++++++++++++++--------------------------- 1 file changed, 124 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index 66ca71619..921ca7ab4 100644 --- a/README.md +++ b/README.md @@ -68,13 +68,13 @@ Documentation - **[Migrations](#migrations)**: Transform your database as your application evolves. -- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. - - **Database protocols, and Record** - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. - [Record](#record): The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. + - **[Sample Code](#sample-code)** @@ -1233,11 +1233,11 @@ Application Tools On top of the SQLite API described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: - **[Migrations](#migrations)**: Transform your database as your application evolves. -- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. - **Database protocols, and Record** - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. -- **[Record](#record)**: The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. + - **[Record](#record)**: The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. +- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. ## Migrations @@ -1320,126 +1320,6 @@ migrator.registerMigrationWithoutForeignKeyChecks("AddNotNullCheckOnName") { db While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors. -## Database Changes Observation - -The TransactionObserverType protocol lets you **observe database changes**: - -```swift -public protocol TransactionObserverType : class { - // Notifies a database change: - // - event.kind (insert, update, or delete) - // - event.tableName - // - event.rowID - func databaseDidChangeWithEvent(event: DatabaseEvent) - - // An opportunity to rollback pending changes by throwing an error. - func databaseWillCommit() throws - - // Database changes have been committed. - func databaseDidCommit(db: Database) - - // Database changes have been rollbacked. - func databaseDidRollback(db: Database) -} -``` - -**There is one transaction observer per database:** - -```swift -var config = Configuration() -config.transactionObserver = MyObserver() -let dbQueue = try DatabaseQueue(path: databasePath, configuration: config) -``` - -Protocol callbacks are all invoked on the database queue. - -**All database changes are notified** to databaseDidChangeWithEvent, inserts, updates and deletes, including indirect ones triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions). - -Those changes are not actually applied until databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation: - -```swift -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // didChange - return .Commit // willCommit, didCommit -} - -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // didChange - return .Rollback // didRollback -} -``` - -Database statements that are executed outside of an explicit transaction do not drop off the radar: - -```swift -try dbQueue.inDatabase { db in - try db.execute("INSERT ...") // didChange, willCommit, didCommit - try db.execute("UPDATE ...") // didChange, willCommit, didCommit -} -``` - -**Eventual errors** thrown from databaseWillCommit are exposed to the application code: - -```swift -do { - try dbQueue.inTransaction { db in - ... - return .Commit // willCommit (throws), didRollback - } -} catch { - // The error thrown by the transaction observer. -} -``` - -> :point_up: **Note**: The databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. - - -### Sample Transaction Observer: TableChangeObserver - -Let's write an object that notifies, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly. - -```swift -/// The notification posted when database tables have changed: -let DatabaseTablesDidChangeNotification = "DatabaseTablesDidChangeNotification" -let ChangedTableNamesKey = "ChangedTableNames" - -/// TableChangeObserver posts a DatabaseTablesDidChangeNotification on the main -/// thread after database tables have changed. -class TableChangeObserver : NSObject, TransactionObserverType { - private var changedTableNames: Set = [] - - func databaseDidChangeWithEvent(event: DatabaseEvent) { - // Remember the name of the changed table: - changedTableNames.insert(event.tableName) - } - - func databaseWillCommit() throws { - // Let go - } - - func databaseDidCommit(db: Database) { - // Extract the names of changed tables, and reset until next - // database event: - let changedTableNames = self.changedTableNames - self.changedTableNames = [] - - // Notify - dispatch_async(dispatch_get_main_queue()) { - NSNotificationCenter.defaultCenter().postNotificationName( - DatabaseTablesDidChangeNotification, - object: self, - userInfo: [ChangedTableNamesKey: changedTableNames]) - } - } - - func databaseDidRollback(db: Database) { - // Reset until next database event: - self.changedTableNames = [] - } -} -``` - - ## RowConvertible Protocol **The `RowConvertible` protocol grants fetching methods to any type** that can be initialized from a database row: @@ -2246,6 +2126,126 @@ person.insert(db) // Replace any existing person named "Arthur" ``` +## Database Changes Observation + +The `TransactionObserverType` protocol lets you **observe database changes**: + +```swift +public protocol TransactionObserverType : class { + // Notifies a database change: + // - event.kind (insert, update, or delete) + // - event.tableName + // - event.rowID + func databaseDidChangeWithEvent(event: DatabaseEvent) + + // An opportunity to rollback pending changes by throwing an error. + func databaseWillCommit() throws + + // Database changes have been committed. + func databaseDidCommit(db: Database) + + // Database changes have been rollbacked. + func databaseDidRollback(db: Database) +} +``` + +**There is one transaction observer per database:** + +```swift +var config = Configuration() +config.transactionObserver = MyObserver() +let dbQueue = try DatabaseQueue(path: databasePath, configuration: config) +``` + +Protocol callbacks are all invoked on the database queue. + +**All database changes are notified** to databaseDidChangeWithEvent, inserts, updates and deletes, including indirect ones triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions). + +Those changes are not actually applied until databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation: + +```swift +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // didChange + return .Commit // willCommit, didCommit +} + +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // didChange + return .Rollback // didRollback +} +``` + +Database statements that are executed outside of an explicit transaction do not drop off the radar: + +```swift +try dbQueue.inDatabase { db in + try db.execute("INSERT ...") // didChange, willCommit, didCommit + try db.execute("UPDATE ...") // didChange, willCommit, didCommit +} +``` + +**Eventual errors** thrown from databaseWillCommit are exposed to the application code: + +```swift +do { + try dbQueue.inTransaction { db in + ... + return .Commit // willCommit (throws), didRollback + } +} catch { + // The error thrown by the transaction observer. +} +``` + +> :point_up: **Note**: The databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. + + +### Sample Transaction Observer: TableChangeObserver + +Let's write an object that notifies, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly. + +```swift +/// The notification posted when database tables have changed: +let DatabaseTablesDidChangeNotification = "DatabaseTablesDidChangeNotification" +let ChangedTableNamesKey = "ChangedTableNames" + +/// TableChangeObserver posts a DatabaseTablesDidChangeNotification on the main +/// thread after database tables have changed. +class TableChangeObserver : NSObject, TransactionObserverType { + private var changedTableNames: Set = [] + + func databaseDidChangeWithEvent(event: DatabaseEvent) { + // Remember the name of the changed table: + changedTableNames.insert(event.tableName) + } + + func databaseWillCommit() throws { + // Let go + } + + func databaseDidCommit(db: Database) { + // Extract the names of changed tables, and reset until next + // database event: + let changedTableNames = self.changedTableNames + self.changedTableNames = [] + + // Notify + dispatch_async(dispatch_get_main_queue()) { + NSNotificationCenter.defaultCenter().postNotificationName( + DatabaseTablesDidChangeNotification, + object: self, + userInfo: [ChangedTableNamesKey: changedTableNames]) + } + } + + func databaseDidRollback(db: Database) { + // Reset until next database event: + self.changedTableNames = [] + } +} +``` + + Sample Code =========== From 592798b40ff23a2b5deadab28093da64e484b6d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 16:12:55 +0100 Subject: [PATCH 19/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 921ca7ab4..0c65ff060 100644 --- a/README.md +++ b/README.md @@ -1236,7 +1236,7 @@ On top of the SQLite API described above, GRDB provides a toolkit for applicatio - **Database protocols, and Record** - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. - - **[Record](#record)**: The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. + - [Record](#record): The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. - **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. From d3ee18fe713be063524fe83d420a62ecff8d060b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 16:19:26 +0100 Subject: [PATCH 20/67] README.md --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0c65ff060..b3dd1da17 100644 --- a/README.md +++ b/README.md @@ -1459,7 +1459,7 @@ Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) **The `DatabasePersistable` protocol grants adopting types with CRUD methods.** -It has only two mandatory methods: +It has two mandatory methods: ```swift public protocol DatabasePersistable : DatabaseTableMapping { @@ -1511,10 +1511,12 @@ extension Person { } } -var person = Person(id: nil, name: "Arthur") -person.id // nil -try person.save(db) -person.id // some value +dbQueue.inDatabase { db in + var person = Person(id: nil, name: "Arthur") + person.id // nil + try person.save(db) + person.id // some value +} ``` From 03facd1765f10799a723550c66a5c40ed475d37c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 16:51:02 +0100 Subject: [PATCH 21/67] README.md --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b3dd1da17..bc3886576 100644 --- a/README.md +++ b/README.md @@ -501,7 +501,7 @@ dbQueue.inDatabase { db in } ``` -For example: +There are many supported value types (Bool, Int, String, NSDate, Swift enums, etc.). See [Values](#values) for more information: ```swift dbQueue.inDatabase { db in @@ -510,8 +510,11 @@ dbQueue.inDatabase { db in "SELECT COUNT(*) FROM persons WHERE email LIKE ?", arguments: ["%@example.com"])! + // All URLs: + let urls = NSURL.fetchAll(db, "SELECT url FROM links") + // The emails of people who own at least two pets: - let emails = String.fetch(db, + let emails = Optional.fetchAll(db, "SELECT persons.email " + "FROM persons " + "JOIN pets ON pets.masterId = persons.id " + @@ -533,7 +536,7 @@ Both `fetch` and `fetchAll` let you iterate the full list of fetched values. The GRDB ships with built-in support for the following value types: -- **Swift**: Bool, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). +- **Swift Standard Library**: Bool, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). - **Foundation**: [NSCoding](#nscoding), [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. @@ -564,14 +567,16 @@ They can be [directly fetched](#value-queries) from the database: let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] ``` -Use them as [Record](#record) properties: +Use them in the `storedDatabaseDictionary` property of [DatabasePersistable protocol](#databasepersistable-protocol) and [Record subclasses](#record): ```swift class Link : Record { var url: NSURL? var verified: Bool - ... + override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["url": url, "verified": verified] + } } ``` @@ -1471,7 +1476,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { } ``` -The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: +The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift struct Person : DatabasePersistable { @@ -1704,7 +1709,7 @@ Person overrides `databaseTableName()` to return the name of the table that shou Person overrides `storedDatabaseDictionary` to return the dictionary of values that should be stored in the database when a person is saved. -Person overrides `storedDatabaseDictionary` and returns a dictionary whose keys are column names, and values any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: +Person overrides `storedDatabaseDictionary` and returns a dictionary whose keys are column names, and values any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift /// The values stored in the database From ccd59714459be3711c216b486e602ea94050b99d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 18:02:09 +0100 Subject: [PATCH 22/67] DatabasePersistable tests --- .../DatabasePersistableTests.swift | 286 ++++++++++++++++++ GRDB.xcodeproj/project.pbxproj | 14 + 2 files changed, 300 insertions(+) create mode 100644 GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift new file mode 100644 index 000000000..ebf98e452 --- /dev/null +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -0,0 +1,286 @@ +import XCTest +import GRDB + +struct PersistablePersonThatIgnoresRowID : DatabasePersistable { + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["name": name] + } +} + +struct PersistablePerson : DatabasePersistable { + var id: Int64? + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + self.id = rowID + } +} + +struct PersistableCountry : DatabasePersistable { + var rowID: Int64? + var isoCode: String + var name: String + + init(isoCode: String, name: String) { + self.rowID = nil + self.isoCode = isoCode + self.name = name + } + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + self.rowID = rowID + } +} + +class DatabasePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + func testInsertPersistablePersonThatIgnoresRowID() { + assertNoError { + try dbQueue.inDatabase { db in + // TODO: avoid the `var` qualifier + var person = PersistablePersonThatIgnoresRowID(name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testInsertPersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = PersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testUpdatePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = PersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = PersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + person1.name = "Craig" + try person1.update(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testSavePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = PersistablePerson(id: nil, name: "Arthur") + try person1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + var person2 = PersistablePerson(id: nil, name: "Barbara") + try person2.save(db) + + person1.name = "Craig" + try person1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testDeletePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = PersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = PersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + person1.name = "Craig" + try person1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + } + + func testExistsPersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = PersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.exists(db)) + + person.name = "Craig" + try person.delete(db) + + XCTAssertFalse(person.exists(db)) + } + } + } + + func testInsertPersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdatePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSavePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.save(db) + + var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testDeletePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.delete(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsPersistablecountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + XCTAssertTrue(country.exists(db)) + + country.name = "France Métropolitaine" + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + } + } + } +} diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index adb030893..c19f60ef3 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -10,6 +10,8 @@ 5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; }; 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; + 560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; }; + 560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; }; 560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97DA1C0E22D300BF8471 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; }; @@ -300,6 +302,7 @@ /* Begin PBXFileReference section */ 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; + 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = ""; }; 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = ""; }; 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; @@ -480,6 +483,14 @@ path = TransactionObserver; sourceTree = ""; }; + 560B3FA41C19DFF800C58EC7 /* DatabasePersistable */ = { + isa = PBXGroup; + children = ( + 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */, + ); + path = DatabasePersistable; + sourceTree = ""; + }; 560C97BF1BFD0B5B00BF8471 /* Function */ = { isa = PBXGroup; children = ( @@ -563,6 +574,7 @@ 56AC8CCC1BA3F267009E4319 /* Concurrency */, 56A238121B9C74A90082EB20 /* Database */, 56A238151B9C74A90082EB20 /* DatabaseError */, + 560B3FA41C19DFF800C58EC7 /* DatabasePersistable */, 56A238171B9C74A90082EB20 /* DatabaseValue */, 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 560C97BF1BFD0B5B00BF8471 /* Function */, @@ -1288,6 +1300,7 @@ 56CA21BB1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */, 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, + 560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56F0B9901B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */, @@ -1346,6 +1359,7 @@ 56CA21BA1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */, 56A238B61B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D741BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, + 560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */, 56F0B9911B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56F0B98F1B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */, From 00fb558db87aaa0775fdca04083fe102256e3f29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 18:20:47 +0100 Subject: [PATCH 23/67] TODO.md --- GRDB/Core/Protocols/DatabasePersistable.swift | 1 + TODO.md | 1 + 2 files changed, 2 insertions(+) diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 79239af10..9ebdc3c7a 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -59,6 +59,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) + // MARK: - CRUD /// Executes an INSERT statement. diff --git a/TODO.md b/TODO.md index 8146f42a6..1d3497250 100644 --- a/TODO.md +++ b/TODO.md @@ -4,6 +4,7 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ +- [ ] Try to avoid the mandatory mutation of DatabasePersistable.insert() Not sure: From ed22876b1d4a81bb2ab13072f600db2565954b9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 21:50:46 +0100 Subject: [PATCH 24/67] Introduce MutableDatabasePersistable --- .../DatabasePersistableTests.swift | 164 ++--------- .../MutableDatabasePersistableTests.swift | 256 ++++++++++++++++++ GRDB.xcodeproj/project.pbxproj | 6 + GRDB/Core/Protocols/DatabasePersistable.swift | 198 ++++++++++++-- GRDB/Record/Record.swift | 6 +- 5 files changed, 459 insertions(+), 171 deletions(-) create mode 100644 GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index ebf98e452..c0eb9757d 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -struct PersistablePersonThatIgnoresRowID : DatabasePersistable { +struct PersistablePerson : DatabasePersistable { var name: String? static func databaseTableName() -> String { @@ -13,30 +13,11 @@ struct PersistablePersonThatIgnoresRowID : DatabasePersistable { } } -struct PersistablePerson : DatabasePersistable { - var id: Int64? - var name: String? - - static func databaseTableName() -> String { - return "persons" - } - - var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "name": name] - } - - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { - self.id = rowID - } -} - struct PersistableCountry : DatabasePersistable { - var rowID: Int64? var isoCode: String var name: String init(isoCode: String, name: String) { - self.rowID = nil self.isoCode = isoCode self.name = name } @@ -48,10 +29,6 @@ struct PersistableCountry : DatabasePersistable { var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { return ["isoCode": isoCode, "name": name] } - - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { - self.rowID = rowID - } } class DatabasePersistableTests: GRDBTestCase { @@ -78,125 +55,28 @@ class DatabasePersistableTests: GRDBTestCase { } } - func testInsertPersistablePersonThatIgnoresRowID() { - assertNoError { - try dbQueue.inDatabase { db in - // TODO: avoid the `var` qualifier - var person = PersistablePersonThatIgnoresRowID(name: "Arthur") - try person.insert(db) - - let rows = Row.fetchAll(db, "SELECT * FROM persons") - XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") - } - } - } - func testInsertPersistablePerson() { assertNoError { try dbQueue.inDatabase { db in - var person = PersistablePerson(id: nil, name: "Arthur") + let person = PersistablePerson(name: "Arthur") try person.insert(db) let rows = Row.fetchAll(db, "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") } } } - func testUpdatePersistablePerson() { - assertNoError { - try dbQueue.inDatabase { db in - var person1 = PersistablePerson(id: nil, name: "Arthur") - try person1.insert(db) - var person2 = PersistablePerson(id: nil, name: "Barbara") - try person2.insert(db) - - person1.name = "Craig" - try person1.update(db) - - let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) - XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") - XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) - XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") - } - } - } - - func testSavePersistablePerson() { - assertNoError { - try dbQueue.inDatabase { db in - var person1 = PersistablePerson(id: nil, name: "Arthur") - try person1.save(db) - - var rows = Row.fetchAll(db, "SELECT * FROM persons") - XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) - XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") - - var person2 = PersistablePerson(id: nil, name: "Barbara") - try person2.save(db) - - person1.name = "Craig" - try person1.save(db) - - rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) - XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") - XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) - XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") - } - } - } - - func testDeletePersistablePerson() { - assertNoError { - try dbQueue.inDatabase { db in - var person1 = PersistablePerson(id: nil, name: "Arthur") - try person1.insert(db) - var person2 = PersistablePerson(id: nil, name: "Barbara") - try person2.insert(db) - - person1.name = "Craig" - try person1.delete(db) - - let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") - XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) - XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") - } - } - } - - func testExistsPersistablePerson() { - assertNoError { - try dbQueue.inDatabase { db in - var person = PersistablePerson(id: nil, name: "Arthur") - try person.insert(db) - XCTAssertTrue(person.exists(db)) - - person.name = "Craig" - try person.delete(db) - - XCTAssertFalse(person.exists(db)) - } - } - } - func testInsertPersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country = PersistableCountry(isoCode: "FR", name: "France") + let country = PersistableCountry(isoCode: "FR", name: "France") try country.insert(db) - let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + let rows = Row.fetchAll(db, "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") XCTAssertEqual(rows[0].value(named: "name") as String, "France") } } @@ -207,17 +87,17 @@ class DatabasePersistableTests: GRDBTestCase { try dbQueue.inDatabase { db in var country1 = PersistableCountry(isoCode: "FR", name: "France") try country1.insert(db) - var country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableCountry(isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) - let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") - XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") XCTAssertEqual(rows[1].value(named: "name") as String, "United States") } } @@ -229,22 +109,22 @@ class DatabasePersistableTests: GRDBTestCase { var country1 = PersistableCountry(isoCode: "FR", name: "France") try country1.save(db) - var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + var rows = Row.fetchAll(db, "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") XCTAssertEqual(rows[0].value(named: "name") as String, "France") - var country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableCountry(isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) - rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") - XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") XCTAssertEqual(rows[1].value(named: "name") as String, "United States") } } @@ -253,30 +133,28 @@ class DatabasePersistableTests: GRDBTestCase { func testDeletePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + let country1 = PersistableCountry(isoCode: "FR", name: "France") try country1.insert(db) - var country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = PersistableCountry(isoCode: "US", name: "United States") try country2.insert(db) - country1.name = "France Métropolitaine" try country1.delete(db) - let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") XCTAssertEqual(rows[0].value(named: "name") as String, "United States") } } } - func testExistsPersistablecountry() { + func testExistsPersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country = PersistableCountry(isoCode: "FR", name: "France") + let country = PersistableCountry(isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(country.exists(db)) - country.name = "France Métropolitaine" try country.delete(db) XCTAssertFalse(country.exists(db)) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift new file mode 100644 index 000000000..39065ea25 --- /dev/null +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -0,0 +1,256 @@ +import XCTest +import GRDB + +struct MutablePersistablePerson : MutableDatabasePersistable { + var id: Int64? + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + self.id = rowID + } +} + +struct MutablePersistableCountry : MutableDatabasePersistable { + var rowID: Int64? + var isoCode: String + var name: String + + init(isoCode: String, name: String) { + self.rowID = nil + self.isoCode = isoCode + self.name = name + } + + static func databaseTableName() -> String { + return "countries" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + self.rowID = rowID + } +} + +class MutableDatabasePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + func testInsertMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testUpdateMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + person1.name = "Craig" + try person1.update(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testSaveMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.save(db) + + person1.name = "Craig" + try person1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testDeleteMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + try person1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + } + + func testExistsMutablePersistablePerson() { + assertNoError { + try dbQueue.inDatabase { db in + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.exists(db)) + + try person.delete(db) + + XCTAssertFalse(person.exists(db)) + } + } + } + + func testInsertMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = MutablePersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdateMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSaveMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + try country1.save(db) + + var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testDeleteMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + try country1.delete(db) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsMutablePersistableCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var country = MutablePersistableCountry(isoCode: "FR", name: "France") + try country.insert(db) + XCTAssertTrue(country.exists(db)) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + } + } + } +} diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c19f60ef3..a0c848fc0 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -35,6 +35,8 @@ 56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; }; 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; + 5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; }; + 5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; }; 565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565B0FF81BBC7FE90098DE03 /* RowConvertible+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FF71BBC7FE90098DE03 /* RowConvertible+Foundation.swift */; }; @@ -309,6 +311,7 @@ 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; + 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableDatabasePersistableTests.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; 565B0FF71BBC7FE90098DE03 /* RowConvertible+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Foundation.swift"; sourceTree = ""; }; 565B0FFA1BBC80720098DE03 /* RowConvertible+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+FoundationTests.swift"; sourceTree = ""; }; @@ -487,6 +490,7 @@ isa = PBXGroup; children = ( 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */, + 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */, ); path = DatabasePersistable; sourceTree = ""; @@ -1283,6 +1287,7 @@ 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, + 5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */, 56FC78671BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238441B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, @@ -1342,6 +1347,7 @@ 56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */, 565B0FFB1BBC80720098DE03 /* RowConvertible+FoundationTests.swift in Sources */, 56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, + 5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */, 56FC78661BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238691B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */, diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 9ebdc3c7a..69918a024 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -3,9 +3,9 @@ /// An error thrown by a type that adopts DatabasePersistable. public enum PersistenceError: ErrorType { - /// Thrown by DatabasePersistable.update() when no matching row could be + /// Thrown by MutableDatabasePersistable.update() when no matching row could be /// found in the database. - case NotFound(DatabasePersistable) + case NotFound(MutableDatabasePersistable) } extension PersistenceError : CustomStringConvertible { @@ -18,10 +18,18 @@ extension PersistenceError : CustomStringConvertible { } } -// MARK: - DatabasePersistable -/// Types that adopt DatabasePersistable can be inserted, updated, and deleted. -public protocol DatabasePersistable : DatabaseTableMapping { +// MARK: - MutableDatabasePersistable + +/// Types that adopt MutableDatabasePersistable can be inserted, updated, +/// and deleted. +/// +/// This protocol is intented for types that have an INTEGER PRIMARY KEY, and +/// are interested in the inserted RowID: they can mutate themselves upon +/// successful insertion with the didInsertWithRowID(_:forColumn:) method. +/// +/// The insert() and save() methods are mutating methods. +public protocol MutableDatabasePersistable : DatabaseTableMapping { /// Returns the values that should be stored in the database. /// @@ -30,7 +38,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// /// In particular, primary key columns, if any, must be included. /// - /// struct Person : DatabasePersistable { + /// struct Person : MutableDatabasePersistable { /// var id: Int64? /// var name: String? /// @@ -46,7 +54,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { /// /// This method is optional: the default implementation does nothing. /// - /// struct Person : DatabasePersistable { + /// struct Person : MutableDatabasePersistable { /// var id: Int64? /// var name: String? /// @@ -142,7 +150,7 @@ public protocol DatabasePersistable : DatabaseTableMapping { func exists(db: Database) -> Bool } -public extension DatabasePersistable { +public extension MutableDatabasePersistable { /// The default implementation does nothing. mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { @@ -192,11 +200,11 @@ public extension DatabasePersistable { // MARK: - CRUD Internals /// Don't invoke this method directly: it is an internal method for types - /// that adopt DatabasePersistable. + /// that adopt MutableDatabasePersistable. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt DatabasePersistable can invoke performInsert() in their - /// implementation of insert(). They should not provide their own + /// that adopt MutableDatabasePersistable can invoke performInsert() in + /// their implementation of insert(). They should not provide their own /// implementation of performInsert(). mutating func performInsert(db: Database) throws { let dataMapper = DataMapper(db, self) @@ -211,11 +219,11 @@ public extension DatabasePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt DatabasePersistable. + /// that adopt MutableDatabasePersistable. /// /// performUpdate() provides the default implementation for update(). Types - /// that adopt DatabasePersistable can invoke performUpdate() in their - /// implementation of update(). They should not provide their own + /// that adopt MutableDatabasePersistable can invoke performUpdate() in + /// their implementation of update(). They should not provide their own /// implementation of performUpdate(). func performUpdate(db: Database) throws { let changes = try DataMapper(db, self).updateStatement().execute() @@ -225,10 +233,10 @@ public extension DatabasePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt DatabasePersistable. + /// that adopt MutableDatabasePersistable. /// /// performSave() provides the default implementation for save(). Types - /// that adopt DatabasePersistable can invoke performSave() in their + /// that adopt MutableDatabasePersistable can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -254,22 +262,22 @@ public extension DatabasePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt DatabasePersistable. + /// that adopt MutableDatabasePersistable. /// /// performDelete() provides the default implementation for deelte(). Types - /// that adopt DatabasePersistable can invoke performDelete() in their - /// implementation of delete(). They should not provide their own + /// that adopt MutableDatabasePersistable can invoke performDelete() in + /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). func performDelete(db: Database) throws -> Bool { return try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 } /// Don't invoke this method directly: it is an internal method for types - /// that adopt DatabasePersistable. + /// that adopt MutableDatabasePersistable. /// /// performExists() provides the default implementation for exists(). Types - /// that adopt DatabasePersistable can invoke performExists() in their - /// implementation of exists(). They should not provide their own + /// that adopt MutableDatabasePersistable can invoke performExists() in + /// their implementation of exists(). They should not provide their own /// implementation of performExists(). func performExists(db: Database) -> Bool { return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) @@ -278,6 +286,148 @@ public extension DatabasePersistable { } +// MARK: - DatabasePersistable + +/// Types that adopt DatabasePersistable can be inserted, updated, and deleted. +/// +/// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. +/// +/// Unlike MutableDatabasePersistable, the insert() and save() methods are not +/// mutating methods. +public protocol DatabasePersistable : MutableDatabasePersistable { + + /// Don't call this method directly: it is called upon successful insertion, + /// with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// + /// This method is optional: the default implementation does nothing. + /// + /// struct Person : DatabasePersistable { + /// var id: Int64? + /// var name: String? + /// + /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + /// self.id = rowID + /// } + /// } + /// + /// - parameter rowID: The inserted rowID. + /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. + func didInsertWithRowID(rowID: Int64, forColumn name: String?) + + /// Executes an INSERT statement. + /// + /// This method is guaranteed to have inserted a row in the database if it + /// returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of insert(). In their implementation, it is recommended + /// that they invoke the performInsert() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs. + func insert(db: Database) throws + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// If the receiver has a non-nil primary key and a matching row in the + /// database, this method performs an update. + /// + /// Otherwise, performs an insert. + /// + /// This method is guaranteed to have inserted or updated a row in the + /// database if it returns without error. + /// + /// This method has a default implementation, so your adopting types don't + /// have to implement it. Yet your types can provide their own + /// implementation of save(). In their implementation, it is recommended + /// that they invoke the performSave() method. + /// + /// - parameter db: A Database. + /// - throws: A DatabaseError whenever a SQLite error occurs, or errors + /// thrown by update(). + func save(db: Database) throws +} + +public extension DatabasePersistable { + + /// The default implementation does nothing. + func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + + } + + // MARK: - Immutable CRUD + + /// Executes an INSERT statement. + /// + /// The default implementation for insert() invokes performInsert(). + func insert(db: Database) throws { + try performInsert(db) + } + + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database. + /// + /// The default implementation for save() invokes performSave(). + func save(db: Database) throws { + try performSave(db) + } + + + // MARK: - Immutable CRUD Internals + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performInsert() provides the default implementation for insert(). Types + /// that adopt DatabasePersistable can invoke performInsert() in their + /// implementation of insert(). They should not provide their own + /// implementation of performInsert(). + func performInsert(db: Database) throws { + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + if case .Managed(let columnName) = dataMapper.primaryKey { + didInsertWithRowID(rowID, forColumn: columnName) + } else { + didInsertWithRowID(rowID, forColumn: nil) + } + } + } + + /// Don't invoke this method directly: it is an internal method for types + /// that adopt DatabasePersistable. + /// + /// performSave() provides the default implementation for save(). Types + /// that adopt DatabasePersistable can invoke performSave() in their + /// implementation of save(). They should not provide their own + /// implementation of performSave(). + /// + /// This default implementation forwards the job to `update` or `insert`. + func performSave(db: Database) throws { + // Make sure we call self.insert and self.update so that classes that + // override insert or save have opportunity to perform their custom job. + + if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil { + try insert(db) + return + } + + do { + try update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update another + // object which may be the one throwing this error. + try insert(db) + } + } + +} + // MARK: - DataMapper /// DataMapper takes care of DatabasePersistable CRUD @@ -287,7 +437,7 @@ final class DataMapper { let db: Database /// The persistable - let persistable: DatabasePersistable + let persistable: MutableDatabasePersistable /// DataMapper keeps a copy the persistable's storedDatabaseDictionary, so /// that this dictionary is built once whatever the database operation. @@ -359,7 +509,7 @@ final class DataMapper { // MARK: - Initializer - init(_ db: Database, _ persistable: DatabasePersistable) { + init(_ db: Database, _ persistable: MutableDatabasePersistable) { let databaseTableName = persistable.dynamicType.databaseTableName() // Fail early if database table does not exist. diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 543d223c0..ac4ad3fc0 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -271,8 +271,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - parameter db: A Database. /// - throws: A DatabaseError whenever a SQLite error occurs. public func insert(db: Database) throws { - var persistable = self as DatabasePersistable - try persistable.performInsert(db) + try performInsert(db) databaseEdited = false } @@ -309,8 +308,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// - throws: A DatabaseError whenever a SQLite error occurs, or errors /// thrown by update(). final public func save(db: Database) throws { - var persistable = self as DatabasePersistable - try persistable.performSave(db) + try performSave(db) } /// Executes a DELETE statement. From 21fc6938caf6ac83cda833a66d8f0f3ad4041f1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:05:13 +0100 Subject: [PATCH 25/67] MutableDatabasePersistable documentation --- CHANGELOG.md | 2 +- GRDB/Core/Protocols/DatabasePersistable.swift | 14 +++---- README.md | 40 ++++++++++++++----- 3 files changed, 36 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4245265..594a1bb50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes **New** -- The `DatabasePersistable` protocol grants any adopting type the CRUD methods that used to be reserved to Record subclasses. +- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the CRUD methods that used to be reserved to Record subclasses. - `Database.clearSchemaCache()` **Breaking Changes** diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 69918a024..69da5dc1f 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -302,14 +302,8 @@ public protocol DatabasePersistable : MutableDatabasePersistable { /// /// This method is optional: the default implementation does nothing. /// - /// struct Person : DatabasePersistable { - /// var id: Int64? - /// var name: String? - /// - /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { - /// self.id = rowID - /// } - /// } + /// If you need a mutating variant of this method, adopt the + /// MutableDatabasePersistable protocol instead. /// /// - parameter rowID: The inserted rowID. /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. @@ -320,6 +314,10 @@ public protocol DatabasePersistable : MutableDatabasePersistable { /// This method is guaranteed to have inserted a row in the database if it /// returns without error. /// + /// Upon successful insertion, the didInsertWithRowID(:forColumn:) method + /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY + /// column name. + /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of insert(). In their implementation, it is recommended diff --git a/README.md b/README.md index bc3886576..ad2eac87d 100644 --- a/README.md +++ b/README.md @@ -1479,16 +1479,20 @@ public protocol DatabasePersistable : DatabaseTableMapping { The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: ```swift -struct Person : DatabasePersistable { - let id: Int64? - let name: String? +// CREATE TABLE countries ( +// isoCode TEXT NOT NULL PRIMARY KEY, +// name TEXT NOT NULL +// ) +struct Country : DatabasePersistable { + let isoCode: String + let name: String static func databaseTableName() -> String { - return "persons" + return "countries" } var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "name": name] + return ["isoCode": isoCode, "name": name] } } ``` @@ -1503,14 +1507,28 @@ func delete(db: Database) throws -> Bool // DELETE func exists(db: Database) -> Bool // Whether a matching row exists ``` -Your type may store its rowID after a successful insertion: + +### Inserted Row IDs + +Your structs that represent a table with an INTEGER PRIMARY KEY will prefer adopting `MutableDatabasePersistable` instead of `DatabasePersistable`: they'll get the opportunity to store the inserted rowID upon successful insertion: ```swift -extension Person { - /// Optional method that is called upon successful insertion. - /// - /// - parameter rowID: The inserted rowID. - /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. +// CREATE TABLE persons ( +// id INTEGER PRIMARY KEY, +// name TEXT +// ) +struct Person : MutableDatabasePersistable { + let id: Int64? + let name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { self.id = rowID } From 7f6a14131dbb9126adf6197de788d7d7c6c92377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:12:29 +0100 Subject: [PATCH 26/67] MutableDatabasePersistable documentation --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index ad2eac87d..df97cde87 100644 --- a/README.md +++ b/README.md @@ -1542,6 +1542,24 @@ dbQueue.inDatabase { db in } ``` +`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion: + +```swift +protocol MutableDatabasePersistable { + // Insertion can mutate: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) + mutating func insert(db: Database) throws + mutating func save(db: Database) throws +} + +protocol DatabasePersistable : MutableDatabasePersistable { + // Insertion can not mutate: + func didInsertWithRowID(rowID: Int64, forColumn column: String?) + func insert(db: Database) throws + func save(db: Database) throws +} +``` + ### Customizing the CRUD methods From b67239ef3ea2e5064ea81e852b9487dc9ca870cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:14:08 +0100 Subject: [PATCH 27/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df97cde87..34673fb03 100644 --- a/README.md +++ b/README.md @@ -1563,7 +1563,7 @@ protocol DatabasePersistable : MutableDatabasePersistable { ### Customizing the CRUD methods -Your custom DatabasePersistable type may want to perform extra work when the CRUD methods are invoked. +Your custom type may want to perform extra work when the CRUD methods are invoked. For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. From 7782bcddacd7be89ec30f4564a08ff288c6db647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:17:25 +0100 Subject: [PATCH 28/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 34673fb03..be9d59cf0 100644 --- a/README.md +++ b/README.md @@ -1584,7 +1584,7 @@ struct Person : DatabasePersistable { > :point_up: **Note**: Those special methods are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. > -> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization. +> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. ## Record From 7fc282a2d5238ab5391ff7051aa4cd0654876e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:20:08 +0100 Subject: [PATCH 29/67] README.md: RecordError has been renamed PersistenceError. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index be9d59cf0..237912787 100644 --- a/README.md +++ b/README.md @@ -1894,7 +1894,7 @@ try dbQueue.inDatabase { db in - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. -- `update` and `reload` methods can also throw a RecordError of type RecordNotFound, should the update or reload fail because the record does not exist in the database. +- `update` and `reload` methods can also throw a PersistenceError of type NotFound, should the update or reload fail because the record does not exist in the database. When saving a record that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. From 6c2431912ef5ee55731655fcca962221c1267992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:22:03 +0100 Subject: [PATCH 30/67] DatabasePersistable documentation --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 237912787..85683beb3 100644 --- a/README.md +++ b/README.md @@ -1507,6 +1507,14 @@ func delete(db: Database) throws -> Bool // DELETE func exists(db: Database) -> Bool // Whether a matching row exists ``` +- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. + +- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. + + When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. + +- `delete` returns whether a database row was deleted or not. + ### Inserted Row IDs @@ -1894,7 +1902,7 @@ try dbQueue.inDatabase { db in - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. -- `update` and `reload` methods can also throw a PersistenceError of type NotFound, should the update or reload fail because the record does not exist in the database. +- `update` and `reload` methods can also throw a PersistenceError of type NotFound, should the update or reload fail because the record does not exist in the database. When saving a record that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. From c07d9cc8cb1678e239b490c539d359a7e39d1764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:30:46 +0100 Subject: [PATCH 31/67] README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 85683beb3..d5d0549e8 100644 --- a/README.md +++ b/README.md @@ -1550,7 +1550,7 @@ dbQueue.inDatabase { db in } ``` -`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion: +`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion. ```swift protocol MutableDatabasePersistable { @@ -1568,6 +1568,7 @@ protocol DatabasePersistable : MutableDatabasePersistable { } ``` +> :point_up: **Note**: Classes should prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). ### Customizing the CRUD methods From ecb7bfc78667d0f71b12ac8f62f9ac34506eb214 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:35:14 +0100 Subject: [PATCH 32/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d5d0549e8..206406f3a 100644 --- a/README.md +++ b/README.md @@ -1568,7 +1568,7 @@ protocol DatabasePersistable : MutableDatabasePersistable { } ``` -> :point_up: **Note**: Classes should prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). +> :point_up: **Note**: Classes should prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). ### Customizing the CRUD methods From be8608eb475e094ff4724626938273e364501424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:38:18 +0100 Subject: [PATCH 33/67] TODO.md --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 1d3497250..1cdb08f95 100644 --- a/TODO.md +++ b/TODO.md @@ -4,7 +4,7 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ -- [ ] Try to avoid the mandatory mutation of DatabasePersistable.insert() +- [ ] Write tests for classes that adopt DatabasePersistable and MutableDatabasePersistable. Check that a class that adopts DatabasePersistable can set its rowID. If not, fix it, or fix the documentation in README that reads "Classes should prefer adopting DatabasePersistable..." Not sure: From f0c78b02df929e3088d7765488b980093cf0f853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:39:47 +0100 Subject: [PATCH 34/67] TODO.md --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 1cdb08f95..0f79477db 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,5 @@ - [ ] #2: this commit may be how stephencelis fixed it: https://github.com/stephencelis/SQLite.swift/commit/8f64e357c3a6668c5f011c91ba33be3e8d4b88d0 - [ ] Study SQLCipher -- [ ] Study custom collations - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ From 164ad16328b91bc3314c817a077deb7edf88a4be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:41:51 +0100 Subject: [PATCH 35/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 206406f3a..a27fc3482 100644 --- a/README.md +++ b/README.md @@ -1550,7 +1550,7 @@ dbQueue.inDatabase { db in } ``` -`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion. +`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion: ```swift protocol MutableDatabasePersistable { From 2aa64bb2cdd3fcc4d1575cc0cacb1c65e1d8a3d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:48:18 +0100 Subject: [PATCH 36/67] README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a27fc3482..a7d83aee3 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,7 @@ You may prefer thinking of rows as dictionaries of `DatabaseValue`, an intermedi ```swift // Test if the column `date` is present: if let databaseValue = row["date"] { + // Pick the type you need: let dateString: String = databaseValue.value() // "2015-09-11 18:14:15.123" let date: NSDate = databaseValue.value() // NSDate From 2b8875d19dd4fcd417e7c4877ddcfd6d6c034987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 10 Dec 2015 22:54:49 +0100 Subject: [PATCH 37/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7d83aee3..29887f548 100644 --- a/README.md +++ b/README.md @@ -1080,7 +1080,7 @@ See [Configuration](GRDB/Core/Configuration.swift) type and [DatabaseQueue.inTra ## Custom SQL Functions -**SQLite let you define SQL functions.** +**SQLite lets you define SQL functions.** You can for example use the Unicode support of Swift strings, and go beyond the ASCII limitations of the built-in SQLite `upper()` function: From 44cdadabcaa55b7cb94d748beb43655ba58bee02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 06:18:01 +0100 Subject: [PATCH 38/67] TODO.md --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 0f79477db..4502b30dc 100644 --- a/TODO.md +++ b/TODO.md @@ -4,6 +4,7 @@ - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ - [ ] Write tests for classes that adopt DatabasePersistable and MutableDatabasePersistable. Check that a class that adopts DatabasePersistable can set its rowID. If not, fix it, or fix the documentation in README that reads "Classes should prefer adopting DatabasePersistable..." +- [ ] Now that DatabasePersistable is out, Record has this didInsertWithRowID(:forColumn:) which calls updateFromRow. When we document "The updateFromRow method MUST NOT assume the presence of particular columns. The Record class itself reserves the right to call updateFromRow with arbitrary columns", we are actually talking about didInsertWithRowID, which is now exposed. Users may be confused. Not sure: From c5913542f0f5536b5aee2d2b5d22a0ce88b20cd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:05:45 +0100 Subject: [PATCH 39/67] DatabasePersistable WIP --- .../DatabasePersistableTests.swift | 13 +++ .../MutableDatabasePersistableTests.swift | 4 +- GRDB/Core/Protocols/DatabasePersistable.swift | 14 +-- GRDB/Record/Record.swift | 8 +- README.md | 95 +++++++++++-------- 5 files changed, 81 insertions(+), 53 deletions(-) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index c0eb9757d..2b7c274f6 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -68,6 +68,19 @@ class DatabasePersistableTests: GRDBTestCase { } } + func testInsertPersistablePersonAsMutableDatabasePersistable() { + assertNoError { + try dbQueue.inDatabase { db in + var person: MutableDatabasePersistable = PersistablePerson(name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + func testInsertPersistableCountry() { assertNoError { try dbQueue.inDatabase { db in diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift index 39065ea25..adacdabd3 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -13,7 +13,7 @@ struct MutablePersistablePerson : MutableDatabasePersistable { return ["id": id, "name": name] } - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { self.id = rowID } } @@ -37,7 +37,7 @@ struct MutablePersistableCountry : MutableDatabasePersistable { return ["isoCode": isoCode, "name": name] } - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { self.rowID = rowID } } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index 69da5dc1f..3aac7d888 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -58,14 +58,14 @@ public protocol MutableDatabasePersistable : DatabaseTableMapping { /// var id: Int64? /// var name: String? /// - /// mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + /// mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { /// self.id = rowID /// } /// } /// /// - parameter rowID: The inserted rowID. - /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) // MARK: - CRUD @@ -153,7 +153,7 @@ public protocol MutableDatabasePersistable : DatabaseTableMapping { public extension MutableDatabasePersistable { /// The default implementation does nothing. - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { } @@ -306,8 +306,8 @@ public protocol DatabasePersistable : MutableDatabasePersistable { /// MutableDatabasePersistable protocol instead. /// /// - parameter rowID: The inserted rowID. - /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. - func didInsertWithRowID(rowID: Int64, forColumn name: String?) + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + func didInsertWithRowID(rowID: Int64, forColumn column: String?) /// Executes an INSERT statement. /// @@ -352,7 +352,7 @@ public protocol DatabasePersistable : MutableDatabasePersistable { public extension DatabasePersistable { /// The default implementation does nothing. - func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index ac4ad3fc0..50ded18db 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -156,10 +156,10 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable /// INTEGER PRIMARY KEY. /// /// - parameter rowID: The inserted rowID. - /// - parameter name: The name of the eventual INTEGER PRIMARY KEY column. - public func didInsertWithRowID(rowID: Int64, forColumn name: String?) { - if let name = name { - updateFromRow(Row(dictionary: [name: rowID])) + /// - parameter column: The name of the eventual INTEGER PRIMARY KEY column. + public func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + if let column = column { + updateFromRow(Row(dictionary: [column: rowID])) } } diff --git a/README.md b/README.md index 29887f548..2729cf04a 100644 --- a/README.md +++ b/README.md @@ -1463,21 +1463,35 @@ Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) ## DatabasePersistable Protocol -**The `DatabasePersistable` protocol grants adopting types with CRUD methods.** - -It has two mandatory methods: +**GRDB provides two protocols that let adopting types storing themselves in the database.**: ```swift -public protocol DatabasePersistable : DatabaseTableMapping { +public protocol MutableDatabasePersistable : DatabaseTableMapping { /// The name of the database table (from DatabaseTableMapping) static func databaseTableName() -> String /// Returns the values that should be stored in the database. var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } + + /// Optional method that lets your adopting type store its rowID upon + /// successful insertion: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} + +public protocol DatabasePersistable : MutableDatabasePersistable { + /// Non-mutating version of didInsertWithRowID(:forColumn:) + func didInsertWithRowID(rowID: Int64, forColumn column: String?) } ``` -The `storedDatabaseDictionary` dictionary keys are column names, and its values can be any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: +That's one more protocol that one could expect, and `MutableDatabasePersistable` may sound intimidating. + +Yet, here is the rule: + +- If your type is a struct that maps a table with an INTEGER PRIMARY KEY, choose `MutableDatabasePersistable` so that you can store the inserted id on successful insertion. +- Otherwise, stick with `DatabasePersistable`. + +For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion. On the other side, the Person struct is interested in its rowID, and mutates itself on insertion: ```swift // CREATE TABLE countries ( @@ -1496,32 +1510,11 @@ struct Country : DatabasePersistable { return ["isoCode": isoCode, "name": name] } } -``` -Adopting types are granted with the CRUD toolkit: +// Declare the country as `let`, since its insertion does not mutate it: +let country = Country(isoCode: "FR", name: "France") +try country.insert(db) -```swift -func insert(db: Database) throws // INSERT -func update(db: Database) throws // UPDATE -func save(db: Database) throws // inserts or updates -func delete(db: Database) throws -> Bool // DELETE -func exists(db: Database) -> Bool // Whether a matching row exists -``` - -- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. - -- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. - - When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. - -- `delete` returns whether a database row was deleted or not. - - -### Inserted Row IDs - -Your structs that represent a table with an INTEGER PRIMARY KEY will prefer adopting `MutableDatabasePersistable` instead of `DatabasePersistable`: they'll get the opportunity to store the inserted rowID upon successful insertion: - -```swift // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // name TEXT @@ -1538,20 +1531,43 @@ struct Person : MutableDatabasePersistable { return ["id": id, "name": name] } - mutating func didInsertWithRowID(rowID: Int64, forColumn name: String?) { + // Update self.id upon successful insertion: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { self.id = rowID } } -dbQueue.inDatabase { db in - var person = Person(id: nil, name: "Arthur") - person.id // nil - try person.save(db) - person.id // some value -} +// Declare the person as `var`, since its insertion mutates it: +var person = Person(id: nil, name: "Arthur") +person.id // nil +try person.insert(db) +person.id // some value ``` -`DatabasePersistable` and `MutableDatabasePersistable` are identical, except for the three methods that are involved in insertion: +> :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). + + +### Persistence Methods + +Types that adopt DatabasePersistable or MutableDatabasePersistable are given default implementations for methods that insert, update, and delete: + +```swift +try object.insert(db) // INSERT +try object.update(db) // UPDATE +try object.save(db) // Inserts or updates +try object.delete(db) // DELETE +object.exists(db) // Bool +``` + +- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. + +- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. + + When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. + +- `delete` returns whether a database row was deleted or not. + +The differences between `DatabasePersistable` and `MutableDatabasePersistable` only lie in insertion-related methods: ```swift protocol MutableDatabasePersistable { @@ -1569,11 +1585,10 @@ protocol DatabasePersistable : MutableDatabasePersistable { } ``` -> :point_up: **Note**: Classes should prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). -### Customizing the CRUD methods +### Customizing the Persistence Methods -Your custom type may want to perform extra work when the CRUD methods are invoked. +Your custom type may want to perform extra work when the persistence methods are invoked. For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. From 8891630f6952a0364666c94766e7c2e9359555d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:27:23 +0100 Subject: [PATCH 40/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2729cf04a..c6d6afb0e 100644 --- a/README.md +++ b/README.md @@ -1595,7 +1595,7 @@ For example, it may want to have its UUID automatically set before inserting. Or The protocol exposes *special methods* for this exact purpose: `performInsert`, `performUpdate`, `performSave`, `performDelete`, and `performExists`. ```swift -struct Person : DatabasePersistable { +struct Person : MutableDatabasePersistable { var uuid: String? mutating func insert(db: Database) throws { From e0a1691621fa5649420571f237c59efa6f5fca5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:44:24 +0100 Subject: [PATCH 41/67] DatabasePersistable tests WIP --- .../DatabasePersistableTests.swift | 292 +++++++++++++++++- .../MutableDatabasePersistableTests.swift | 20 ++ 2 files changed, 306 insertions(+), 6 deletions(-) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index 2b7c274f6..3b0f8993d 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -17,11 +17,24 @@ struct PersistableCountry : DatabasePersistable { var isoCode: String var name: String - init(isoCode: String, name: String) { - self.isoCode = isoCode - self.name = name + static func databaseTableName() -> String { + return "countries" } + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } +} + +struct PersistableCustomizedCountry : DatabasePersistable { + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + static func databaseTableName() -> String { return "countries" } @@ -29,6 +42,31 @@ struct PersistableCountry : DatabasePersistable { var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { return ["isoCode": isoCode, "name": name] } + + func insert(db: Database) throws { + willInsert() + try performInsert(db) + } + + func update(db: Database) throws { + willUpdate() + try performUpdate(db) + } + + func save(db: Database) throws { + willSave() + try performSave(db) + } + + func delete(db: Database) throws { + willDelete() + try performDelete(db) + } + + func exists(db: Database) -> Bool { + willExists() + return performExists(db) + } } class DatabasePersistableTests: GRDBTestCase { @@ -68,11 +106,11 @@ class DatabasePersistableTests: GRDBTestCase { } } - func testInsertPersistablePersonAsMutableDatabasePersistable() { + func testSavePersistablePerson() { assertNoError { try dbQueue.inDatabase { db in - var person: MutableDatabasePersistable = PersistablePerson(name: "Arthur") - try person.insert(db) + let person = PersistablePerson(name: "Arthur") + try person.save(db) let rows = Row.fetchAll(db, "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) @@ -139,6 +177,16 @@ class DatabasePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") } } } @@ -174,4 +222,236 @@ class DatabasePersistableTests: GRDBTestCase { } } } + + func testInsertPersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdatePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSavePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(db, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testDeletePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + try country1.delete(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsPersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + XCTAssertTrue(country.exists(db)) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } + } } diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift index adacdabd3..109344bc1 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -124,6 +124,16 @@ class MutableDatabasePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + + try person1.delete(db) + try person1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") } } } @@ -218,6 +228,16 @@ class MutableDatabasePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") } } } From e870eceaca0a795bea2a1e9db5b7495c7ee3bcc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:52:31 +0100 Subject: [PATCH 42/67] DatabasePersistable tests WIP --- .../DatabasePersistableTests.swift | 2 +- .../MutableDatabasePersistableTests.swift | 306 +++++++++++++++++- 2 files changed, 295 insertions(+), 13 deletions(-) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index 3b0f8993d..c35b70773 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -435,8 +435,8 @@ class DatabasePersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country.insert(db) - XCTAssertTrue(country.exists(db)) + XCTAssertTrue(country.exists(db)) XCTAssertEqual(insertCount, 1) XCTAssertEqual(updateCount, 0) XCTAssertEqual(saveCount, 0) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift index 109344bc1..493c00f99 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -23,12 +23,29 @@ struct MutablePersistableCountry : MutableDatabasePersistable { var isoCode: String var name: String - init(isoCode: String, name: String) { - self.rowID = nil - self.isoCode = isoCode - self.name = name + static func databaseTableName() -> String { + return "countries" } + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } +} + +struct MutablePersistableCustomizedCountry : MutableDatabasePersistable { + var rowID: Int64? + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + static func databaseTableName() -> String { return "countries" } @@ -40,6 +57,31 @@ struct MutablePersistableCountry : MutableDatabasePersistable { mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { self.rowID = rowID } + + mutating func insert(db: Database) throws { + willInsert() + try performInsert(db) + } + + func update(db: Database) throws { + willUpdate() + try performUpdate(db) + } + + mutating func save(db: Database) throws { + willSave() + try performSave(db) + } + + func delete(db: Database) throws { + willDelete() + try performDelete(db) + } + + func exists(db: Database) -> Bool { + willExists() + return performExists(db) + } } class MutableDatabasePersistableTests: GRDBTestCase { @@ -173,7 +215,7 @@ class MutableDatabasePersistableTests: GRDBTestCase { func testInsertMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(isoCode: "FR", name: "France") + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -187,9 +229,9 @@ class MutableDatabasePersistableTests: GRDBTestCase { func testUpdateMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -208,7 +250,7 @@ class MutableDatabasePersistableTests: GRDBTestCase { func testSaveMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") try country1.save(db) var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -216,7 +258,7 @@ class MutableDatabasePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) XCTAssertEqual(rows[0].value(named: "name") as String, "France") - var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -245,9 +287,9 @@ class MutableDatabasePersistableTests: GRDBTestCase { func testDeleteMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(isoCode: "FR", name: "France") + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(isoCode: "US", name: "United States") + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) try country1.delete(db) @@ -263,7 +305,7 @@ class MutableDatabasePersistableTests: GRDBTestCase { func testExistsMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(isoCode: "FR", name: "France") + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(country.exists(db)) @@ -273,4 +315,244 @@ class MutableDatabasePersistableTests: GRDBTestCase { } } } + + func testInsertMutablePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + } + + func testUpdateMutablePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + + func testSaveMutablePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(db, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(db) + + country1.name = "France Métropolitaine" + try country1.save(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(db) + try country1.save(db) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + } + + func testDeleteMutablePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + try country1.delete(db) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + } + + func testExistsMutablePersistableCustomizedCountry() { + assertNoError { + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(db) + + XCTAssertTrue(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(db) + + XCTAssertFalse(country.exists(db)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } + } } From 50057ec289a406898ae27f7760f14e8b57aba0ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:58:11 +0100 Subject: [PATCH 43/67] DatabasePersistable tests WIP --- .../DatabasePersistableTests.swift | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index c35b70773..9dee81c7a 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -13,6 +13,28 @@ struct PersistablePerson : DatabasePersistable { } } +class PersistablePersonClass : DatabasePersistable { + var id: Int64? + var name: String? + + init(id: Int64?, name: String?) { + self.id = id + self.name = name + } + + static func databaseTableName() -> String { + return "persons" + } + + var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + struct PersistableCountry : DatabasePersistable { var isoCode: String var name: String @@ -119,6 +141,110 @@ class DatabasePersistableTests: GRDBTestCase { } } + func testInsertPersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePersonClass(id: nil, name: "Arthur") + try person.insert(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + } + + func testUpdatePersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.insert(db) + + person1.name = "Craig" + try person1.update(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testSavePersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.save(db) + + var rows = Row.fetchAll(db, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.save(db) + + person1.name = "Craig" + try person1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + + try person1.delete(db) + try person1.save(db) + + rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + + func testDeletePersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur") + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara") + try person2.insert(db) + + try person1.delete(db) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + } + + func testExistsPersistablePersonClass() { + assertNoError { + try dbQueue.inDatabase { db in + let person = PersistablePersonClass(id: nil, name: "Arthur") + try person.insert(db) + XCTAssertTrue(person.exists(db)) + + try person.delete(db) + + XCTAssertFalse(person.exists(db)) + } + } + } + func testInsertPersistableCountry() { assertNoError { try dbQueue.inDatabase { db in From 99fb649ba711a5e71f5a9a9704dc7211453bf862 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 07:58:51 +0100 Subject: [PATCH 44/67] TODO.md --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 4502b30dc..05672ef90 100644 --- a/TODO.md +++ b/TODO.md @@ -3,7 +3,6 @@ - [ ] `IN (?)` sql snippet, with an array argument. - [ ] Write sample code around NSFetchedResultsController: fetch and output a list of TableView sections & row differences. - [ ] Compare DatabaseCoder with http://mjtsai.com/blog/2015/11/08/the-java-deserialization-bug-and-nssecurecoding/ -- [ ] Write tests for classes that adopt DatabasePersistable and MutableDatabasePersistable. Check that a class that adopts DatabasePersistable can set its rowID. If not, fix it, or fix the documentation in README that reads "Classes should prefer adopting DatabasePersistable..." - [ ] Now that DatabasePersistable is out, Record has this didInsertWithRowID(:forColumn:) which calls updateFromRow. When we document "The updateFromRow method MUST NOT assume the presence of particular columns. The Record class itself reserves the right to call updateFromRow with arbitrary columns", we are actually talking about didInsertWithRowID, which is now exposed. Users may be confused. Not sure: From 430c239171f8401a7d22b59cf55304d8682649f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:12:41 +0100 Subject: [PATCH 45/67] README.md --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/README.md b/README.md index c6d6afb0e..1888fb2f2 100644 --- a/README.md +++ b/README.md @@ -452,6 +452,9 @@ if let databaseValue = row["date"] { print("NSData: \(data)") } } + +// Nil if the column is not present: +let date: NSDate = row["date"]?.value() ``` Iterate all the tuples (columnName, databaseValue) in a row, from left to right: @@ -1378,6 +1381,37 @@ PointOfInterest(dictionary: [ "title": "Rome"]) ``` +Your RowConvertible type can accept rows that do not always contain the same columns: + +For example: + +```swift +struct Person : RowConvertible { + let id: Int64? + let name: String + let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() + + init(row: Row) { + id = row.value(named: "id") + name = row.value(named: "name") + + // bookCount may not always be present: + bookCount = row["bookCount"]?.value() + } + + // The returned persons have a value in their bookCount property: + static func fetchAllWithBookCount(db: Database) -> [Person] { + return fetchAll(db, + "SELECT persons.*, COUNT(books.id) AS bookCount " + + "FROM persons " + + "LEFT JOIN books ON books.ownerId = persons.id " + + "GROUP BY persons.id") + } +} +``` + +See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]` expression. + See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. From 6be37b9dc397c72d50de5418a263d8198118dfd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:13:55 +0100 Subject: [PATCH 46/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1888fb2f2..71ca388d8 100644 --- a/README.md +++ b/README.md @@ -1410,7 +1410,7 @@ struct Person : RowConvertible { } ``` -See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]` expression. +See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]?.value()` expression. See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. From b0e9011372964ab15834f1ad3ac5915f956c2faa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:16:34 +0100 Subject: [PATCH 47/67] README.md --- README.md | 65 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 71ca388d8..2e3761241 100644 --- a/README.md +++ b/README.md @@ -1381,37 +1381,6 @@ PointOfInterest(dictionary: [ "title": "Rome"]) ``` -Your RowConvertible type can accept rows that do not always contain the same columns: - -For example: - -```swift -struct Person : RowConvertible { - let id: Int64? - let name: String - let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() - - init(row: Row) { - id = row.value(named: "id") - name = row.value(named: "name") - - // bookCount may not always be present: - bookCount = row["bookCount"]?.value() - } - - // The returned persons have a value in their bookCount property: - static func fetchAllWithBookCount(db: Database) -> [Person] { - return fetchAll(db, - "SELECT persons.*, COUNT(books.id) AS bookCount " + - "FROM persons " + - "LEFT JOIN books ON books.ownerId = persons.id " + - "GROUP BY persons.id") - } -} -``` - -See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]?.value()` expression. - See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. @@ -1495,6 +1464,40 @@ Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) ``` +### Optional Columns + +**Your RowConvertible type can accept rows that do not always contain the same columns.** + +This allows you to load only a subset of a table columns, or to load extra columns joined from other tables. For example: + +```swift +struct Person : RowConvertible { + let id: Int64? + let name: String + let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() + + init(row: Row) { + id = row.value(named: "id") + name = row.value(named: "name") + + // bookCount may not always be present: + bookCount = row["bookCount"]?.value() + } + + // The returned persons have a value in their bookCount property: + static func fetchAllWithBookCount(db: Database) -> [Person] { + return fetchAll(db, + "SELECT persons.*, COUNT(books.id) AS bookCount " + + "FROM persons " + + "LEFT JOIN books ON books.ownerId = persons.id " + + "GROUP BY persons.id") + } +} +``` + +See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the `row["bookCount"]?.value()` expression. + + ## DatabasePersistable Protocol **GRDB provides two protocols that let adopting types storing themselves in the database.**: From f5b7a05e282a55259a20152af159d9c41a87ce69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:18:04 +0100 Subject: [PATCH 48/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e3761241..00e62e346 100644 --- a/README.md +++ b/README.md @@ -1500,7 +1500,7 @@ See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the ## DatabasePersistable Protocol -**GRDB provides two protocols that let adopting types storing themselves in the database.**: +**GRDB provides two protocols that let adopting types store themselves in the database.**: ```swift public protocol MutableDatabasePersistable : DatabaseTableMapping { From a10a504558cd02cc9c3a349fff7f36905f816090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:18:23 +0100 Subject: [PATCH 49/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 00e62e346..f808702a2 100644 --- a/README.md +++ b/README.md @@ -1500,7 +1500,7 @@ See [Rows as Dictionaries](#rows-as-dictionaries) for more information about the ## DatabasePersistable Protocol -**GRDB provides two protocols that let adopting types store themselves in the database.**: +**GRDB provides two protocols that let adopting types store themselves in the database:** ```swift public protocol MutableDatabasePersistable : DatabaseTableMapping { From 372f69835772d38c703bccbe456fe92272eb2a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:20:03 +0100 Subject: [PATCH 50/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f808702a2..96d9498d1 100644 --- a/README.md +++ b/README.md @@ -1525,7 +1525,7 @@ That's one more protocol that one could expect, and `MutableDatabasePersistable` Yet, here is the rule: -- If your type is a struct that maps a table with an INTEGER PRIMARY KEY, choose `MutableDatabasePersistable` so that you can store the inserted id on successful insertion. +- If your type is a struct that mutates on insertion, choose `MutableDatabasePersistable`. For example, if your table has an INTEGER PRIMARY KEY, you want to store the inserted id on successful insertion. - Otherwise, stick with `DatabasePersistable`. For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion. On the other side, the Person struct is interested in its rowID, and mutates itself on insertion: From 7bea6d54c92ce5ac5af2770d9b528ae1d21aeae9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:23:43 +0100 Subject: [PATCH 51/67] README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 96d9498d1..a092cf750 100644 --- a/README.md +++ b/README.md @@ -1680,6 +1680,8 @@ try dbQueue.inDatabase { db in } ``` +It builds on top of the [RowConvertible](#rowconvertible-protocol) and [DatabasePersistable](#databasepersistable-protocol) protocols. + **Record is not a smart class.** It is no replacement for Core Data’s NSManagedObject, [Realm](https://realm.io)’s Object, or for an Active Record pattern. It does not provide any uniquing, automatic refresh, or synthesized properties. It has no knowledge of external references and table relationships, and will not generate JOIN queries for you. Yet, it does a few things well: From 8422ff4e3174bc86e5e0c134bd4894b5c00a31aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:25:07 +0100 Subject: [PATCH 52/67] README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a092cf750..0d624af2c 100644 --- a/README.md +++ b/README.md @@ -1477,6 +1477,7 @@ struct Person : RowConvertible { let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() init(row: Row) { + // mandatory columns: id = row.value(named: "id") name = row.value(named: "name") From 99a7ac1e13a6a781294a2580a64d68f7c9d96b50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:37:52 +0100 Subject: [PATCH 53/67] "CRUD" -> "persistence" --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 0d624af2c..5b9019f49 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Features -------- - **A low-level [SQLite API](#sqlite-api)** that leverages the Swift 2 standard library. -- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations. +- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic persistence operations. - **[Swift type freedom](#values)**: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types. - **[Database migrations](#migrations)** - **[Database changes observation hooks](#database-changes-observation)** @@ -70,8 +70,8 @@ Documentation - **Database protocols, and Record** - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. - - [Record](#record): The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. + - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. - **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. @@ -1244,8 +1244,8 @@ On top of the SQLite API described above, GRDB provides a toolkit for applicatio - **[Migrations](#migrations)**: Transform your database as your application evolves. - **Database protocols, and Record** - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with CRUD methods. - - [Record](#record): The class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. + - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. + - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. - **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. @@ -1381,7 +1381,7 @@ PointOfInterest(dictionary: [ "title": "Rome"]) ``` -See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like CRUD operations, and changes tracking. +See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like persistence methods, and changes tracking. ### Fetching by Key @@ -1663,7 +1663,7 @@ struct Person : MutableDatabasePersistable { ### Record Overview -**Record** is a class that wraps a table row or the result of any query, provides CRUD operations, and changes tracking. It is designed to be subclassed. +**Record** is a class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. It is designed to be subclassed. ```swift // Define Record subclass @@ -1701,7 +1701,7 @@ Yet, it does a few things well: (person.name, person.citizenshipsCount) ``` -- **It provides the classic CRUD operations.** All primary keys are supported (auto-incremented INTEGER PRIMARY KEY, single column, multiple columns). +- **It provides the classic CRUD persistence methods.** All primary keys are supported (auto-incremented INTEGER PRIMARY KEY, single column, multiple columns). ```swift let person = Person(...) @@ -1757,7 +1757,7 @@ class Person { var databaseEdited: Bool var databaseChanges: [String: (old: DatabaseValue?, new: DatabaseValue)] - // CRUD + // Persistence func insert(db: Database) throws func update(db: Database) throws func save(db: Database) throws // inserts or updates From d7c62c3022b348a654c9fb6f299285c3d09fb615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 08:47:58 +0100 Subject: [PATCH 54/67] "CRUD" -> "persistence" --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 594a1bb50..c6b04b590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes **New** -- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the CRUD methods that used to be reserved to Record subclasses. +- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the persistence methods that used to be reserved to subclasses of `Record`. - `Database.clearSchemaCache()` **Breaking Changes** From f6371ac1f6f15f4c8721cd61b13976a12ab41662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 09:08:42 +0100 Subject: [PATCH 55/67] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5b9019f49..5453f3807 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ Why GRDB, when we already have the excellent [ccgus/fmdb](https://github.com/ccg **GRDB owes a lot to FMDB.** You will use the familiar and safe [database queues](#database-queues) you are used to. Yet you may appreciate that [database errors](#error-handling) are handled in the Swift way, and that [fetching data](#fetch-queries) is somewhat easier. -**Your SQL skills are rewarded here.** You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. Without losing type safety and all niceties you expect from a real Swift library. +**Your SQL skills are rewarded here.** Complex queries are never treated differently from the simple ones. You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. And you are granted with type safety and all the niceties you expect from a real Swift library. -**GRDB provides protocols** that grant database powers to your custom types, and reduce the database noise in your application code. +**GRDB provides protocols and a Record class** that help isolating database management code into database layer types, and avoid cluterring the rest of your application. **GRDB is fast**. As fast, when not faster, than FMDB and SQLite.swift. From 1f0fd28baac3244e127b474239473fa3fb534b68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 09:10:03 +0100 Subject: [PATCH 56/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5453f3807..24a141788 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Features -------- - **A low-level [SQLite API](#sqlite-api)** that leverages the Swift 2 standard library. -- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, and provides basic persistence operations. +- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, provides persistence operations, and changes tracking. - **[Swift type freedom](#values)**: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types. - **[Database migrations](#migrations)** - **[Database changes observation hooks](#database-changes-observation)** From 0658f454b3b787a30585f1ea26595799152d4c48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:15:05 +0100 Subject: [PATCH 57/67] README.md --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 24a141788..e4f52bbbe 100644 --- a/README.md +++ b/README.md @@ -1643,6 +1643,26 @@ struct Person : MutableDatabasePersistable { try performInsert(db) } } + +struct Link : DatabasePersistable { + var url: NSURL + + func insert(db: Database) throws { + try validate() + try performInsert(db) + } + + func update(db: Database) throws { + try validate() + try performUpdate(db) + } + + func validate() throws { + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } +} ``` > :point_up: **Note**: Those special methods are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. From ca98412dec4055b30b31a0e7fac32374c3a41466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:23:28 +0100 Subject: [PATCH 58/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e4f52bbbe..b3bc1da02 100644 --- a/README.md +++ b/README.md @@ -1665,7 +1665,7 @@ struct Link : DatabasePersistable { } ``` -> :point_up: **Note**: Those special methods are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. +> :point_up: **Note**: The special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. > > :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. From 2f66dbfe8adf7a7da3af235ff2b94652d30f916c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:27:05 +0100 Subject: [PATCH 59/67] README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b3bc1da02..895e7b8c7 100644 --- a/README.md +++ b/README.md @@ -1582,6 +1582,8 @@ try person.insert(db) person.id // some value ``` +The `storedDatabaseDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See Values for more information. + > :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). From 308118951729e87b4725f314a37eb4dd6a1173cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:32:00 +0100 Subject: [PATCH 60/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 895e7b8c7..8976ee857 100644 --- a/README.md +++ b/README.md @@ -1582,7 +1582,7 @@ try person.insert(db) person.id // some value ``` -The `storedDatabaseDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See Values for more information. +The `storedDatabaseDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. > :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). From 1789b38dec946c8a267a1e369c6a64dbd4d4b30c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:32:57 +0100 Subject: [PATCH 61/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8976ee857..efee21e75 100644 --- a/README.md +++ b/README.md @@ -1517,7 +1517,7 @@ public protocol MutableDatabasePersistable : DatabaseTableMapping { } public protocol DatabasePersistable : MutableDatabasePersistable { - /// Non-mutating version of didInsertWithRowID(:forColumn:) + /// Non-mutating version of the optional didInsertWithRowID(:forColumn:) func didInsertWithRowID(rowID: Int64, forColumn column: String?) } ``` From ed80d02ee04c4c9425c0de4b640316e0bd983e0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 10:47:30 +0100 Subject: [PATCH 62/67] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index efee21e75..68d110481 100644 --- a/README.md +++ b/README.md @@ -1584,7 +1584,7 @@ person.id // some value The `storedDatabaseDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. -> :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate themselves in `didInsertWithRowID(:forColumn:)`. They'll avoid strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). +> :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate on insertion. This will prevent strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). ### Persistence Methods From de4a86ca504a0deebb379bd98262b590c76d620f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 13:03:02 +0100 Subject: [PATCH 63/67] DatabasePersistable tests WIP --- .../DatabasePersistableTests.swift | 12 ++++++++++++ .../MutableDatabasePersistableTests.swift | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift index 9dee81c7a..63965adf2 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift @@ -115,6 +115,9 @@ class DatabasePersistableTests: GRDBTestCase { } } + + // MARK: - PersistablePerson + func testInsertPersistablePerson() { assertNoError { try dbQueue.inDatabase { db in @@ -141,6 +144,9 @@ class DatabasePersistableTests: GRDBTestCase { } } + + // MARK: - PersistablePersonClass + func testInsertPersistablePersonClass() { assertNoError { try dbQueue.inDatabase { db in @@ -245,6 +251,9 @@ class DatabasePersistableTests: GRDBTestCase { } } + + // MARK: - PersistableCountry + func testInsertPersistableCountry() { assertNoError { try dbQueue.inDatabase { db in @@ -349,6 +358,9 @@ class DatabasePersistableTests: GRDBTestCase { } } + + // MARK: - PersistableCustomizedCountry + func testInsertPersistableCustomizedCountry() { assertNoError { try dbQueue.inDatabase { db in diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift index 493c00f99..5c30b2680 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift @@ -108,6 +108,9 @@ class MutableDatabasePersistableTests: GRDBTestCase { } } + + // MARK: - MutablePersistablePerson + func testInsertMutablePersistablePerson() { assertNoError { try dbQueue.inDatabase { db in @@ -212,6 +215,9 @@ class MutableDatabasePersistableTests: GRDBTestCase { } } + + // MARK: - MutablePersistableCountry + func testInsertMutablePersistableCountry() { assertNoError { try dbQueue.inDatabase { db in @@ -316,6 +322,9 @@ class MutableDatabasePersistableTests: GRDBTestCase { } } + + // MARK: - MutablePersistableCustomizedCountry + func testInsertMutablePersistableCustomizedCountry() { assertNoError { try dbQueue.inDatabase { db in From 1f3f2d04eb2cf5b6767fe815cac83b5b808189ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 13:05:10 +0100 Subject: [PATCH 64/67] Instead of disabling schema cache throughout the migrations, clear the schema cache after each migration. --- GRDB/Core/Database.swift | 23 ++--------------------- GRDB/Migrations/DatabaseMigrator.swift | 11 ++++++----- 2 files changed, 8 insertions(+), 26 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 63e0e0897..37ae1e361 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -461,22 +461,6 @@ public final class Database { assertValidQueue() columnInfosCache = [:] } - - /// When false, the schema cache is disabled. - private var schemaCacheIsEnabled: Bool - - func withDisabledSchemaCache(@noescape block:() throws -> ()) rethrows { - assertValidQueue() - - var schemaCacheWasEnabled = schemaCacheIsEnabled - defer { - schemaCacheIsEnabled = schemaCacheWasEnabled - } - - schemaCacheIsEnabled = false - clearSchemaCache() - try block() - } /// The last error message var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } @@ -599,15 +583,13 @@ public final class Database { // Cache for columnInfosForTable(named:) private var columnInfosCache: [String: [ColumnInfo]] = [:] private func columnInfosForTable(named tableName: String) -> [ColumnInfo] { - if let columnInfos = columnInfosCache[tableName] where schemaCacheIsEnabled { + if let columnInfos = columnInfosCache[tableName] { return columnInfos } else { // This pragma is case-insensitive: PRAGMA table_info("PERSONS") and // PRAGMA table_info("persons") yield the same results. let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - if schemaCacheIsEnabled { - columnInfosCache[tableName] = columnInfos - } + columnInfosCache[tableName] = columnInfos return columnInfos } } @@ -637,7 +619,6 @@ public final class Database { init(path: String, configuration: Configuration) throws { self.configuration = configuration - self.schemaCacheIsEnabled = true // See https://www.sqlite.org/c3ref/open.html var sqliteConnection = SQLiteConnection() diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 73324986a..a4f9fb980 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -85,10 +85,8 @@ public struct DatabaseMigrator { /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(dbQueue: DatabaseQueue) throws { try dbQueue.inDatabase { db in - try db.withDisabledSchemaCache { - try self.setupMigrations(db) - try self.runMigrations(db) - } + try self.setupMigrations(db) + try self.runMigrations(db) } } @@ -112,6 +110,9 @@ public struct DatabaseMigrator { let appliedMigrationIdentifiers = String.fetchAll(db, "SELECT identifier FROM grdb_migrations") try migrations .filter { !appliedMigrationIdentifiers.contains($0.identifier) } - .forEach { try $0.run(db) } + .forEach { + try $0.run(db) + db.clearSchemaCache() + } } } \ No newline at end of file From 6555881a79ab59d52bd922f61b3192d9e6726555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 13:08:06 +0100 Subject: [PATCH 65/67] Drop documentation for NSCoding support --- README.md | 34 +--------------------------------- 1 file changed, 1 insertion(+), 33 deletions(-) diff --git a/README.md b/README.md index 68d110481..c8c0fdfbb 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,6 @@ Documentation - [Values](#values) - [NSData](#nsdata-and-memory-savings) - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) - - [NSCoding](#nscoding) - [Swift enums](#swift-enums) - [Custom Value Types](#custom-value-types) - [Transactions](#transactions) @@ -542,7 +541,7 @@ GRDB ships with built-in support for the following value types: - **Swift Standard Library**: Bool, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). -- **Foundation**: [NSCoding](#nscoding), [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. +- **Foundation**: [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. - **CoreGraphics**: CGFloat. @@ -748,37 +747,6 @@ DatabaseDateComponents.fetchOne(db, "SELECT ...") // DatabaseDateComponents? See [Column Values](#column-values) and [Value Queries](#value-queries) for more information. -### NSCoding - -NSCoding is indirectly supported, through the **DatabaseCoder** helper type. - -DatabaseCoder reads and writes objects that adopt NSCoding into Blob columns. - -For example, store NSArray into the database: - -```swift -let ints = [1, 2, 3] -try db.execute( - "INSERT INTO ... (ints, ...) VALUES (?, ...)", - arguments: [DatabaseCoder(ints), ...]) -``` - -Extract NSArray from the database: - -```swift -let row = Row.fetchOne(db, "SELECT ints ...")! -let coder = row.value(named: "ints") as DatabaseCoder // DatabaseCoder -let array = coder.object as! NSArray // NSArray -let ints = array.map { $0 as! Int } // [Int] - -DatabaseCoder.fetch(db, "SELECT ...") // DatabaseSequence -DatabaseCoder.fetchAll(db, "SELECT ...") // [DatabaseCoder] -DatabaseCoder.fetchOne(db, "SELECT ...") // DatabaseCoder? -``` - -See [Column Values](#column-values) and [Value Queries](#value-queries) for more information. - - ### Swift Enums **Swift enums** get full support from GRDB.swift as long as their raw values are Int, Int32, Int64 or String. From 833a5af74f5ea9b3e2268d011b5d27dde78fd136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 13:24:01 +0100 Subject: [PATCH 66/67] v0.33.0 --- CHANGELOG.md | 4 +++- GRDB.swift.podspec | 2 +- GRDB/Info.plist | 2 +- README.md | 10 +++++----- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6b04b590..c2f396036 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,9 @@ Release Notes ============= -## Next Release +## 0.33.0 + +Released December 11, 2015 **New** diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index d6b16e5be..f0d528d9c 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.32.2' + s.version = '0.33.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Versatile SQLite toolkit for Swift.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/GRDB/Info.plist b/GRDB/Info.plist index 2e0287431..1cb93ef4a 100644 --- a/GRDB/Info.plist +++ b/GRDB/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.32.2 + 0.33.0 CFBundleSignature ???? CFBundleVersion diff --git a/README.md b/README.md index c8c0fdfbb..334aba588 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2, from the It ships with a low-level database API, plus application-level tools. -**December 3, 2015: GRDB.swift 0.32.2 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**December 11, 2015: GRDB.swift 0.33.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ @@ -39,7 +39,7 @@ Features Documentation ============= -- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.32.2/index.html)** (on cocoadocs.org) +- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.33.0/index.html)** (on cocoadocs.org) - **[Installation](#installation)** @@ -95,7 +95,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '0.32.2' +pod 'GRDB.swift', '0.33.0' ``` @@ -106,7 +106,7 @@ pod 'GRDB.swift', '0.32.2' To use GRDB.swift with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" == 0.32.2 +github "groue/GRDB.swift" == 0.33.0 ``` @@ -183,7 +183,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.32.2/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.33.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. Once connected, the `inDatabase` and `inTransaction` methods perform your **database statements** in a dedicated, serial, queue: From fe3b5073bc210f98ce448c9533258865f276aa02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 11 Dec 2015 13:36:23 +0100 Subject: [PATCH 67/67] CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f396036..3fd88e5f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ Released December 11, 2015 **New** -- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the persistence methods that used to be reserved to subclasses of `Record`. +- The `DatabasePersistable` and `MutableDatabasePersistable` protocols grant any adopting type the persistence methods that used to be reserved to subclasses of `Record` ([#12](https://github.com/groue/GRDB.swift/issues/12)) - `Database.clearSchemaCache()` **Breaking Changes**