mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
#56: fetchOne(_:key:Dictionary) performs the same unique index check as deleteOne()
This commit is contained in:
1 parent
1141676223
commit
baff716ef6
5 files changed
+48
-31
No files matched your search
@@ -906,7 +906,7 @@ extension Database {
|
||||
|
||||
/// The indexes on table named `tableName`; throws if the table does
|
||||
/// not exist.
|
||||
func indexes(tableName: String) throws -> [IndexInfo] {
|
||||
func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
let indexes = Row.fetch(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
|
||||
let indexName: String = row.value(atIndex: 1)
|
||||
let unique: Bool = row.value(atIndex: 2)
|
||||
@@ -914,18 +914,27 @@ extension Database {
|
||||
.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)
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
if let primaryKeyColumns = try self.primaryKey(tableName)?.columns where indexes.all({ $0.columns != primaryKeyColumns }) {
|
||||
if let primaryKeyColumns = try primaryKey(tableName)?.columns where indexes.all({ $0.columns != primaryKeyColumns }) {
|
||||
// Only known case when the primary key is not listed in the
|
||||
// index_list pragma: the implicit index on INTEGER PRIMARY KEY.
|
||||
let pkIndex = IndexInfo(name: nil, columns: primaryKeyColumns, isUnique: true)
|
||||
let pkIndex = IndexInfo(name: nil, columns: primaryKeyColumns, unique: true)
|
||||
return [pkIndex] + indexes
|
||||
} else {
|
||||
return indexes
|
||||
}
|
||||
}
|
||||
|
||||
/// True if there exists a unique index on the provided table and columns;
|
||||
/// throws if the table does not exist.
|
||||
func hasUniqueIndex<T: SequenceType where T.Generator.Element == String>(on tableName: String, columns: T) throws -> Bool {
|
||||
let columns = Set(columns)
|
||||
return try indexes(on: tableName).contains { index in
|
||||
index.isUnique && index.columnsSet == columns
|
||||
}
|
||||
}
|
||||
|
||||
// CREATE TABLE persons (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
@@ -957,7 +966,15 @@ extension Database {
|
||||
/// nil when the index is the implicit index on INTEGER PRIMARY KEY column.
|
||||
let name: String?
|
||||
let columns: [String]
|
||||
let columnsSet: Set<String>
|
||||
let isUnique: Bool
|
||||
|
||||
init(name: String?, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.columnsSet = Set(columns)
|
||||
self.isUnique = unique
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,15 +107,9 @@ extension SequenceType where Generator.Element: Equatable {
|
||||
}
|
||||
|
||||
extension SequenceType {
|
||||
/// Return true if one element matches the predicate
|
||||
func any(predicate: (Generator.Element -> Bool)) -> Bool {
|
||||
for element in self where predicate(element) { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
func all(predicate: (Generator.Element -> Bool)) -> Bool {
|
||||
for element in self where !predicate(element) { return false }
|
||||
return true
|
||||
@warn_unused_result
|
||||
func all(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool {
|
||||
return try !contains { try !predicate($0) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -555,7 +555,7 @@ private class FetchedChangesController<Record: RowConvertible, T> {
|
||||
}
|
||||
#else
|
||||
// Look for a row difference
|
||||
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).any({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
|
||||
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).contains({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
|
||||
return
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -205,7 +205,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: A sequence of records.
|
||||
@warn_unused_result
|
||||
public static func fetch(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
|
||||
guard let statement = fetchByKeyStatement(db, keys: keys) else {
|
||||
guard let statement = try! fetchByKeyStatement(db, keys: keys) else {
|
||||
return DatabaseSequence.emptySequence(db)
|
||||
}
|
||||
return fetch(statement)
|
||||
@@ -223,7 +223,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An array of records.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] {
|
||||
guard let statement = fetchByKeyStatement(db, keys: keys) else {
|
||||
guard let statement = try! fetchByKeyStatement(db, keys: keys) else {
|
||||
return []
|
||||
}
|
||||
return fetchAll(statement)
|
||||
@@ -239,28 +239,32 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An optional record.
|
||||
@warn_unused_result
|
||||
public static func fetchOne(db: Database, key: [String: DatabaseValueConvertible?]) -> Self? {
|
||||
return fetchOne(fetchByKeyStatement(db, keys: [key])!)
|
||||
return try! fetchOne(fetchByKeyStatement(db, keys: [key])!)
|
||||
}
|
||||
|
||||
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
@warn_unused_result
|
||||
private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? {
|
||||
private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> SelectStatement? {
|
||||
// Avoid performing useless SELECT
|
||||
guard keys.count > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName()
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = dictionary.keys
|
||||
guard try db.hasUniqueIndex(on: databaseTableName, columns: columns) else {
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joinWithSeparator(", "))")
|
||||
}
|
||||
arguments.appendContentsOf(dictionary.values)
|
||||
whereClauses.append("(" + (dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joinWithSeparator(" AND ") + ")")
|
||||
whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joinWithSeparator(" AND ") + ")")
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName()
|
||||
let whereClause = whereClauses.joinWithSeparator(" OR ")
|
||||
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
|
||||
let statement = try! db.selectStatement(sql)
|
||||
@@ -315,16 +319,14 @@ extension TableMapping {
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName()
|
||||
let uniqueColumnSets = try Set(db.indexes(databaseTableName).filter { $0.isUnique }.map { Set($0.columns) })
|
||||
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = dictionary.keys
|
||||
guard uniqueColumnSets.contains(Set(columns)) else {
|
||||
guard try db.hasUniqueIndex(on: databaseTableName, columns: 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 ") + ")")
|
||||
}
|
||||
|
||||
@@ -10,16 +10,19 @@ import XCTest
|
||||
// Item has no primary key.
|
||||
private class Item : Record {
|
||||
var name: String?
|
||||
var email: String?
|
||||
|
||||
init(name: String? = nil) {
|
||||
init(name: String? = nil, email: String? = nil) {
|
||||
self.name = name
|
||||
self.email = email
|
||||
super.init()
|
||||
}
|
||||
|
||||
static func setupInDatabase(db: Database) throws {
|
||||
try db.execute(
|
||||
"CREATE TABLE items (" +
|
||||
"name NOT NULL" +
|
||||
"name TEXT," +
|
||||
"email TEXT UNIQUE" +
|
||||
")")
|
||||
}
|
||||
|
||||
@@ -31,11 +34,12 @@ private class Item : Record {
|
||||
|
||||
required init(_ row: Row) {
|
||||
name = row.value(named: "name")
|
||||
email = row.value(named: "email")
|
||||
super.init(row)
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
return ["name": name]
|
||||
return ["name": name, "email": email]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,15 +88,15 @@ class PrimaryKeyNoneTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Select
|
||||
|
||||
func testSelectWithKey() {
|
||||
func testFetchOneWithKey() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Item(name: "Table")
|
||||
let record = Item(email: "item@example.com")
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = Item.fetchOne(db, key: ["name": record.name])!
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
let fetchedRecord = Item.fetchOne(db, key: ["email": record.email])!
|
||||
XCTAssertTrue(fetchedRecord.email == record.email)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user