From 938977bbca1480f83de9252f8e8171f7ec8f01f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 16 Jan 2018 13:58:55 +0100 Subject: [PATCH] Cleanup DatabaseRegion: no more public intersection, no more public way to specify rowids --- CHANGELOG.md | 7 - GRDB/Core/Database+Schema.swift | 32 +-- GRDB/Core/DatabaseRegion.swift | 193 ++++++++---------- GRDB/Core/DatabaseSchemaCache.swift | 24 ++- .../QueryInterfaceSelectQueryDefinition.swift | 5 +- 5 files changed, 127 insertions(+), 134 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20182e1e3..1ce4df633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,10 +33,7 @@ Release Notes +struct DatabaseRegion: Equatable { + var isEmpty: Bool + -+ func intersection(_ other: DatabaseRegion) -> DatabaseRegion + func union(_ other: DatabaseRegion) -> DatabaseRegion -+ -+ mutating func formIntersection(_ other: DatabaseRegion) + mutating func formUnion(_ other: DatabaseRegion) + + func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool @@ -52,10 +49,6 @@ Release Notes + @available(*, deprecated, renamed:"region") + var selectionInfo: DatabaseRegion } - - class Database { -+ func region(rowIds: Set, in tableName: String) throws -> DatabaseRegion - } enum DatabaseEventKind { - func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index b22a6127f..6038c9743 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -216,21 +216,25 @@ extension Database { return foreignKeys } - /// Returns a region that contains the given rows in the given table: - /// - /// dbQueue.inDatabase { db in - /// let region = db.region(rowIds: [1, 2], in: "players") - /// print(egion) - /// // prints "players(*)[1, 2]" - /// } - /// - /// - throws: A DatabaseError if table does not exist. - public func region(rowIds: Set, in tableName: String) throws -> DatabaseRegion { - // TODO: improves this. - guard let canonicalTableName = try String.fetchOne(self, "SELECT name FROM (SELECT name, type FROM sqlite_master UNION SELECT name, type FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) else { - throw DatabaseError(message: "table does not exist") + /// Returns the actual name of the database table + func canonicalName(table: String) throws -> String { + if let canonicalName = schemaCache.canonicalName(table: table) { + return canonicalName } - return DatabaseRegion(table: canonicalTableName, rowIds: rowIds) + + guard let canonicalName = try String.fetchOne(self, """ + SELECT name FROM ( + SELECT name, type FROM sqlite_master + UNION + SELECT name, type FROM sqlite_temp_master) + WHERE type = 'table' AND LOWER(name) = ? + """, arguments: [table.lowercased()]) + else { + throw DatabaseError(message: "no such table: \(table)") + } + + schemaCache.set(canonicalName: canonicalName, forTable: table) + return canonicalName } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index f7dd7b062..f6b44aaf2 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -1,32 +1,17 @@ -/// DatabaseRegion defines a region in the database, that is to say tables, -/// columns, and rows (identified by their rowids). DatabaseRegion is dedicated +/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated /// to help transaction observers recognize impactful database changes in their /// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods. /// -/// A region can represent a full table, a column, or a row: +/// A database region is the union of any number of "table regions", which can +/// cover a full table, or the combination of columns and rows (identified by +/// their rowids): /// -/// | T | | U | | V | -/// |-----| |-----| |-----| -/// |x|x|x| |x| | | | | | | -/// |x|x|x| |x| | | |x|x|x| -/// |x|x|x| |x| | | | | | | -/// |x|x|x| |x| | | | | | | -/// -/// Unions and intersections of regions create more complex regions: -/// -/// | T | | U | | T | | U | -/// |-----| |-----| |-----| |-----| -/// | | | | + |x| | | = | | | | |x| | | -/// |x| | | |x| | | |x| | | |x| | | -/// | | | | |x| | | | | | | |x| | | -/// | | | | |x| | | | | | | |x| | | -/// -/// | T | | T | | T | -/// |-----| |-----| |-----| -/// |x| | | * | | | | = | | | | -/// |x| | | |x|x|x| |x| | | -/// |x| | | | | | | | | | | -/// |x| | | | | | | | | | | +/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | +/// |-------| |-------| |-------| |-------| |-------| +/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | +/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// /// You don't create a database region directly. Instead, you use one of /// those methods: @@ -43,115 +28,109 @@ /// try print(request.region(db)) /// // prints "players(*)[1]" /// -/// - `Database.region(rowIds:in:)` -/// -/// try print(db.region(rowIds: [1, 2], in: "players") -/// // prints "players(*)[1, 2]" +/// Database regions returned by requests can be more precise than regions +/// returned by select statements. public struct DatabaseRegion { - private let tables: [String: TableRegion]? - private init(tables: [String: TableRegion]?) { - self.tables = tables + private let tableRegions: [String: TableRegion]? + private init(tableRegions: [String: TableRegion]?) { + self.tableRegions = tableRegions } /// Returns whether the region is empty. public var isEmpty: Bool { - guard let tables = tables else { return false } - return tables.isEmpty + guard let tableRegions = tableRegions else { return false } + return tableRegions.isEmpty } /// The full database: (All columns in all tables) × (all rows) - static let fullDatabase = DatabaseRegion(tables: nil) + static let fullDatabase = DatabaseRegion(tableRegions: nil) /// The empty region init() { - self.init(tables: [:]) + self.init(tableRegions: [:]) } /// A full table: (all columns in the table) × (all rows) init(table: String) { - self.init(tables: [table: TableRegion(columns: nil, rowIds: nil)]) + self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)]) } /// Full columns in a table: (some columns in a table) × (all rows) init(table: String, columns: Set) { - self.init(tables: [table: TableRegion(columns: columns, rowIds: nil)]) + self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)]) } /// Full rows in a table: (all columns in a table) × (some rows) init(table: String, rowIds: Set) { - self.init(tables: [table: TableRegion(columns: nil, rowIds: rowIds)]) + self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)]) } /// Returns the intersection of this region and the given one. /// - /// | T | | T | | T | - /// |-----| |-----| |-----| - /// |x| | | * | | | | = | | | | - /// |x| | | |x|x|x| |x| | | - /// |x| | | | | | | | | | | - /// |x| | | | | | | | | | | - public func intersection(_ other: DatabaseRegion) -> DatabaseRegion { - guard let tables = tables else { return other } - guard let otherTables = other.tables else { return self } + /// This method is not public because there is no known public use case for + /// this intersection. It is currently only used as support for + /// the isModified(byEventsOfKind:) method. + func intersection(_ other: DatabaseRegion) -> DatabaseRegion { + guard let tableRegions = tableRegions else { return other } + guard let otherTableRegions = other.tableRegions else { return self } - var tablesIntersection: [String: TableRegion] = [:] - for (table, tableInfo) in tables { - guard let otherTableInfo = otherTables + var tableRegionsIntersection: [String: TableRegion] = [:] + for (table, tableRegion) in tableRegions { + guard let otherTableRegion = otherTableRegions .first(where: { (otherTable, _) in otherTable == table })? .value else { continue } - let tableInfoIntersection = tableInfo.intersection(otherTableInfo) - guard !tableInfoIntersection.isEmpty else { continue } - tablesIntersection[table] = tableInfoIntersection + let tableRegionIntersection = tableRegion.intersection(otherTableRegion) + guard !tableRegionIntersection.isEmpty else { continue } + tableRegionsIntersection[table] = tableRegionIntersection } - return DatabaseRegion(tables: tablesIntersection) + return DatabaseRegion(tableRegions: tableRegionsIntersection) + } + + /// Only keeps those rowIds in the given table + func tableIntersection(_ table: String, rowIds: Set) -> DatabaseRegion { + guard var tableRegions = tableRegions else { + return DatabaseRegion(table: table, rowIds: rowIds) + } + + guard let tableRegion = tableRegions[table] else { + return self + } + + let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds)) + if intersection.isEmpty { + tableRegions.removeValue(forKey: table) + } else { + tableRegions[table] = intersection + } + return DatabaseRegion(tableRegions: tableRegions) } /// Returns the union of this region and the given one. - /// - /// | T | | T | | T | - /// |-----| |-----| |-----| - /// |x| | | + | |x| | = |x|x| | - /// |x| | | | |x| | |x|x| | - /// |x| | | | |x| | |x|x| | - /// |x| | | | |x| | |x|x| | public func union(_ other: DatabaseRegion) -> DatabaseRegion { - guard let tables = tables else { return .fullDatabase } - guard let otherTables = other.tables else { return .fullDatabase } + guard let tableRegions = tableRegions else { return .fullDatabase } + guard let otherTableRegions = other.tableRegions else { return .fullDatabase } - var tablesUnion: [String: TableRegion] = [:] - let tableNames = Set(tables.map { $0.key }).union(Set(otherTables.map { $0.key })) + var tableRegionsUnion: [String: TableRegion] = [:] + let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key })) for table in tableNames { - let tableInfo = tables[table] - let otherTableInfo = otherTables[table] - let tableInfoUnion: TableRegion - switch (tableInfo, otherTableInfo) { + let tableRegion = tableRegions[table] + let otherTableRegion = otherTableRegions[table] + let tableRegionUnion: TableRegion + switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() - case (nil, let tableInfo?), (let tableInfo?, nil): - tableInfoUnion = tableInfo - case (let tableInfo?, let otherTableInfo?): - tableInfoUnion = tableInfo.union(otherTableInfo) + case (nil, let tableRegion?), (let tableRegion?, nil): + tableRegionUnion = tableRegion + case (let tableRegion?, let otherTableRegion?): + tableRegionUnion = tableRegion.union(otherTableRegion) } - tablesUnion[table] = tableInfoUnion + tableRegionsUnion[table] = tableRegionUnion } - return DatabaseRegion(tables: tablesUnion) + return DatabaseRegion(tableRegions: tableRegionsUnion) } - - /// Removes the table, columns, and rows in the given region that are not - /// in this region. - /// - /// | T | | T | | T | - /// |-----| |-----| |-----| - /// |x| | | * | | | | = | | | | - /// |x| | | |x|x|x| |x| | | - /// |x| | | | | | | | | | | - /// |x| | | | | | | | | | | - public mutating func formIntersection(_ other: DatabaseRegion) { - self = intersection(other) - } - + /// Inserts the given region into this region /// /// | T | | T | | T | @@ -181,11 +160,11 @@ extension DatabaseRegion { /// in the TransactionObserver.observes(eventsOfKind:) method, by calling /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { - guard let tables = tables else { + guard let tableRegions = tableRegions else { return true } - switch tables.count { + switch tableRegions.count { case 1: // The precondition applies here: // @@ -193,17 +172,17 @@ extension DatabaseRegion { // filtering of events performed in observes(eventsOfKind:), the // event argument is guaranteed to be about the fetched table. // We thus only have to check for rowIds. - assert(event.tableName == tables[tables.startIndex].key) // sanity check - guard let rowIds = tables[tables.startIndex].value.rowIds else { + assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check + guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else { return true } return rowIds.contains(event.rowID) default: - guard let tableInfo = tables[event.tableName] else { + guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") } - guard let rowIds = tableInfo.rowIds else { + guard let rowIds = tableRegion.rowIds else { return true } return rowIds.contains(event.rowID) @@ -213,17 +192,17 @@ extension DatabaseRegion { extension DatabaseRegion: Equatable { public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool { - switch (lhs.tables, rhs.tables) { + switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true - case (let ltables?, let rtables?): - let ltableNames = Set(ltables.map { $0.key }) - let rtableNames = Set(rtables.map { $0.key }) + case (let ltableRegions?, let rtableRegions?): + let ltableNames = Set(ltableRegions.map { $0.key }) + let rtableNames = Set(rtableRegions.map { $0.key }) guard ltableNames == rtableNames else { return false } for tableName in ltableNames { - if ltables[tableName]! != rtables[tableName]! { + if ltableRegions[tableName]! != rtableRegions[tableName]! { return false } } @@ -236,22 +215,22 @@ extension DatabaseRegion: Equatable { extension DatabaseRegion: CustomStringConvertible { public var description: String { - guard let tables = tables else { + guard let tableRegions = tableRegions else { return "full database" } - if tables.isEmpty { + if tableRegions.isEmpty { return "empty" } - return tables + return tableRegions .sorted(by: { (l, r) in l.key < r.key }) - .map { (table, tableInfo) in + .map { (table, tableRegion) in var desc = table - if let columns = tableInfo.columns { + if let columns = tableRegion.columns { desc += "(" + columns.sorted().joined(separator: ",") + ")" } else { desc += "(*)" } - if let rowIds = tableInfo.rowIds { + if let rowIds = tableRegion.rowIds { desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]" } return desc diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index a344c81c3..46d57e51c 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -2,6 +2,9 @@ protocol DatabaseSchemaCache { mutating func clear() + func canonicalName(table: String) -> String? + mutating func set(canonicalName: String, forTable table: String) + func primaryKey(_ table: String) -> PrimaryKeyInfo? mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) @@ -17,18 +20,28 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { + private var canonicalNames: [String: String] = [:] private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] private var foreignKeys: [String: [ForeignKeyInfo]] = [:] mutating func clear() { + canonicalNames = [:] primaryKeys = [:] columns = [:] indexes = [:] foreignKeys = [:] } + func canonicalName(table: String) -> String? { + return canonicalNames[table] + } + + mutating func set(canonicalName: String, forTable table: String) { + canonicalNames[table] = table + } + func primaryKey(_ table: String) -> PrimaryKeyInfo? { return primaryKeys[table] } @@ -66,15 +79,18 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { func clear() { } + func canonicalName(table: String) -> String? { return nil } + func set(canonicalName: String, forTable table: String) { } + func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } - mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } + func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } func columns(in table: String) -> [ColumnInfo]? { return nil } - mutating func set(columns: [ColumnInfo], forTable table: String) { } + func set(columns: [ColumnInfo], forTable table: String) { } func indexes(on table: String) -> [IndexInfo]? { return nil } - mutating func set(indexes: [IndexInfo], forTable table: String) { } + func set(indexes: [IndexInfo], forTable table: String) { } func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil } - mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { } + func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { } } diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift index 50c7d3dc0..89f5f9248 100644 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift @@ -212,8 +212,9 @@ extension QueryInterfaceSelectQueryDefinition : Request { return region } - // Intersect - return try region.intersection(db.region(rowIds: rowIds, in: tableName)) + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalName(table: tableName) + return region.tableIntersection(canonicalTableName, rowIds: rowIds) } private var countQuery: QueryInterfaceSelectQueryDefinition {