Compound unique keys: preserve index ordering in generated SQL queries

This commit is contained in:
Gwendal Roué committed 2017-01-22 16:51:02 +01:00
1 parent d8b64aa2f4
commit 4dfd672c04
4 files changed
+51 -37

No files matched your search

+33 -23
View File
@@ -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<T: Sequence>(_ 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
}
}
+7 -5
View File
@@ -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 ")
+7 -5
View File
@@ -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 ")
+4 -4
View File
@@ -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)