From 99ec2a11286dc6fd18acf66cc8ddd811f9cdf066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Oct 2015 14:02:57 +0100 Subject: [PATCH] DatabaseTableMapping.fetch(_:keys:) tests WIP --- .../Record/MinimalPrimaryKeyRowIDTests.swift | 62 +++++++++++++- .../Core/Protocols/DatabaseTableMapping.swift | 84 +++++++++++++++---- 2 files changed, 128 insertions(+), 18 deletions(-) diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift index a97ed33b5..4872ed28e 100644 --- a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift @@ -343,9 +343,65 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { } - // MARK: - Select + // MARK: - Fetch - func testSelectWithPrimaryKey() { + func testFetchWithKeys() { + assertNoError { + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let fetchedRecords = Array(MinimalRowID.fetch(db, keys: [])) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = Array(MinimalRowID.fetch(db, keys: [["id": record1.id], ["id": record2.id]])) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + } + + do { + let fetchedRecords = Array(MinimalRowID.fetch(db, keys: [["id": record1.id], ["id": nil]])) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.id, record1.id!) + } + } + } + } + + func testFetchAllWithKeys() { + assertNoError { + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let fetchedRecords = MinimalRowID.fetchAll(db, keys: []) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = MinimalRowID.fetchAll(db, keys: [["id": record1.id], ["id": record2.id]]) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + } + + do { + let fetchedRecords = MinimalRowID.fetchAll(db, keys: [["id": record1.id], ["id": nil]]) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.id, record1.id!) + } + } + } + } + + func testFetchOneWithPrimaryKey() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalRowID() @@ -357,7 +413,7 @@ class MinimalPrimaryKeyRowIDTests: GRDBTestCase { } } - func testSelectWithKey() { + func testFetchOneWithKey() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalRowID() diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index a3e11d937..2c463d8d4 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -38,7 +38,7 @@ extension DatabaseTableMapping { /// The order of values in the returned array is undefined. /// /// - parameter db: A Database. - /// - parameter primaryKeys: A array of primary keys. + /// - parameter primaryKeys: An array of primary keys. /// - returns: An array. public static func fetchAll(db: Database, primaryKeys: Sequence) -> [Self] { if let statement = self.fetchByPrimaryKeyStatement(db, primaryKeys: primaryKeys) { @@ -62,6 +62,40 @@ extension DatabaseTableMapping { return self.fetchOne(self.fetchByPrimaryKeyStatement(db, primaryKeys: [primaryKey])!) } + /// Fetches a sequence of values, given an array of key dictionaries. + /// + /// let persons = Person.fetch(db, keys: [["name": "Arthur"], ["name": "Barbara"]]) // DatabaseSequence + /// + /// The order of values in the returned sequence is undefined. + /// + /// - parameter db: A Database. + /// - parameter keys: An array of key dictionaries. + /// - returns: A sequence. + public static func fetch(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence { + if let statement = self.fetchByKeyStatement(db, keys: keys) { + return self.fetch(statement) + } else { + return DatabaseSequence() + } + } + + /// Fetches an array of values, given an array of key dictionaries. + /// + /// let persons = Person.fetchAll(db, primaryKeys: [["name": "Arthur"], ["name": "Barbara"]]) // [Person] + /// + /// The order of values in the returned array is undefined. + /// + /// - parameter db: A Database. + /// - parameter keys: An array of key dictionaries. + /// - returns: An array. + public static func fetchAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] { + if let statement = self.fetchByKeyStatement(db, keys: keys) { + return self.fetchAll(statement) + } else { + return [] + } + } + /// Fetches a single value given a key. /// /// let person = Person.fetchOne(db, key: ["name": Arthur"]) // Person? @@ -69,20 +103,8 @@ extension DatabaseTableMapping { /// - parameter db: A Database. /// - parameter key: A dictionary of values. /// - returns: An optional value. - public static func fetchOne(db: Database, key dictionary: [String: DatabaseValueConvertible?]) -> Self? { - // Fail early if databaseTable is nil - guard let databaseTableName = self.databaseTableName() else { - fatalError("Nil returned from \(self).databaseTableName()") - } - - // Fail early if key is empty. - guard dictionary.count > 0 else { - fatalError("Invalid empty key") - } - - let whereSQL = dictionary.keys.map { column in "\(column.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ") - let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" - return fetchOne(db.selectStatement(sql), arguments: StatementArguments(dictionary.values)) + public static func fetchOne(db: Database, key: [String: DatabaseValueConvertible?]) -> Self? { + return self.fetchOne(self.fetchByKeyStatement(db, keys: [key])!) } // Returns "SELECT * FROM table WHERE id IN (?,?,?)" @@ -126,4 +148,36 @@ extension DatabaseTableMapping { return statement } } + + // Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ... + // + // 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 = self.databaseTableName() else { + fatalError("Nil returned from \(self).databaseTableName()") + } + + // Avoid performing useless SELECT + guard keys.count > 0 else { + return nil + } + + var arguments: [DatabaseValueConvertible?] = [] + var whereClauses: [String] = [] + for dictionary in keys { + guard dictionary.count > 0 else { + fatalError("Invalid empty key") + } + + arguments.appendContentsOf(dictionary.values) + whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") + } + + let whereClause = whereClauses.joinWithSeparator(" OR ") + let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)" + let statement = db.selectStatement(sql) + statement.arguments = StatementArguments(arguments) + return statement + } }