From a6ce80d39bbc25ce65ccf729db77e3cdf5db0c80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jul 2016 22:16:23 +0200 Subject: [PATCH] #56: TableMapping.deleteOne(_:key:), TableMapping.deleteAll(_:keys:) --- GRDB.xcodeproj/project.pbxproj | 18 ++ GRDB/Core/Database.swift | 20 +++ GRDB/Record/TableMapping.swift | 186 ++++++++++++++++++--- Tests/Public/Record/DeleteByKeyTests.swift | 128 ++++++++++++++ 4 files changed, 332 insertions(+), 20 deletions(-) create mode 100644 Tests/Public/Record/DeleteByKeyTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index abd788950..094193c0c 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -748,6 +748,14 @@ 56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */; }; 56FDECE21BB32DFD009AD709 /* MetalRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */; }; 56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */; }; + 56FF45401D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45411D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45421D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45431D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45441D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45451D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45461D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC70AC991AC2331000371524 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = DC37744219C8DC91004FCF85 /* libsqlite3.dylib */; }; @@ -1425,6 +1433,7 @@ 56FC78641BBAEB8C00CA1285 /* MappingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MappingTests.swift; sourceTree = ""; }; 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagedDataControllerTests.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalRowTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeleteByKeyTests.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "../GRDB/GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1936,6 +1945,7 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */, 56A238261B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift */, 56A238271B9C74A90082EB20 /* MinimalPrimaryKeySingleTests.swift */, 56A238281B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift */, @@ -3001,6 +3011,7 @@ files = ( 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */, 560FC5B31CB031EA0014AA8E /* NSDataMemoryTests.swift in Sources */, + 56FF45411D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */, 560FC5641CB00B880014AA8E /* DatabaseQueueConcurrencyTests.swift in Sources */, 560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -3110,6 +3121,7 @@ files = ( 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */, 5671561E1CB16729007DC145 /* NSDataMemoryTests.swift in Sources */, + 56FF45421D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */, 567156211CB16729007DC145 /* DatabaseQueueConcurrencyTests.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -3297,6 +3309,7 @@ 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, 56AFCA511CB1AA9900F48B96 /* ManagedDataControllerTests.swift in Sources */, + 56FF45451D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 56AFCA541CB1AA9900F48B96 /* MappingTests.swift in Sources */, @@ -3391,6 +3404,7 @@ 56AFCAAA1CB1ABC800F48B96 /* ManagedDataControllerTests.swift in Sources */, 569178421CED8E0D00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */, + 56FF45461D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */, 56AFCAAD1CB1ABC800F48B96 /* MappingTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentableTests.swift in Sources */, @@ -3497,6 +3511,7 @@ files = ( 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* AdapterRowTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 56A238561B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -3623,6 +3638,7 @@ 56EA869E1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 56A2385D1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 5672DE591CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 56FF45401D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, 56A238431B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */, 56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */, EED6C2CE1D00B6C900F8E701 /* NSStringTests.swift in Sources */, @@ -3788,6 +3804,7 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* MinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -3967,6 +3984,7 @@ F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */, F3BA811C1CFB305F003DC1BA /* SQLSupportTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */, F3BA80A71CFB2F9D003DC1BA /* MappingTests.swift in Sources */, EED6C2D11D00B6CB00F8E701 /* NSStringTests.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1ea884dbd..375be1331 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -904,6 +904,20 @@ extension Database { return primaryKey } + /// The indexes on table named `tableName`; empty if the table does + /// not exist. + func indexes(tableName: String) -> [IndexInfo] { + return Row.fetch(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row in + let indexName: String = row.value(atIndex: 1) + let unique: Bool = row.value(atIndex: 2) + let columns = Row.fetch(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") + .map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) } + .sort { $0.0 < $1.0 } + .map { $0.1 } + return IndexInfo(name: indexName, columns: columns, isUnique: unique) + } + } + // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // firstName TEXT, @@ -930,6 +944,12 @@ extension Database { primaryKeyIndex = row.value(named: "pk") } } + + struct IndexInfo { + let name: String + let columns: [String] + let isUnique: Bool + } } /// You get primary keys from table names, with the Database.primaryKey(_) diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index ecd32b591..4e057554b 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -1,3 +1,15 @@ +#if !USING_BUILTIN_SQLITE + #if os(OSX) + import SQLiteMacOSX + #elseif os(iOS) + #if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS + #endif + #endif +#endif + /// Types that adopt TableMapping declare a particular relationship with /// a database table. /// @@ -15,7 +27,7 @@ public protocol TableMapping { extension RowConvertible where Self: TableMapping { - // MARK: - Single-Column Primary Key + // MARK: - Fetching by Single-Column Primary Key /// Returns a sequence of records, given their primary keys. /// @@ -29,7 +41,7 @@ extension RowConvertible where Self: TableMapping { /// - returns: A sequence of records. @warn_unused_result public static func fetch(db: Database, keys: Sequence) -> DatabaseSequence { - guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { + guard let statement = fetchByPrimaryKeyStatement(db, keys: keys) else { return DatabaseSequence.emptySequence(db) } return fetch(statement) @@ -47,7 +59,7 @@ extension RowConvertible where Self: TableMapping { /// - returns: An array of records. @warn_unused_result public static func fetchAll(db: Database, keys: Sequence) -> [Self] { - guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { + guard let statement = fetchByPrimaryKeyStatement(db, keys: keys) else { return [] } return fetchAll(statement) @@ -66,14 +78,14 @@ extension RowConvertible where Self: TableMapping { guard let key = key else { return nil } - return fetchOne(fetchByPrimaryKeyStatement(db, values: [key])!) + return fetchOne(fetchByPrimaryKeyStatement(db, keys: [key])!) } // Returns "SELECT * FROM table WHERE id IN (?,?,?)" // // Returns nil if values is empty. @warn_unused_result - private static func fetchByPrimaryKeyStatement(db: Database, values: Sequence) -> SelectStatement? { + private static func fetchByPrimaryKeyStatement(db: Database, keys: Sequence) -> SelectStatement? { // Fail early if database table does not exist. let databaseTableName = self.databaseTableName() let primaryKey = try! db.primaryKey(databaseTableName) @@ -83,8 +95,8 @@ extension RowConvertible where Self: TableMapping { GRDBPrecondition(columns.count == 1, "requires single column primary key in table: \(databaseTableName)") let column = columns.first! - let values = Array(values) - switch values.count { + let keys = Array(keys) + switch keys.count { case 0: // Avoid performing useless SELECT return nil @@ -92,20 +104,94 @@ extension RowConvertible where Self: TableMapping { // SELECT * FROM table WHERE id = ? let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?" let statement = try! db.selectStatement(sql) - statement.arguments = StatementArguments(values) + statement.arguments = StatementArguments(keys) return statement case let count: // SELECT * FROM table WHERE id IN (?,?,?) - let valuesSQL = databaseQuestionMarks(count: count) - let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(valuesSQL))" + let keysSQL = databaseQuestionMarks(count: count) + let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))" let statement = try! db.selectStatement(sql) - statement.arguments = StatementArguments(values) + statement.arguments = StatementArguments(keys) return statement } } +} + +extension TableMapping { + // MARK: - Deleting by Single-Column Primary Key - // MARK: - Other Keys + /// Delete records identified by their primary keys. + /// + /// try Person.deleteAll(db, keys: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: A sequence of primary keys. + /// - returns: The number of deleted rows + public static func deleteAll(db: Database, keys: Sequence) throws -> Int { + guard let statement = deleteByPrimaryKeyStatement(db, keys: keys) else { + return 0 + } + try statement.execute() + return db.changesCount + } + + /// Delete a record, identified by its primary key. + /// + /// try Person.deleteOne(db, key: 123) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a database row was deleted. + public static func deleteOne(db: Database, key: PrimaryKeyType?) throws -> Bool { + guard let key = key else { + return false + } + return try deleteAll(db, keys: [key]) > 0 + } + + // Returns "DELETE FROM table WHERE id IN (?,?,?)" + // + // Returns nil if keys is empty. + @warn_unused_result + private static func deleteByPrimaryKeyStatement(db: Database, keys: Sequence) -> UpdateStatement? { + // Fail early if database table does not exist. + let databaseTableName = self.databaseTableName() + let primaryKey = try! db.primaryKey(databaseTableName) + + // Fail early if database table has not one column in its primary key + let columns = primaryKey?.columns ?? [] + GRDBPrecondition(columns.count == 1, "requires single column primary key in table: \(databaseTableName)") + let column = columns.first! + + let keys = Array(keys) + switch keys.count { + case 0: + // Avoid performing useless DELETE + return nil + case 1: + // DELETE FROM table WHERE id = ? + let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?" + let statement = try! db.updateStatement(sql) + statement.arguments = StatementArguments(keys) + return statement + case let count: + // DELETE FROM table WHERE id IN (?,?,?) + let keysSQL = databaseQuestionMarks(count: count) + let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))" + let statement = try! db.updateStatement(sql) + statement.arguments = StatementArguments(keys) + return statement + } + } +} + + +extension RowConvertible where Self: TableMapping { + + // MARK: - Fetching by Key /// Returns a sequence of records, given an array of key dictionaries. /// @@ -161,11 +247,6 @@ extension RowConvertible where Self: TableMapping { // Returns nil if keys is empty. @warn_unused_result private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? { - // NOTE: this method *was* slow to compile - // https://medium.com/swift-programming/speeding-up-slow-swift-build-times-922feeba5780#.s77wmh4h0 - // 586.8ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/Record/TableMapping.swift:163:25 @warn_unused_result private static func fetchByKeyStatement(db: Database, keys: [[String : DatabaseValueConvertible?]]) -> SelectStatement? - // Fixes are marked with "## Slow Compile Fix (Swift 2.2.x):" - // Avoid performing useless SELECT guard keys.count > 0 else { return nil @@ -176,9 +257,6 @@ extension RowConvertible where Self: TableMapping { for dictionary in keys { GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary") arguments.appendContentsOf(dictionary.values) - // ## Slow Compile Fix (Swift 2.2.x): - // TODO: Check if Swift 3 compiler fixes this line's slow compilation time: - //whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") // Original, Slow To Compile whereClauses.append("(" + (dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joinWithSeparator(" AND ") + ")") } @@ -190,3 +268,71 @@ extension RowConvertible where Self: TableMapping { return statement } } + + +extension TableMapping { + + // MARK: - Deleting by Key + + /// Delete records, given an array of key dictionaries. + /// + /// try Person.deleteAll(db, keys: [["name": "Arthur"], ["name": "Barbara"]]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: An array of key dictionaries. + /// - returns: The number of deleted rows + public static func deleteAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + guard let statement = try deleteByKeyStatement(db, keys: keys) else { + return 0 + } + try statement.execute() + return db.changesCount + } + + /// Delete a record, identified by a key dictionary. + /// + /// Person.deleteOne(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a database row was deleted. + public static func deleteOne(db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + return try deleteAll(db, keys: [key]) > 0 + } + + // Returns "DELETE FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ... + // + // Returns nil if keys is empty. + // + // - throws SQLITE_MISUSE if table has no unique index of the requested columns + @warn_unused_result + private static func deleteByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> UpdateStatement? { + // Avoid performing useless SELECT + guard keys.count > 0 else { + return nil + } + + let databaseTableName = self.databaseTableName() + let uniqueColumnSets = Set(db.indexes(databaseTableName).filter { $0.isUnique }.map { Set($0.columns) }) + + var arguments: [DatabaseValueConvertible?] = [] + var whereClauses: [String] = [] + for dictionary in keys { + let columns = dictionary.keys + guard uniqueColumnSets.contains(Set(columns)) else { + throw DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joinWithSeparator(", "))") + } + GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary") + arguments.appendContentsOf(dictionary.values) + whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joinWithSeparator(" AND ") + ")") + } + + let whereClause = whereClauses.joinWithSeparator(" OR ") + let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)" + let statement = try! db.updateStatement(sql) + statement.arguments = StatementArguments(arguments) + return statement + } +} diff --git a/Tests/Public/Record/DeleteByKeyTests.swift b/Tests/Public/Record/DeleteByKeyTests.swift new file mode 100644 index 000000000..ef253764c --- /dev/null +++ b/Tests/Public/Record/DeleteByKeyTests.swift @@ -0,0 +1,128 @@ +import XCTest +#if USING_SQLCIPHER + import GRDBCipher +#elseif USING_CUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Person : TableMapping { + static func databaseTableName() -> String { + return "persons" + } +} + +private struct Citizenship : TableMapping { + static func databaseTableName() -> String { + return "citizenships" + } +} + + +class DeleteByKeyTests: GRDBTestCase { + + override func setUpDatabase(dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") + try db.execute("CREATE TABLE citizenships (personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))") + } + } + + func testSingleColumnPrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try Person.deleteOne(db, key: 1) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1") + XCTAssertFalse(deleted) + + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try Person.deleteOne(db, key: 1) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1") + XCTAssertTrue(deleted) + XCTAssertEqual(Person.fetchCount(db), 0) + + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try Person.deleteAll(db, keys: [2, 3, 4]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (2,3,4)") + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(Person.fetchCount(db), 1) + } + } + } + + func testMultipleColumnPrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenships\" WHERE (\"personId\" = 1 AND \"countryIsoCode\" = 'FR')") + XCTAssertFalse(deleted) + + try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"]) + deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenships\" WHERE (\"personId\" = 1 AND \"countryIsoCode\" = 'FR')") + XCTAssertTrue(deleted) + XCTAssertEqual(Citizenship.fetchCount(db), 0) + + try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"]) + try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "US"]) + try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [2, "US"]) + let deletedCount = try Citizenship.deleteAll(db, keys: [["personId": 1, "countryIsoCode": "FR"], ["personId": 1, "countryIsoCode": "US"], ["personId": 1, "countryIsoCode": "DE"]]) + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(Citizenship.fetchCount(db), 1) + } + } + } + + func testUniqueIndex() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try Person.deleteOne(db, key: ["email": "arthur@example.com"]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"email\" = 'arthur@example.com')") + XCTAssertFalse(deleted) + + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try Person.deleteOne(db, key: ["email": "arthur@example.com"]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"email\" = 'arthur@example.com')") + XCTAssertTrue(deleted) + XCTAssertEqual(Person.fetchCount(db), 0) + + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try Person.deleteAll(db, keys: [["email": "arthur@example.com"], ["email": "barbara@example.com"], ["email": "david@example.com"]]) + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(Person.fetchCount(db), 1) + } + } + } + + func testNonUniqueIndex() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + try Person.deleteOne(db, key: ["name": "Arthur"]) + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, 21) // SQLITE_MISUSE + XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name") + XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name") + } + do { + try Person.deleteAll(db, keys: [["name": "Arthur"], ["name": "Barbara"]]) + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, 21) // SQLITE_MISUSE + XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name") + XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name") + } + } + } + } +}