From 4dfd672c045866c0d97880028bf964e4bdf7a744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Jan 2017 16:51:02 +0100 Subject: [PATCH] Compound unique keys: preserve index ordering in generated SQL queries --- GRDB/Core/Database.swift | 56 +++++++++++++--------- GRDB/Record/RowConvertible.swift | 12 +++-- GRDB/Record/TableMapping.swift | 12 +++-- Tests/Private/RecordUniqueIndexTests.swift | 8 ++-- 4 files changed, 51 insertions(+), 37 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 4c498644c..7ec7324cc 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1143,13 +1143,16 @@ extension Database { // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - if #available(iOS 8.2, OSX 10.10, *) { } else { - // Work around a bug in SQLite where PRAGMA table_info would - // return a result even after the table was deleted. - if try !tableExists(tableName) { - throw DatabaseError(message: "no such table: \(tableName)") + #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER + if #available(iOS 8.2, OSX 10.10, *) { + } else { + // Work around a bug in SQLite where PRAGMA table_info would + // return a result even after the table was deleted. + if try !tableExists(tableName) { + throw DatabaseError(message: "no such table: \(tableName)") + } } - } + #endif let columns = try ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") guard columns.count > 0 else { throw DatabaseError(message: "no such table: \(tableName)") @@ -1186,26 +1189,33 @@ extension Database { return indexes } + /// If there exists a unique key on columns, return the columns + /// ordered as the matching index (or primay key). Case of returned columns + /// is not guaranteed. + func columnsForUniqueKey(_ columns: [String], in tableName: String) throws -> [String]? { + let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist + let lowercasedColumns = Set(columns.map { $0.lowercased() }) + if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) { + // There is an explicit unique index on the columns + return index.columns + } + if let lowercasedColumn = lowercasedColumns.first, lowercasedColumns.count == 1 { + if let rowIDColumnName = primaryKey?.rowIDColumn, rowIDColumnName.lowercased() == lowercasedColumn { + // An explicit INTEGER PRIMARY KEY column is a unique key. + return [rowIDColumnName] + } + if try primaryKey == nil && ["rowid", "oid", "_rowid_"].contains(lowercasedColumn) && !self.columns(in: tableName).map({ $0.name.lowercased() }).contains(lowercasedColumn) { + // A rowid, oid or _rowid_ column is a unique key when there is no explicit primary key and the column is not already used. + return [lowercasedColumn] + } + } + return nil + } + /// True if a sequence of columns uniquely identifies a row, that is to say /// if the columns are the primary key, or if there is a unique index on them. public func table(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String { - let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist - let columns = Set(columns.map { $0.lowercased() }) - if try indexes(on: tableName).contains(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == columns }) { - // There is an explicit unique index on the columns - return true - } - if let column = columns.first, columns.count == 1 { - if let rowIDColumnName = primaryKey?.rowIDColumn, rowIDColumnName.lowercased() == column { - // An explicit INTEGER PRIMARY KEY column is a unique key. - return true - } - if try primaryKey == nil && ["rowid", "oid", "_rowid_"].contains(column) && !self.columns(in: tableName).map({ $0.name.lowercased() }).contains(column) { - // A rowid, oid or _rowid_ column is a unique key when there is no explicit primary key and the column is not already used. - return true - } - } - return false + return try columnsForUniqueKey(Array(columns), in: tableName) != nil } } diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/RowConvertible.swift index d0c5a6cf7..cbbbe5cb1 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/RowConvertible.swift @@ -452,9 +452,9 @@ extension RowConvertible where Self: TableMapping { var whereClauses: [String] = [] for dictionary in keys { GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary") - let columns = dictionary.keys - guard try db.table(databaseTableName, hasUniqueKey: columns) else { - let error = DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))") + let columns = Array(dictionary.keys) + guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else { + let error = DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))") if fatalErrorOnMissingUniqueIndex { // Programmer error fatalError(error.description) @@ -462,8 +462,10 @@ extension RowConvertible where Self: TableMapping { throw error } } - arguments.append(contentsOf: dictionary.values) - whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")") + arguments.append(contentsOf: orderedColumns.map { orderedColumn in + dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value + }) + whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")") } let whereClause = whereClauses.joined(separator: " OR ") diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index 3f847d3cc..5f3b56b37 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -204,17 +204,19 @@ extension TableMapping { var whereClauses: [String] = [] for dictionary in keys { GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary") - let columns = dictionary.keys - guard try db.table(databaseTableName, hasUniqueKey: columns) else { - let error = DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))") + let columns = Array(dictionary.keys) + guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else { + let error = DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))") if fatalErrorOnMissingUniqueIndex { fatalError(error.description) } else { throw error } } - arguments.append(contentsOf: dictionary.values) - whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")") + arguments.append(contentsOf: orderedColumns.map { orderedColumn in + dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value + }) + whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")") } let whereClause = whereClauses.joined(separator: " OR ") diff --git a/Tests/Private/RecordUniqueIndexTests.swift b/Tests/Private/RecordUniqueIndexTests.swift index 7620c9cb0..611b71810 100644 --- a/Tests/Private/RecordUniqueIndexTests.swift +++ b/Tests/Private/RecordUniqueIndexTests.swift @@ -28,8 +28,8 @@ class RecordUniqueIndexTests: GRDBTestCase { XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.code, 21) // SQLITE_MISUSE - XCTAssertEqual(error.message!, "table persons has no unique index on column(s) id, email") - XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) id, email") + 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.makeFetchByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false) @@ -56,8 +56,8 @@ class RecordUniqueIndexTests: GRDBTestCase { XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.code, 21) // SQLITE_MISUSE - XCTAssertEqual(error.message!, "table persons has no unique index on column(s) id, email") - XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) id, email") + 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.makeDeleteByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)