mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
DatabaseRegion is now case-preserving and case-insensitive
This commit is contained in:
1 parent
c02901b335
commit
c0a3e61253
6 files changed
+126
-52
No files matched your search
@@ -421,14 +421,14 @@ extension Database {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table, in the main or temp schema.
|
||||
/// Returns the actual name of the database table, in the main or temp
|
||||
/// schema, or nil if the table does not exist.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
// SQLite has temporary tables shadow main ones
|
||||
try schema(.temp).canonicalName(tableName, ofType: .table)
|
||||
?? schema(.main).canonicalName(tableName, ofType: .table)
|
||||
?? { throw DatabaseError.noSuchTable(tableName) }()
|
||||
}
|
||||
|
||||
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
|
||||
|
||||
@@ -30,9 +30,9 @@
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
@@ -64,16 +64,20 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
public init(table: String) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
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<String>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
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<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
@@ -86,7 +90,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
@@ -105,6 +109,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
@@ -123,7 +128,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
@@ -148,26 +153,39 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation by removing views.
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// We can do it because modifications only happen in actual tables. And we
|
||||
/// want to do it because we have a fast path for regions that span a
|
||||
/// single table.
|
||||
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let mainViewNames = try db.schema(.main).names(ofType: .view)
|
||||
let tempViewNames = try db.schema(.temp).names(ofType: .view)
|
||||
let viewNames = mainViewNames.union(tempViewNames)
|
||||
guard viewNames.isEmpty == false else { return self }
|
||||
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
if let canonicalTableName = try db.canonicalTableName(table.rawValue) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: canonicalTableName)
|
||||
region.formUnion(DatabaseRegion(tableRegions: [table: tableRegion]))
|
||||
}
|
||||
}
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key)
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
@@ -194,7 +212,7 @@ extension DatabaseRegion {
|
||||
return true
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
guard let tableRegion = tableRegions[CaseInsensitiveIdentifier(rawValue: event.tableName)] else {
|
||||
// FTS4 (and maybe other virtual tables) perform unadvertised
|
||||
// changes. For example, an "INSERT INTO document ..." statement
|
||||
// advertises an insertion in the `document` table, but the
|
||||
@@ -242,11 +260,11 @@ extension DatabaseRegion {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
var desc = table
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
@@ -260,7 +278,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var columns: Set<CaseInsensitiveIdentifier>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
@@ -270,7 +288,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
let columnsIntersection: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case let (nil, columns), let (columns, nil):
|
||||
columnsIntersection = columns
|
||||
@@ -290,7 +308,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
let columnsUnion: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
|
||||
@@ -91,7 +91,7 @@ extension DatabaseRegionObservation {
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db).ignoringViews(db)
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
|
||||
@@ -161,9 +161,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
return selectedRegion
|
||||
}
|
||||
|
||||
// Database regions are case-sensitive: use the canonical table name
|
||||
let canonicalTableName = try db.canonicalTableName(tableName)
|
||||
return selectedRegion.tableIntersection(canonicalTableName, rowIds: rowIDs)
|
||||
return selectedRegion.tableIntersection(tableName, rowIds: rowIDs)
|
||||
}
|
||||
|
||||
/// If true, executing this query yields at most one row.
|
||||
|
||||
@@ -213,12 +213,7 @@ extension ValueObserver {
|
||||
|
||||
var region = DatabaseRegion()
|
||||
let result = try db.recordingSelection(®ion, fetch)
|
||||
|
||||
// SQLite does not expose views and schema changes to the
|
||||
// TransactionObserver protocol. By removing them from the observed
|
||||
// region, we optimize our TransactionObserver conformance.
|
||||
observedRegion = try region.ignoringViews(db).ignoringInternalSQLiteTables()
|
||||
|
||||
observedRegion = try region.observableRegion(db)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,7 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
DatabaseRegion.fullDatabase,
|
||||
DatabaseRegion(),
|
||||
DatabaseRegion(table: "foo"),
|
||||
DatabaseRegion(table: "FOO"), // selection info is case-sensitive on table name
|
||||
DatabaseRegion(table: "foo", columns: ["a", "b"]),
|
||||
DatabaseRegion(table: "foo", columns: ["A", "B"]), // selection info is case-sensitive on columns names
|
||||
DatabaseRegion(table: "foo", columns: ["b", "c"]),
|
||||
DatabaseRegion(table: "foo", rowIds: [1, 2]),
|
||||
DatabaseRegion(table: "foo", rowIds: [2, 3]),
|
||||
@@ -26,6 +24,14 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Case insensitivity
|
||||
XCTAssertEqual(
|
||||
DatabaseRegion(table: "foo"),
|
||||
DatabaseRegion(table: "FOO"))
|
||||
XCTAssertEqual(
|
||||
DatabaseRegion(table: "foo", columns: ["a", "b"]),
|
||||
DatabaseRegion(table: "FOO", columns: ["A", "B"]))
|
||||
}
|
||||
|
||||
func testRegionUnion() {
|
||||
@@ -243,15 +249,47 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(intersection.map(\.description), ["foo(a)[1]", "empty", "empty", "foo(b)[2]"])
|
||||
}
|
||||
|
||||
|
||||
func testSelectStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (id INTEGER, name TEXT)")
|
||||
try db.execute(sql: "CREATE TABLE bar (id INTEGER, fooId INTEGER)")
|
||||
try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)")
|
||||
try db.execute(sql: "CREATE TABLE bar (id INTEGER PRIMARY KEY, fooId INTEGER)")
|
||||
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id")
|
||||
// Select the rowid
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT id FROM foo")
|
||||
let expectedRegion = DatabaseRegion(table: "foo")
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(*)")
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT ID FROM FOO")
|
||||
let expectedRegion = DatabaseRegion(table: "foo")
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(*)")
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT name FROM foo")
|
||||
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"])
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(name)")
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT NAME FROM FOO")
|
||||
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"])
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(name)")
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT foo.name FROM foo JOIN bar ON fooId = foo.id")
|
||||
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"])
|
||||
.union(DatabaseRegion(table: "bar", columns: ["fooId"]))
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)")
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT FOO.NAME FROM FOO JOIN BAR ON FOOID = FOO.ID")
|
||||
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"])
|
||||
.union(DatabaseRegion(table: "bar", columns: ["fooId"]))
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
@@ -269,6 +307,18 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(*)")
|
||||
}
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM FOO")
|
||||
if sqlite3_libversion_number() < 3019000 {
|
||||
let expectedRegion = DatabaseRegion.fullDatabase
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "full database")
|
||||
} else {
|
||||
let expectedRegion = DatabaseRegion(table: "foo")
|
||||
XCTAssertEqual(statement.databaseRegion, expectedRegion)
|
||||
XCTAssertEqual(statement.databaseRegion.description, "FOO(*)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,16 +524,29 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
func testUpdateStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
|
||||
let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, bar TEXT, baz TEXT, qux TEXT)")
|
||||
do {
|
||||
let statement = try db.makeUpdateStatement(sql: "UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeUpdateStatement(sql: "UPDATE FOO SET BAR = 'bar', BAZ = 'baz' WHERE ID = 1")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user