From 8afb44cdc0c4a5848a8aee998e44909d481b15ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Oct 2015 14:35:19 +0100 Subject: [PATCH] DatabaseTableMapping.fetch(_:primaryKeys:), DatabaseTableMapping.fetchAll(_:primaryKeys:) --- .../Core/Protocols/DatabaseTableMapping.swift | 78 +++++++++++++++---- GRDB/Core/SelectStatement.swift | 71 ++++++++--------- 2 files changed, 100 insertions(+), 49 deletions(-) diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index d21027083..277ad7464 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -16,16 +16,7 @@ public protocol DatabaseTableMapping : RowConvertible { extension DatabaseTableMapping { - /** - Fetches a single value by primary key. - - let person = Person.fetchOne(db, primaryKey: 123) // Person? - - - parameter db: A Database. - - parameter primaryKey: A value. - - returns: An optional value. - */ - public static func fetchOne(db: Database, primaryKey primaryKeyValue: DatabaseValueConvertible?) -> Self? { + private static func fetchByPrimaryKeyStatement(db: Database, primaryKeys: [DatabaseValueConvertible]) -> SelectStatement? { // Fail early if databaseTable is nil guard let databaseTableName = self.databaseTableName() else { fatalError("Nil returned from \(self).databaseTableName()") @@ -42,13 +33,72 @@ extension DatabaseTableMapping { fatalError("Primary key of table \(databaseTableName.quotedDatabaseIdentifier) is not made of a single column. See \(self).databaseTableName()") } - // Avoid performing a useless SELECT with NULL primary key - guard let primaryKeyValue = primaryKeyValue else { + // Avoid performing useless SELECT + guard primaryKeys.count > 0 else { return nil } - let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(columns.first!.quotedDatabaseIdentifier) = ?" - return fetchOne(db.selectStatement(sql), arguments: [primaryKeyValue]) + let questionMarks = Array(count: primaryKeys.count, repeatedValue: "?").joinWithSeparator(",") + let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(columns.first!.quotedDatabaseIdentifier) IN (\(questionMarks))" + let statement = db.selectStatement(sql) + statement.arguments = StatementArguments(primaryKeys.map { $0 }) + return statement + } + + /** + Fetches a sequence of values, given their primary keys. + + let persons = Person.fetch(db, primaryKeys:[1, 2, 3]) // DatabaseSequence + + The order of values in the sequence is undefined. + + - parameter db: A Database. + - parameter primaryKey: A value. + - returns: A sequence. + */ + public static func fetch(db: Database, primaryKeys: [DatabaseValueConvertible]) -> DatabaseSequence { + if let statement = self.fetchByPrimaryKeyStatement(db, primaryKeys: primaryKeys) { + return self.fetch(statement) + } else { + return DatabaseSequence() + } + } + + /** + Fetches an array of values, given their primary keys. + + let persons = Person.fetchAll(db, primaryKeys:[1, 2, 3]) // [Person] + + The order of values in the array is undefined. + + - parameter db: A Database. + - parameter primaryKey: A value. + - returns: An array. + */ + public static func fetchAll(db: Database, primaryKeys: [DatabaseValueConvertible]) -> [Self] { + if let statement = self.fetchByPrimaryKeyStatement(db, primaryKeys: primaryKeys) { + return self.fetchAll(statement) + } else { + return [] + } + } + + /** + Fetches a single value given its primary key. + + let person = Person.fetchOne(db, primaryKey: 123) // Person? + + - parameter db: A Database. + - parameter primaryKey: A value. + - returns: An optional value. + */ + public static func fetchOne(db: Database, primaryKey: DatabaseValueConvertible?) -> Self? { + let primaryKeys = primaryKey.map { [$0] } ?? [] + if let statement = self.fetchByPrimaryKeyStatement(db, primaryKeys: primaryKeys) { + return self.fetchOne(statement) + } else { + return nil + } } /** diff --git a/GRDB/Core/SelectStatement.swift b/GRDB/Core/SelectStatement.swift index a27450b8a..0fbad278e 100644 --- a/GRDB/Core/SelectStatement.swift +++ b/GRDB/Core/SelectStatement.swift @@ -59,19 +59,44 @@ public final class SelectStatement : Statement { A sequence of elements fetched from the database. */ public struct DatabaseSequence: SequenceType { - let statement: SelectStatement - let yield: () -> T + private let generateImpl: () -> DatabaseGenerator + + private init(statement: SelectStatement, yield: () -> T) { + generateImpl = { + let assertValidQueue = statement.database.assertValidQueue + let sqliteStatement = statement.sqliteStatement + + // Check that sequence is built on a valid database. + assertValidQueue() + + // DatabaseSequence can be restarted: + statement.reset() + + return DatabaseGenerator { + // Check that generator is used on a valid database. + assertValidQueue() + + let code = sqlite3_step(sqliteStatement) + switch code { + case SQLITE_DONE: + return nil + case SQLITE_ROW: + return yield() + default: + fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description) + } + } + } + } + + init() { + generateImpl = { return DatabaseGenerator { return nil } } + } /// Return a *generator* over the elements of this *sequence*. @warn_unused_result public func generate() -> DatabaseGenerator { - // Check that sequence is built on a valid database. - statement.database.assertValidQueue() - - // DatabaseSequence can be restarted: - statement.reset() - - return DatabaseGenerator(statement: statement, yield: yield) + return generateImpl() } } @@ -79,32 +104,8 @@ public struct DatabaseSequence: SequenceType { A generator of elements fetched from the database. */ public struct DatabaseGenerator: GeneratorType { - let statement: SelectStatement - let sqliteStatement: SQLiteStatement - let assertValidQueue: () -> () - let yield: () -> T - - init(statement: SelectStatement, yield: () -> T) { - self.statement = statement - self.sqliteStatement = statement.sqliteStatement - self.yield = yield - self.assertValidQueue = statement.database.assertValidQueue - } - - /// Advance to the next element and return it, or `nil` if no next - /// element exists. + private let nextImpl: () -> T? public func next() -> T? { - // Check that generator is used on a valid database. - assertValidQueue() - - let code = sqlite3_step(sqliteStatement) - switch code { - case SQLITE_DONE: - return nil - case SQLITE_ROW: - return yield() - default: - fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description) - } + return nextImpl() } }