DatabaseTableMapping.fetch(_:primaryKeys:), DatabaseTableMapping.fetchAll(_:primaryKeys:)

This commit is contained in:
Gwendal Roué committed 2015-10-26 14:35:19 +01:00
1 parent a1848e7594
commit 8afb44cdc0
2 files changed
+100 -49

No files matched your search

+64 -14
View File
@@ -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<Person>
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<Self> {
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
}
}
/**
+36 -35
View File
@@ -59,19 +59,44 @@ public final class SelectStatement : Statement {
A sequence of elements fetched from the database.
*/
public struct DatabaseSequence<T>: SequenceType {
let statement: SelectStatement
let yield: () -> T
private let generateImpl: () -> DatabaseGenerator<T>
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<T> {
// 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<T>: SequenceType {
A generator of elements fetched from the database.
*/
public struct DatabaseGenerator<T>: 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()
}
}