diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 79d026c97..c84bb373a 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -104,15 +104,13 @@ extension QueryInterfaceRequest { /// var request = Player.all() /// request = request.filter(Column("email") == "arthur@example.com") public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - var query = self.query - query.wherePromise = query.wherePromise.map { (db, expression) in + return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in if let expression = expression { return expression && predicate.sqlExpression } else { return predicate.sqlExpression } - } - return QueryInterfaceRequest(query: query) + }) } /// A new QueryInterfaceRequest with the provided *predicate* added to the @@ -241,7 +239,7 @@ extension QueryInterfaceRequest where T: TableMapping { /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id IN 1 + /// // SELECT * FROM players WHERE id = 1 /// var request = Player.all() /// request = request.filter(key: 1) /// @@ -266,8 +264,6 @@ extension QueryInterfaceRequest where T: TableMapping { /// all requests by the `TableMapping.databaseSelection` property, or /// for individual requests with the `TableMapping.select` method. public func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { - var query = self.query - let keys = Array(keys) let makePredicate: (Column) -> SQLExpression switch keys.count { @@ -279,17 +275,82 @@ extension QueryInterfaceRequest where T: TableMapping { makePredicate = { keys.contains($0) } } - query.wherePromise = query.wherePromise.map { (db, expression) in + return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in let primaryKey = try db.primaryKey(T.databaseTableName) GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)") - let keyPredicate = makePredicate(Column(primaryKey.columns[0])) + let keysPredicate = makePredicate(Column(primaryKey.columns[0])) if let expression = expression { - return expression && keyPredicate + return expression && keysPredicate } else { - return keyPredicate + return keysPredicate } + }) + } + + /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// + /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' + /// var request = Player.all() + /// request = request.filter(key: ["personId": 1, "countryCode": "FR"]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + guard let key = key else { + return T.none() } - return QueryInterfaceRequest(query: query) + + return filter(keys: [key]) + } + + /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// + /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + guard !keys.isEmpty else { + return T.none() + } + + return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in + let keyPredicates: [SQLExpression] = try keys.map { key in + // Prevent filter(db, keys: [[:]]) + GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary") + + // Prevent filter(keys: [["foo": 1, "bar": 2]]) where + // ("foo", "bar") is not a unique key (primary key or columns of a + // unique index) + guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else { + fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + } + + let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } + let columnPredicates: [SQLExpression] = key + // Sort key columns in the same order as the unique index + .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } + .map { (column, value) in Column(column) == value } + return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty + } + + let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keys is not emmpty + + if let expression = expression { + return expression && keysPredicate + } else { + return keysPredicate + } + }) } } @@ -366,10 +427,9 @@ extension TableMapping { return all().filter(predicate) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id IN 1 + /// // SELECT * FROM players WHERE id = 1 /// let request = Player.filter(key: 1) /// /// The selection defaults to all columns. This default can be changed for @@ -391,6 +451,36 @@ extension TableMapping { return all().filter(keys: keys) } + /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// + /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' + /// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + public static func filter(key: [String: DatabaseValueConvertible?]) -> QueryInterfaceRequest { + return all().filter(key: key) + } + + /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// + /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + return all().filter(keys: keys) + } + /// Creates a QueryInterfaceRequest with the provided *predicate*. /// /// // SELECT * FROM players WHERE email = 'arthur@example.com' diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift index 61489145d..91331992a 100644 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift @@ -1,27 +1,14 @@ // MARK: - QueryInterfaceSelectQueryDefinition -// Badly named, I know struct DatabasePromise { - private enum Future { - case value(T) - case function((Database) throws -> T) - } - - private var future: Future + let resolve: (Database) throws -> T init(value: T) { - self.future = .value(value) + self.resolve = { _ in value } } - init(_ function: @escaping (Database) throws -> T) { - self.future = .function(function) - } - - func resolve(_ db: Database) throws -> T { - switch future { - case .value(let value): return value - case .function(let f): return try f(db) - } + init(_ resolve: @escaping (Database) throws -> T) { + self.resolve = resolve } func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise { @@ -64,6 +51,12 @@ struct QueryInterfaceSelectQueryDefinition { self.limit = limit } + func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition { + var query = self + query.wherePromise = query.wherePromise.map(transform) + return query + } + func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { var sql = "SELECT" diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index d892a8b7a..b739f95c9 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -623,7 +623,7 @@ extension MutablePersistable { // Avoid hitting the database return 0 } - return try filter(db, keys: keys).deleteAll(db) + return try filter(keys: keys).deleteAll(db) } /// Delete a record, identified by a unique key (the primary key or any key diff --git a/GRDB/Record/RowConvertible+TableMapping.swift b/GRDB/Record/RowConvertible+TableMapping.swift index ec2ef3458..409ac2709 100644 --- a/GRDB/Record/RowConvertible+TableMapping.swift +++ b/GRDB/Record/RowConvertible+TableMapping.swift @@ -139,7 +139,7 @@ extension RowConvertible where Self: TableMapping { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor { - return try filter(db, keys: keys).fetchCursor(db) + return try filter(keys: keys).fetchCursor(db) } /// Returns an array of records identified by the provided unique keys @@ -155,12 +155,11 @@ extension RowConvertible where Self: TableMapping { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] { - let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database return [] } - return try filter(db, keys: keys).fetchAll(db) + return try filter(keys: keys).fetchAll(db) } /// Returns a single record identified by a unique key (the primary key or @@ -173,7 +172,11 @@ extension RowConvertible where Self: TableMapping { /// - key: A dictionary of values. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? { - return try filter(db, keys: [key]).fetchOne(db) + public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? { + guard let key = key else { + // Avoid hitting the database + return nil + } + return try filter(key: key).fetchOne(db) } } diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index b690d0ad4..7d70fda66 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -68,48 +68,3 @@ extension TableMapping { } } -extension TableMapping { - - // MARK: Key Requests - - // Raises a fatal error if there is no unique index on the columns (unless - // fatalErrorOnMissingUniqueIndex is false, for testability). - // - // TODO: think about - // - allowing non unique keys in Type.fetchOne(db, key: ...) ??? - // - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...) - // - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key) - static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest { - // SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...) - let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(db, keys: [[:]]) - GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary") - - // Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where - // ("foo", "bar") is not a unique key (primary key or columns of a - // unique index) - guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { - let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))" - if fatalErrorOnMissingUniqueIndex { - fatalError(message) - } else { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message) - } - } - - let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } - let columnPredicates: [SQLExpression] = key - // Sort key columns in the same order as the unique index - .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } - .map { (column, value) in Column(column) == value } - return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty - } - - guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else { - // No key - return none() - } - - return filter(predicate) - } -} diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme index 5dddc11e7..7a6690b89 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme @@ -41,7 +41,8 @@ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" language = "" - shouldUseLaunchSchemeArgsEnv = "YES"> + shouldUseLaunchSchemeArgsEnv = "YES" + codeCoverageEnabled = "YES"> diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index aeb40ebd0..9c4e9eb64 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -310,6 +310,76 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let cursor = try MinimalRowID.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.id!, record1.id!) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let fetchedRecords = try MinimalRowID.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + } + + do { + let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.id, record1.id!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + + let fetchedRecord = try MinimalRowID.filter(key: ["id": record.id]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + } + } + // MARK: - Fetch With Primary Key @@ -379,6 +449,75 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let ids: [Int64] = [] + let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalRowID() + try record1.insert(db) + let record2 = MinimalRowID() + try record2.insert(db) + + do { + let ids: [Int64] = [] + let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + + do { + let id: Int64? = nil + let fetchedRecord = try MinimalRowID.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try MinimalRowID.filter(key: record.id).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 42e33136f..53de5100e 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -321,6 +321,81 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalSingle() + record1.UUID = "theUUID1" + try record1.insert(db) + let record2 = MinimalSingle() + record2.UUID = "theUUID2" + try record2.insert(db) + + do { + let cursor = try MinimalSingle.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalSingle() + record1.UUID = "theUUID1" + try record1.insert(db) + let record2 = MinimalSingle() + record2.UUID = "theUUID2" + try record2.insert(db) + + do { + let fetchedRecords = try MinimalSingle.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!])) + } + + do { + let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + + let fetchedRecord = try MinimalSingle.filter(key: ["UUID": record.UUID]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + } + } + // MARK: - Fetch With Primary Key @@ -395,6 +470,80 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalSingle() + record1.UUID = "theUUID1" + try record1.insert(db) + let record2 = MinimalSingle() + record2.UUID = "theUUID2" + try record2.insert(db) + + do { + let UUIDs: [String] = [] + let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = MinimalSingle() + record1.UUID = "theUUID1" + try record1.insert(db) + let record2 = MinimalSingle() + record2.UUID = "theUUID2" + try record2.insert(db) + + do { + let UUIDs: [String] = [] + let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + + do { + let id: String? = nil + let fetchedRecord = try MinimalSingle.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try MinimalSingle.filter(key: record.UUID).fetchOne(db)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index ae1b3b903..4b6f1be62 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -390,6 +390,79 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let cursor = try Person.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.id!, record1.id!) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let fetchedRecords = try Person.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + } + + do { + let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.id, record1.id!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(name: "Arthur") + try record.insert(db) + + let fetchedRecord = try Person.filter(key: ["rowid": record.id]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + } + } + // MARK: - Fetch With Primary Key @@ -462,6 +535,78 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let ids: [Int64] = [] + let cursor = try Person.filter(keys: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try Person.filter(keys: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(name: "Arthur") + try record.insert(db) + + do { + let id: Int64? = nil + let fetchedRecord = try Person.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 8464ad6df..486610a9e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -344,6 +344,78 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true) + try record1.insert(db) + let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false) + try record2.insert(db) + + do { + let cursor = try Citizenship.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.personName, record1.personName) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true) + try record1.insert(db) + let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false) + try record2.insert(db) + + do { + let fetchedRecords = try Citizenship.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName])) + } + + do { + let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.personName, record1.personName!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Citizenship(personName: "Arthur", countryName: "France", native: true) + try record.insert(db) + + let fetchedRecord = try Citizenship.filter(key: ["personName": record.personName, "countryName": record.countryName]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.personName == record.personName) + XCTAssertTrue(fetchedRecord.countryName == record.countryName) + XCTAssertTrue(fetchedRecord.native == record.native) + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index c7edf26c2..76890fa94 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -103,6 +103,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Item(email: "item@example.com") + try record.insert(db) + + let fetchedRecord = try Item.filter(key: ["email": record.email]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.email == record.email) + } + } + // MARK: - Fetch With Primary Key @@ -176,4 +190,78 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } } } + + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Item(name: "Table") + try record1.insert(db) + let id1 = db.lastInsertedRowID + let record2 = Item(name: "Chair") + try record2.insert(db) + let id2 = db.lastInsertedRowID + + do { + let ids: [Int64] = [] + let cursor = try Item.filter(keys: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [id1, id2] + let cursor = try Item.filter(keys: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! })) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Item(name: "Table") + try record1.insert(db) + let id1 = db.lastInsertedRowID + let record2 = Item(name: "Chair") + try record2.insert(db) + let id2 = db.lastInsertedRowID + + do { + let ids: [Int64] = [] + let fetchedRecords = try Item.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [id1, id2] + let fetchedRecords = try Item.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! })) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Item(name: "Table") + try record.insert(db) + let id = db.lastInsertedRowID + + do { + let id: Int64? = nil + let fetchedRecord = try Item.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try Item.filter(key: id).fetchOne(db)! + XCTAssertTrue(fetchedRecord.name == record.name) + } + } + } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 1eab69e95..8ca0f792e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -386,6 +386,79 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let cursor = try Person.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.id!, record1.id!) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let fetchedRecords = try Person.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id])) + } + + do { + let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.id, record1.id!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(name: "Arthur") + try record.insert(db) + + let fetchedRecord = try Person.filter(key: ["id": record.id]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + } + } + // MARK: - Fetch With Primary Key @@ -458,6 +531,78 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let ids: [Int64] = [] + let cursor = try Person.filter(keys: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try Person.filter(keys: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Person(name: "Arthur") + try record1.insert(db) + let record2 = Person(name: "Barbara") + try record2.insert(db) + + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.filter(keys: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Person(name: "Arthur") + try record.insert(db) + + do { + let id: Int64? = nil + let fetchedRecord = try Person.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 32b4232ac..37e7f840a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -336,6 +336,77 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Pet(UUID: "BobbyUUID", name: "Bobby") + try record1.insert(db) + let record2 = Pet(UUID: "CainUUID", name: "Cain") + try record2.insert(db) + + do { + let cursor = try Pet.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Pet(UUID: "BobbyUUID", name: "Bobby") + try record1.insert(db) + let record2 = Pet(UUID: "CainUUID", name: "Cain") + try record2.insert(db) + + do { + let fetchedRecords = try Pet.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!])) + } + + do { + let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Pet(UUID: "BobbyUUID", name: "Bobby") + try record.insert(db) + + let fetchedRecord = try Pet.filter(key: ["UUID": record.UUID]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + XCTAssertTrue(fetchedRecord.name == record.name) + } + } + // MARK: - Fetch With Primary Key @@ -406,6 +477,76 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Pet(UUID: "BobbyUUID", name: "Bobby") + try record1.insert(db) + let record2 = Pet(UUID: "CainUUID", name: "Cain") + try record2.insert(db) + + do { + let UUIDs: [String] = [] + let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Pet(UUID: "BobbyUUID", name: "Bobby") + try record1.insert(db) + let record2 = Pet(UUID: "CainUUID", name: "Cain") + try record2.insert(db) + + do { + let UUIDs: [String] = [] + let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Pet(UUID: "BobbyUUID", name: "Bobby") + try record.insert(db) + + do { + let id: String? = nil + let fetchedRecord = try Pet.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try Pet.filter(key: record.UUID).fetchOne(db)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + XCTAssertTrue(fetchedRecord.name == record.name) + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index e531788e8..39c99e05c 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -327,6 +327,81 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } + + // MARK: - Fetch With Key Request + + func testFetchCursorWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Email() + record1.email = "me@domain.com" + try record1.insert(db) + let record2 = Email() + record2.email = "you@domain.com" + try record2.insert(db) + + do { + let cursor = try Email.filter(keys: []).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let cursor = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email])) + XCTAssertTrue(try cursor.next() == nil) // end + } + + do { + let cursor = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchCursor(db) + let fetchedRecord = try cursor.next()! + XCTAssertEqual(fetchedRecord.email, record1.email) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Email() + record1.email = "me@domain.com" + try record1.insert(db) + let record2 = Email() + record2.email = "you@domain.com" + try record2.insert(db) + + do { + let fetchedRecords = try Email.filter(keys: []).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email])) + } + + do { + let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 1) + XCTAssertEqual(fetchedRecords.first!.email, record1.email!) + } + } + } + + func testFetchOneWithKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Email() + record.email = "me@domain.com" + try record.insert(db) + + let fetchedRecord = try Email.filter(key: ["email": record.email]).fetchOne(db)! + XCTAssertTrue(fetchedRecord.email == record.email) + } + } + // MARK: - Fetch With Primary Key @@ -401,6 +476,80 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } + + // MARK: - Fetch With Primary Key Request + + func testFetchCursorWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Email() + record1.email = "me@domain.com" + try record1.insert(db) + let record2 = Email() + record2.email = "you@domain.com" + try record2.insert(db) + + do { + let emails: [String] = [] + let cursor = try Email.filter(keys: emails).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let emails = [record1.email!, record2.email!] + let cursor = try Email.filter(keys: emails).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.email! }), Set(emails)) + XCTAssertTrue(try cursor.next() == nil) // end + } + } + } + + func testFetchAllWithPrimaryKeysRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record1 = Email() + record1.email = "me@domain.com" + try record1.insert(db) + let record2 = Email() + record2.email = "you@domain.com" + try record2.insert(db) + + do { + let emails: [String] = [] + let fetchedRecords = try Email.filter(keys: emails).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let emails = [record1.email!, record2.email!] + let fetchedRecords = try Email.filter(keys: emails).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set(emails)) + } + } + } + + func testFetchOneWithPrimaryKeyRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = Email() + record.email = "me@domain.com" + try record.insert(db) + + do { + let id: String? = nil + let fetchedRecord = try Email.filter(key: id).fetchOne(db) + XCTAssertTrue(fetchedRecord == nil) + } + + do { + let fetchedRecord = try Email.filter(key: record.email).fetchOne(db)! + XCTAssertTrue(fetchedRecord.email == record.email) + } + } + } + // MARK: - Exists diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index ad71d2c93..efee44855 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -15,29 +15,13 @@ private struct Person : RowConvertible, TableMapping { class RecordUniqueIndexTests: GRDBTestCase { - func testKeyFilterRequiresUniqueIndex() throws { + func testKeyFilterAcceptsUniqueIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") - _ = try Person.filter(db, keys: [["id": nil]]) - _ = try Person.filter(db, keys: [["email": nil]]) - do { - _ = try Person.filter(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false) - XCTFail() - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_MISUSE) - XCTAssertEqual(error.message!, "table persons has no unique index on column(s) email, id") - XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id") - } - do { - _ = try Person.filter(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false) - XCTFail() - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .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") - } + _ = try Person.filter(keys: [["id": nil]]).fetchOne(db) + _ = try Person.filter(keys: [["email": nil]]).fetchOne(db) } } }