diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4e7e01662..d9a9a826a 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -778,6 +778,14 @@ 56AFCACF1CB1ABC800F48B96 /* StatementInformationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementInformationTests.swift */; }; 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; }; + 56B021C91D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CA1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CB1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CC1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CD1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CE1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021CF1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; + 56B021D01D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */; }; 56B14E801D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift */; }; 56B14E811D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift */; }; @@ -1564,6 +1572,7 @@ 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCA7F1CB1AA9900F48B96 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCAD71CB1ABC800F48B96 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAsDictionaryLiteralConvertibleTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControlleriOSTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -1864,6 +1873,7 @@ children = ( 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 56B021C81D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift */, ); path = Persistable; sourceTree = ""; @@ -3333,6 +3343,7 @@ 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* PrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, + 56B021CA1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 560FC5731CB00B880014AA8E /* RecordFetchTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, 560FC5761CB00B880014AA8E /* DetachedRowTests.swift in Sources */, @@ -3512,6 +3523,7 @@ 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* SavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 56B021CB1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, 566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */, @@ -3648,6 +3660,7 @@ buildActionMask = 2147483647; files = ( 56AFCA301CB1AA9900F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, + 56B021CE1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 56F26C241CEE3F34007969C4 /* AdapterRowTests.swift in Sources */, 56AFCA311CB1AA9900F48B96 /* PrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3752,6 +3765,7 @@ buildActionMask = 2147483647; files = ( 56C3F7581CF9F12400F6A361 /* SavepointTests.swift in Sources */, + 56B021CF1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56AFCA8A1CB1ABC800F48B96 /* PrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3935,6 +3949,7 @@ 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, 56A238481B9C74A90082EB20 /* DetachedRowTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* SavepointTests.swift in Sources */, + 56B021CD1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, 566AD8CA1D531BEC002EC1A8 /* SQLTableBuilderTests.swift in Sources */, @@ -4084,6 +4099,7 @@ 56D4966C1D81309E008276D7 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* NSNumberTests.swift in Sources */, + 56B021C91D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 56D496571D81303E008276D7 /* DateComponentsTests.swift in Sources */, 56D496701D81309E008276D7 /* PrimaryKeyRowIDTests.swift in Sources */, @@ -4245,6 +4261,7 @@ F3BA81221CFB3063003DC1BA /* PrimaryKeyRowIDTests.swift in Sources */, F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* AdapterRowTests.swift in Sources */, + 56B021D01D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */, @@ -4389,6 +4406,7 @@ 5657AB591D108BA9006283EF /* NSStringTests.swift in Sources */, 56B14E821D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, + 56B021CC1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */, 561667041D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */, F3BA80BF1CFB2FD2003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 930673fda..6a6547bd9 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -36,6 +36,26 @@ private func databaseValues(for columns: [String], inDictionary dictionary: [Str // MARK: - MutablePersistable +/// The MutablePersistable protocol uses this type in order to handle SQLite +/// conflicts when records are inserted or updated. +/// +/// See `MutablePersistable.persistenceConflictPolicy`. +/// +/// See https://www.sqlite.org/lang_conflict.html +public struct PersistenceConflictPolicy { + /// The conflict resolution algorithm for insertions + public let insertionConflictResolution: SQLConflictResolution + + /// The conflict resolution algorithm for updates + public let updateConflictResolution: SQLConflictResolution + + /// Creates a policy + public init(insertion: SQLConflictResolution, update: SQLConflictResolution) { + self.insertionConflictResolution = insertion + self.updateConflictResolution = update + } +} + /// Types that adopt MutablePersistable can be inserted, updated, and deleted. /// /// This protocol is intented for types that have an INTEGER PRIMARY KEY, and @@ -44,6 +64,19 @@ private func databaseValues(for columns: [String], inDictionary dictionary: [Str /// /// The insert() and save() methods are mutating methods. public protocol MutablePersistable : TableMapping { + /// The policy that handles SQLite conflicts when records are inserted + /// or updated. + /// + /// This property is optional: its default value specifies ABORT policy + /// for both insertions and updates, which has GRDB generate regular + /// INSERT and UPDATE queries. + /// + /// If insertions are resolved with .replace or .ignore policies, the + /// `didInsert(with:for:)` method is not called upon successful insertion, + /// even when there was no conflict, and a row was actually inserted. + /// + /// See https://www.sqlite.org/lang_conflict.html + static var persistenceConflictPolicy: PersistenceConflictPolicy { get } /// Returns the values that should be stored in the database. /// @@ -169,6 +202,13 @@ public protocol MutablePersistable : TableMapping { } public extension MutablePersistable { + /// Describes the conflict policy for insertions and updates. + /// + /// The default value specifies ABORT policy for both insertions and + /// updates, which has GRDB generate regular INSERT and UPDATE queries. + static var persistenceConflictPolicy: PersistenceConflictPolicy { + return PersistenceConflictPolicy(insertion: .abort, update: .abort) + } /// Notifies the record that it was succesfully inserted. /// @@ -279,9 +319,17 @@ public extension MutablePersistable { /// implementation of insert(). They should not provide their own /// implementation of performInsert(). mutating func performInsert(_ db: Database) throws { + let insertionConflictResolution = type(of: self).persistenceConflictPolicy.insertionConflictResolution let dao = DAO(db, self) - try dao.insertStatement().execute() - didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn) + try dao.insertStatement(onConflict: insertionConflictResolution).execute() + + switch insertionConflictResolution { + case .abort, .fail, .rollback: + didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn) + case .replace, .ignore: + // Statement may have succeeded without inserting any row + break + } } /// Don't invoke this method directly: it is an internal method for types @@ -298,7 +346,7 @@ public extension MutablePersistable { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. func performUpdate(_ db: Database, columns: Set) throws { - guard let statement = DAO(db, self).updateStatement(columns: columns) else { + guard let statement = DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.updateConflictResolution) else { // Nil primary key throw PersistenceError.recordNotFound(self) } @@ -473,9 +521,17 @@ public extension Persistable { /// implementation of insert(). They should not provide their own /// implementation of performInsert(). func performInsert(_ db: Database) throws { + let insertionConflictResolution = type(of: self).persistenceConflictPolicy.insertionConflictResolution let dao = DAO(db, self) - try dao.insertStatement().execute() - didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn) + try dao.insertStatement(onConflict: insertionConflictResolution).execute() + + switch insertionConflictResolution { + case .abort, .fail, .rollback: + didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn) + case .replace, .ignore: + // Statement may have succeeded without inserting any row + break + } } /// Don't invoke this method directly: it is an internal method for types @@ -547,8 +603,9 @@ final class DAO { self.primaryKey = primaryKey } - func insertStatement() -> UpdateStatement { + func insertStatement(onConflict: SQLConflictResolution) -> UpdateStatement { let query = InsertQuery( + onConflict: onConflict, tableName: databaseTableName, insertedColumns: Array(persistentDictionary.keys)) let statement = try! db.cachedUpdateStatement(query.sql) @@ -557,7 +614,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func updateStatement(columns: Set) -> UpdateStatement? { + func updateStatement(columns: Set, onConflict: SQLConflictResolution) -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary) @@ -589,6 +646,7 @@ final class DAO { let updatedValues = databaseValues(for: updatedColumns, inDictionary: persistentDictionary) let query = UpdateQuery( + onConflict: onConflict, tableName: databaseTableName, updatedColumns: updatedColumns, conditionColumns: primaryKeyColumns) @@ -632,6 +690,7 @@ final class DAO { // MARK: - InsertQuery private struct InsertQuery { + let onConflict: SQLConflictResolution let tableName: String let insertedColumns: [String] } @@ -642,6 +701,7 @@ extension InsertQuery : Hashable { private func == (lhs: InsertQuery, rhs: InsertQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } + if lhs.onConflict != rhs.onConflict { return false } return lhs.insertedColumns == rhs.insertedColumns } @@ -653,7 +713,13 @@ extension InsertQuery { } let columnsSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ") let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) - let sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + let sql: String + switch onConflict { + case .abort: + sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + default: + sql = "INSERT OR \(onConflict.rawValue) INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + } InsertQuery.sqlCache.write { $0[self] = sql } return sql } @@ -663,6 +729,7 @@ extension InsertQuery { // MARK: - UpdateQuery private struct UpdateQuery { + let onConflict: SQLConflictResolution let tableName: String let updatedColumns: [String] let conditionColumns: [String] @@ -674,6 +741,7 @@ extension UpdateQuery : Hashable { private func == (lhs: UpdateQuery, rhs: UpdateQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } + if lhs.onConflict != rhs.onConflict { return false } if lhs.updatedColumns != rhs.updatedColumns { return false } return lhs.conditionColumns == rhs.conditionColumns } @@ -686,7 +754,13 @@ extension UpdateQuery { } let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") - let sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + let sql: String + switch onConflict { + case .abort: + sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + default: + sql = "UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + } UpdateQuery.sqlCache.write { $0[self] = sql } return sql } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 329c15f79..d9036d05c 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -215,25 +215,33 @@ open class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both insertion, and change tracking. + let insertionConflictResolution = type(of: self).persistenceConflictPolicy.insertionConflictResolution let dao = DAO(db, self) var persistentDictionary = dao.persistentDictionary - try dao.insertStatement().execute() - let rowID = db.lastInsertedRowID - let rowIDColumn = dao.primaryKey?.rowIDColumn - didInsert(with: rowID, for: rowIDColumn) + try dao.insertStatement(onConflict: insertionConflictResolution).execute() - // Update persistentDictionary with inserted id, so that we can - // set hasPersistentChangedValues to false: - if let rowIDColumn = rowIDColumn { - if persistentDictionary[rowIDColumn] != nil { - persistentDictionary[rowIDColumn] = rowID - } else { - let rowIDColumn = rowIDColumn.lowercased() - for column in persistentDictionary.keys where column.lowercased() == rowIDColumn { - persistentDictionary[column] = rowID - break + switch insertionConflictResolution { + case .abort, .fail, .rollback: + let rowID = db.lastInsertedRowID + let rowIDColumn = dao.primaryKey?.rowIDColumn + didInsert(with: rowID, for: rowIDColumn) + + // Update persistentDictionary with inserted id, so that we can + // set hasPersistentChangedValues to false: + if let rowIDColumn = rowIDColumn { + if persistentDictionary[rowIDColumn] != nil { + persistentDictionary[rowIDColumn] = rowID + } else { + let rowIDColumn = rowIDColumn.lowercased() + for column in persistentDictionary.keys where column.lowercased() == rowIDColumn { + persistentDictionary[column] = rowID + break + } } } + case .replace, .ignore: + // Statement may have succeeded without inserting any row + break } // Set hasPersistentChangedValues to false @@ -266,7 +274,7 @@ open class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both update, and change tracking. let dao = DAO(db, self) - guard let statement = dao.updateStatement(columns: columns) else { + guard let statement = dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.updateConflictResolution) else { // Nil primary key throw PersistenceError.recordNotFound(self) } diff --git a/Tests/Public/Core/Persistable/PersistenceConflictPolicyTests.swift b/Tests/Public/Core/Persistable/PersistenceConflictPolicyTests.swift new file mode 100644 index 000000000..17405e40e --- /dev/null +++ b/Tests/Public/Core/Persistable/PersistenceConflictPolicyTests.swift @@ -0,0 +1,270 @@ +import XCTest +#if USING_SQLCIPHER + import GRDBCipher +#elseif USING_CUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct DefaultPolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct MixedPolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .fail, update: .rollback) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct ReplacePolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .replace, update: .replace) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct IgnorePolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .ignore, update: .ignore) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct FailPolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .fail, update: .fail) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct AbortPolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .abort, update: .abort) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +private struct RollbackPolicy: MutablePersistable { + var id: Int64? + + static let databaseTableName = "records" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insertion: .rollback, update: .rollback) + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id] + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +class PersistenceConflictPolicyTests: GRDBTestCase { + + func testDefaultPolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = DefaultPolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT INTO \"records\"")) + XCTAssertTrue(record.id == 1) + + // Update + record = DefaultPolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE \"records\"")) + } + } + } + + func testMixedPolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = MixedPolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR FAIL INTO \"records\"")) + XCTAssertTrue(record.id == 1) + + // Update + record = MixedPolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR ROLLBACK \"records\"")) + } + } + } + + func testReplacePolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = ReplacePolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR REPLACE INTO \"records\"")) + XCTAssertTrue(record.id == nil) + + // Update + record = ReplacePolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR REPLACE \"records\"")) + } + } + } + + func testIgnorePolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = IgnorePolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR IGNORE INTO \"records\"")) + XCTAssertTrue(record.id == nil) + + // Update + record = IgnorePolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR IGNORE \"records\"")) + } + } + } + + func testFailPolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = FailPolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR FAIL INTO \"records\"")) + XCTAssertTrue(record.id == 1) + + // Update + record = FailPolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR FAIL \"records\"")) + } + } + } + + func testAbortPolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = AbortPolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT INTO \"records\"")) + XCTAssertTrue(record.id == 1) + + // Update + record = AbortPolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE \"records\"")) + } + } + } + + func testRollbackPolicy() { + assertNoError { + let db = try makeDatabaseQueue() + try db.inDatabase { db in + try db.create(table: "records") { t in + t.column("id", .integer).primaryKey() + } + + // Insert + var record = RollbackPolicy(id: nil) + try record.insert(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR ROLLBACK INTO \"records\"")) + XCTAssertTrue(record.id == 1) + + // Update + record = RollbackPolicy(id: 1) + try record.update(db) + XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR ROLLBACK \"records\"")) + } + } + } + +}