Database schema cache distinguishes the main from the temp schema

Addresses https://github.com/groue/GRDB.swift/pull/946#issuecomment-805756799
This commit is contained in:
Gwendal Roué committed 2021-03-27 14:50:25 +01:00
1 parent f6f4839e07
commit b13922b76e
13 files changed
+386 -139

No files matched your search

+186 -71
View File
@@ -1,4 +1,49 @@
extension Database {
/// A SQLite schema. See https://sqlite.org/lang_naming.html
enum SchemaIdentifier: Hashable {
/// The main database
case main
/// The temp database
case temp
// Future support for attached database: https://sqlite.org/lang_attach.html
// case attached(String)
/// The name of the schema in SQL queries
var sql: String {
switch self {
case .main: return "main"
case .temp: return "temp"
}
}
/// The name of the master sqlite table
var masterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main: return "sqlite_master"
case .temp: return "sqlite_temp_master"
}
}
}
/// A table identifier
struct TableIdentifier {
/// The SQLite schema
var schemaID: SchemaIdentifier
/// The table name
var name: String
/// Returns the receiver, quoted for safe insertion as an identifier in
/// an SQL query.
///
/// // SELECT * FROM temp.player
/// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)")
var quotedDatabaseIdentifier: String {
"\(schemaID.sql).\(name.quotedDatabaseIdentifier)"
}
}
// MARK: - Database Schema
@@ -28,9 +73,13 @@ extension Database {
}
}
/// Returns whether a table exists.
/// Returns whether a table exists in the main or temp schema.
public func tableExists(_ name: String) throws -> Bool {
try exists(type: .table, name: name)
try exists(type: .table, name: name, in: .main) || exists(type: .table, name: name, in: .temp)
}
private func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
}
/// Returns whether a table is an internal SQLite table.
@@ -73,26 +122,26 @@ extension Database {
Self.isGRDBInternalTable(tableName)
}
/// Returns whether a view exists.
/// Returns whether a view exists in the main or temp schema.
public func viewExists(_ name: String) throws -> Bool {
try exists(type: .view, name: name)
try exists(type: .view, name: name, in: .main) || exists(type: .view, name: name, in: .temp)
}
/// Returns whether a trigger exists.
/// Returns whether a trigger exists in the main or temp schema.
public func triggerExists(_ name: String) throws -> Bool {
try exists(type: .trigger, name: name)
try exists(type: .trigger, name: name, in: .main) || exists(type: .trigger, name: name, in: .temp)
}
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
let name = name.lowercased()
return try schema()
return try schema(schemaID)
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`.
/// The primary key for table named `tableName`, in the main or temp schema.
///
/// All tables have a primary key, even when it is not explicit. When a
/// table has no explicit primary key, the result is the hidden
@@ -100,10 +149,18 @@ extension Database {
///
/// - throws: A DatabaseError if table does not exist.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
// SQLite has temporary tables shadow main ones
try primaryKey(TableIdentifier(schemaID: .temp, name: tableName))
?? primaryKey(TableIdentifier(schemaID: .main, name: tableName))
?? { throw DatabaseError.noSuchTable(tableName) }()
}
/// Returns nil if table does not exist
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
SchedulingWatchdog.preconditionValidQueue(self)
if let primaryKey = schemaCache.primaryKey(tableName) {
return primaryKey
if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) {
return primaryKey.value
}
// https://www.sqlite.org/pragma.html
@@ -130,7 +187,11 @@ extension Database {
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let columns = try self.columns(in: tableName)
guard let columns = try self.columns(in: table) else {
// table does not exist
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
return nil
}
let primaryKey: PrimaryKeyInfo
let pkColumns = columns
@@ -168,14 +229,14 @@ extension Database {
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
} else {
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(tableName))
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(tableName))
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
}
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
return primaryKey
}
@@ -186,18 +247,21 @@ extension Database {
}
/// Returns whether the table has a rowid column.
private func tableHasRowID(_ tableName: String) throws -> Bool {
///
/// - precondition: table exists.
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
// Not need to cache the result, because this information feeds
// `PrimaryKeyInfo`, which is cached.
do {
_ = try makeSelectStatement(sql: "SELECT rowid FROM \(tableName.quotedDatabaseIdentifier)")
#warning("TODO: change query in order to better understand why it enters the error log")
_ = try makeSelectStatement(sql: "SELECT rowid FROM \(table.quotedDatabaseIdentifier)")
return true
} catch DatabaseError.SQLITE_ERROR {
return false
}
}
/// The indexes on table named `tableName`.
/// The indexes on table named `tableName`, in the main or temp schema.
///
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
@@ -207,21 +271,33 @@ extension Database {
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// `table(_:hasUniqueKey:)` instead.
///
/// - throws: A DatabaseError if table does not exist.
public func indexes(on tableName: String) throws -> [IndexInfo] {
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
// SQLite has temporary tables shadow main ones
try indexes(on: TableIdentifier(schemaID: .temp, name: tableName))
?? indexes(on: TableIdentifier(schemaID: .main, name: tableName))
?? { throw DatabaseError.noSuchTable(tableName) }()
}
/// Returns nil if table does not exist
private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? {
if let indexes = schemaCache[table.schemaID].indexes(on: table.name) {
return indexes.value
}
let indexes = try Row
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))")
.compactMap { row -> IndexInfo? in
let indexName: String = row[1]
let unique: Bool = row[2]
let indexInfoRows = try Row
// [seqno:0 cid:2 name:"column"]
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier))
""")
// Sort by rank
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
var columns: [String] = []
@@ -243,12 +319,13 @@ extension Database {
if indexes.isEmpty {
// PRAGMA index_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
if try tableExists(table) == false {
schemaCache[table.schemaID].set(indexes: .missing, forTable: table.name)
return nil
}
}
schemaCache.set(indexes: indexes, forTable: tableName)
schemaCache[table.schemaID].set(indexes: .value(indexes), forTable: table.name)
return indexes
}
@@ -263,17 +340,30 @@ extension Database {
try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
/// The foreign keys defined on table named `tableName`.
/// The foreign keys defined on table named `tableName`, in the main or temp schema.
///
/// - throws: A DatabaseError if table does not exist.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
return foreignKeys
// SQLite has temporary tables shadow main ones
try foreignKeys(on: TableIdentifier(schemaID: .temp, name: tableName))
?? foreignKeys(on: TableIdentifier(schemaID: .main, name: tableName))
?? { throw DatabaseError.noSuchTable(tableName) }()
}
/// Returns nil if table does not exist
private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? {
if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) {
return foreignKeys.value
}
var rawForeignKeys: [(
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
for row in try Row.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier))
""")
{
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
@@ -295,8 +385,9 @@ extension Database {
if rawForeignKeys.isEmpty {
// PRAGMA foreign_key_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
if try tableExists(table) == false {
schemaCache[table.schemaID].set(foreignKeys: .missing, forTable: table.name)
return nil
}
}
@@ -319,36 +410,46 @@ extension Database {
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
}
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name)
return foreignKeys
}
/// Returns the actual name of the database table
/// Returns the actual name of the database table, in the main or temp schema.
///
/// - throws: A DatabaseError if table does not exist.
func canonicalTableName(_ tableName: String) throws -> String {
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
throw DatabaseError(message: "no such table: \(tableName)")
}
return name
// 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() throws -> SchemaInfo {
if let schemaInfo = schemaCache.schemaInfo {
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
if let schemaInfo = schemaCache[schemaID].schemaInfo {
return schemaInfo
}
let schemaInfo = try SchemaInfo(self)
schemaCache.schemaInfo = schemaInfo
let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName)
schemaCache[schemaID].schemaInfo = schemaInfo
return schemaInfo
}
}
extension Database {
/// The columns in the table named `tableName`
/// The columns in the table named `tableName`, in the main or temp schema.
///
/// - throws: A DatabaseError if table does not exist.
public func columns(in tableName: String) throws -> [ColumnInfo] {
if let columns = schemaCache.columns(in: tableName) {
return columns
// SQLite has temporary tables shadow main ones
try columns(in: TableIdentifier(schemaID: .temp, name: tableName))
?? columns(in: TableIdentifier(schemaID: .main, name: tableName))
?? { throw DatabaseError.noSuchTable(tableName) }()
}
/// Returns nil if table does not exist
private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? {
if let columns = schemaCache[table.schemaID].columns(in: table.name) {
return columns.value
}
// https://www.sqlite.org/pragma.html
@@ -396,27 +497,35 @@ extension Database {
if sqlite3_libversion_number() < 3008005 {
// 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 try !tableExists(table) {
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
return nil
}
}
columnInfoQuery = "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))"
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))"
} else {
// For our purposes, we look for generated columns, not hidden
// columns. The "hidden" column magic numbers come from the SQLite
// source code. The values 2 and 3 refer to virtual and stored
// generated columns, respectively. Search for COLFLAG_VIRTUAL in
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
columnInfoQuery = "SELECT * FROM pragma_table_xinfo('\(tableName)') WHERE hidden IN (0,2,3)"
// Use PRAGMA table_xinfo so that we can load generated columns
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
}
let columns = try ColumnInfo
.fetchAll(self, sql: columnInfoQuery)
.filter {
// Purpose: keep generated columns, but discard hidden ones.
// The "hidden" column magic numbers come from the SQLite
// source code. The values 2 and 3 refer to virtual and stored
// generated columns, respectively, and 1 refer to hidden one.
// Search for COLFLAG_HIDDEN in
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
$0.hidden != 1
}
.sorted(by: { $0.cid < $1.cid })
if columns.isEmpty {
throw DatabaseError(message: "no such table: \(tableName)")
// Table does not exist
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
return nil
}
schemaCache.set(columns: columns, forTable: tableName)
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
return columns
}
@@ -461,22 +570,29 @@ extension Database {
/// A column of a database table.
///
/// This type closely matches the information returned by the
/// `table_info` pragma.
/// `table_info` and `table_xinfo` pragmas.
///
/// > CREATE TABLE player (
/// id INTEGER PRIMARY KEY,
/// firstName TEXT,
/// lastName TEXT)
/// > PRAGMA table_info("player")
/// cid name type notnull dflt_value pk
/// ---- ----- ------- -------- ---------- ---
/// 0 id INTEGER 0 NULL 1
/// 1 name TEXT 0 NULL 0
/// 2 score INTEGER 0 NULL 0
/// sqlite> CREATE TABLE player (
/// ...> id INTEGER PRIMARY KEY,
/// ...> firstName TEXT,
/// ...> lastName TEXT);
/// sqlite> PRAGMA table_info(player);
/// cid name type notnull dflt_value pk
/// ------ ---------- ---------- ---------- ---------- -----
/// 0 id INTEGER 0 1
/// 1 firstName TEXT 0 0
/// 2 lastName TEXT 0 0
/// sqlite> PRAGMA table_xinfo(player);
/// cid name type notnull dflt_value pk hidden
/// ------ ---------- ---------- ---------- ---------- ----- ----------
/// 0 id INTEGER 0 1 0
/// 1 firstName TEXT 0 0 0
/// 2 lastName TEXT 0 0 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo: FetchableRecord {
let cid: Int
let hidden: Int?
/// The column name
public let name: String
@@ -533,6 +649,7 @@ public struct ColumnInfo: FetchableRecord {
isNotNull = row["notnull"]
defaultValueSQL = row["dflt_value"]
primaryKeyIndex = row["pk"]
hidden = row["hidden"]
}
}
@@ -719,11 +836,10 @@ enum SchemaObjectType: String {
struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
objects = try Set(SchemaObject.fetchCursor(db, sql: """
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
SELECT type, name, tbl_name, sql FROM \(masterTableName)
"""))
}
@@ -750,6 +866,5 @@ struct SchemaInfo: Equatable {
var name: String
var tbl_name: String?
var sql: String?
var isTemporary: Bool
}
}
+30 -4
View File
@@ -125,8 +125,36 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Internal properties
// Caches
struct SchemaCache {
/// The cache for the main schema
fileprivate var main = DatabaseSchemaCache()
/// The cache for the temp schema
fileprivate var temp = DatabaseSchemaCache()
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
get {
switch schemaID {
case .main: return main
case .temp: return temp
}
}
set {
switch schemaID {
case .main: main = newValue
case .temp: temp = newValue
}
}
}
mutating func clear() {
main.clear()
temp.clear()
}
}
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
var schemaCache = SchemaCache()
lazy var internalStatementCache = StatementCache(database: self)
lazy var publicStatementCache = StatementCache(database: self)
@@ -170,13 +198,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
init(
path: String,
description: String,
configuration: Configuration,
schemaCache: DatabaseSchemaCache) throws
configuration: Configuration) throws
{
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaCache = schemaCache
}
deinit {
+4
View File
@@ -251,6 +251,10 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
static func noSuchTable(_ tableName: String) -> Self {
DatabaseError(message: "no such table: \(tableName)")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
-2
View File
@@ -42,7 +42,6 @@ public final class DatabasePool: DatabaseWriter {
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "writer")
@@ -60,7 +59,6 @@ public final class DatabasePool: DatabaseWriter {
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
})
-2
View File
@@ -36,7 +36,6 @@ public final class DatabaseQueue: DatabaseWriter {
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
setupSuspension()
@@ -60,7 +59,6 @@ public final class DatabaseQueue: DatabaseWriter {
writer = try! SerializedDatabase(
path: ":memory:",
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
}
+3 -1
View File
@@ -155,7 +155,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
/// single table.
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
let viewNames = try db.schema().names(ofType: .view)
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)
+32 -12
View File
@@ -1,10 +1,30 @@
/// A thread-unsafe database schema cache
struct DatabaseSchemaCache {
/// A cached value
///
/// We cache both hits and misses, because we often query both the temp
/// schema and the main schema: not remembering misses would have us
/// perform too many database queries.
enum Presence<T> {
/// Value does not exist in the schema.
case missing
/// Value exists in the schema.
case value(T)
var value: T? {
switch self {
case .missing: return nil
case let .value(value): return value
}
}
}
var schemaInfo: SchemaInfo?
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
private var primaryKeys: [String: Presence<PrimaryKeyInfo>] = [:]
private var columns: [String: Presence<[ColumnInfo]>] = [:]
private var indexes: [String: Presence<[IndexInfo]>] = [:]
private var foreignKeys: [String: Presence<[ForeignKeyInfo]>] = [:]
mutating func clear() {
primaryKeys = [:]
@@ -14,35 +34,35 @@ struct DatabaseSchemaCache {
schemaInfo = nil
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
func primaryKey(_ table: String) -> Presence<PrimaryKeyInfo>? {
primaryKeys[table]
}
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
mutating func set(primaryKey: Presence<PrimaryKeyInfo>, forTable table: String) {
primaryKeys[table] = primaryKey
}
func columns(in table: String) -> [ColumnInfo]? {
func columns(in table: String) -> Presence<[ColumnInfo]>? {
columns[table]
}
mutating func set(columns: [ColumnInfo], forTable table: String) {
mutating func set(columns: Presence<[ColumnInfo]>, forTable table: String) {
self.columns[table] = columns
}
func indexes(on table: String) -> [IndexInfo]? {
func indexes(on table: String) -> Presence<[IndexInfo]>? {
indexes[table]
}
mutating func set(indexes: [IndexInfo], forTable table: String) {
mutating func set(indexes: Presence<[IndexInfo]>, forTable table: String) {
self.indexes[table] = indexes
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
func foreignKeys(on table: String) -> Presence<[ForeignKeyInfo]>? {
foreignKeys[table]
}
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
mutating func set(foreignKeys: Presence<[ForeignKeyInfo]>, forTable table: String) {
self.foreignKeys[table] = foreignKeys
}
}
-1
View File
@@ -26,7 +26,6 @@ public class DatabaseSnapshot: DatabaseReader {
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: defaultLabel,
purpose: purpose)
+1 -3
View File
@@ -17,7 +17,6 @@ final class SerializedDatabase {
init(
path: String,
configuration: Configuration = Configuration(),
schemaCache: DatabaseSchemaCache,
defaultLabel: String,
purpose: String? = nil)
throws
@@ -47,8 +46,7 @@ final class SerializedDatabase {
self.db = try Database(
path: path,
description: identifier,
configuration: config,
schemaCache: schemaCache)
configuration: config)
self.queue = configuration.makeDispatchQueue(label: identifier)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
+2 -2
View File
@@ -318,11 +318,11 @@ public struct DatabaseMigrator {
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema()
return try db.schema(.main)
}
}()
if try db.schema() != tmpSchema {
if try db.schema(.main) != tmpSchema {
needsErase = true
return .commit
}
@@ -13,16 +13,16 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try dbPool.write { db in
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") == nil)
}
try dbPool.read { db in
// Assert that a reader cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") == nil)
}
try dbPool.read { db in
@@ -32,16 +32,16 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
_ = try db.indexes(on: "items")
// Assert that reader cache is warm
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") != nil)
}
try dbPool.read { db in
// Assert that reader cache is still warm
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") != nil)
}
try dbPool.write { db in
@@ -51,16 +51,16 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
_ = try db.indexes(on: "items")
// Assert that writer cache is warm
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") != nil)
}
try dbPool.write { db in
// Assert that writer cache is still warm
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") != nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") != nil)
}
try dbPool.write { db in
@@ -68,16 +68,16 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try db.execute(sql: "DROP TABLE items")
// Assert that the writer cache is cleared
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") == nil)
}
try dbPool.read { db in
// Assert that reader cache is cleared
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") == nil)
}
try dbPool.read { db in
@@ -161,16 +161,16 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
XCTAssertNotNil(db.schemaCache[.main].primaryKey("foo"))
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute(sql: "DROP TABLE foo")
// cache does not contain the primary key
XCTAssertNil(db.schemaCache.primaryKey("foo"))
XCTAssertNil(db.schemaCache[.main].primaryKey("foo"))
s3.signal()
_ = s4.wait(timeout: .distantFuture)
// cache does not contain the primary key
XCTAssertNil(db.schemaCache.primaryKey("foo"))
XCTAssertNil(db.schemaCache[.main].primaryKey("foo"))
}
}
let block2 = { () in
@@ -181,11 +181,11 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
XCTAssertNotNil(db.schemaCache[.main].primaryKey("foo"))
s2.signal()
_ = s3.wait(timeout: .distantFuture)
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
XCTAssertNotNil(db.schemaCache[.main].primaryKey("foo"))
// warm cache if needed
_ = try db.primaryKey("foo")
s4.signal()
@@ -207,9 +207,9 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try dbPool.unsafeRead { db in
// Assert that a cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache[.main].indexes(on: "items") == nil)
// Warm cache in a reader
_ = try db.primaryKey("items")
@@ -217,9 +217,9 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
_ = try db.indexes(on: "items")
// Assert that a reader cache is warmed
XCTAssertFalse(db.schemaCache.primaryKey("items") == nil)
XCTAssertFalse(db.schemaCache.columns(in: "items") == nil)
XCTAssertFalse(db.schemaCache.indexes(on: "items") == nil)
XCTAssertFalse(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertFalse(db.schemaCache[.main].columns(in: "items") == nil)
XCTAssertFalse(db.schemaCache[.main].indexes(on: "items") == nil)
}
}
}
@@ -12,7 +12,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
dbQueue.inDatabase { db in
// Assert that cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
@@ -21,7 +21,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
}
try dbQueue.inDatabase { db in
@@ -29,7 +29,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
try db.execute(sql: "DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
@@ -45,4 +45,91 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
}
}
}
func testTempCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TEMPORARY TABLE items (id INTEGER PRIMARY KEY)")
}
dbQueue.inDatabase { db in
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
// Warm cache
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") != nil)
}
try dbQueue.inDatabase { db in
// Empty cache after schema change
try db.execute(sql: "DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
do {
// Assert that cache is used: we expect an error now that
// the cache is empty.
_ = try db.primaryKey("items")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "no such table: items")
XCTAssertEqual(error.description, "SQLite error 1: no such table: items")
}
}
}
func testMainShadowedByTemp() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
do {
try db.execute(sql: """
CREATE TABLE items (id INTEGER PRIMARY KEY);
INSERT INTO items (id) VALUES (1);
""")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items")!.value != nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items")!.value == nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT id FROM items"), 1)
}
do {
try db.execute(sql: """
CREATE TEMPORARY TABLE items (otherID INTEGER PRIMARY KEY);
INSERT INTO items (otherID) VALUES (2);
""")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "otherID")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items")!.value != nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT otherID FROM items"), 2)
}
do {
try db.execute(sql: "DROP TABLE items")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items")!.value != nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items")!.value == nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT id FROM items"), 1)
}
}
}
}
+3 -3
View File
@@ -349,13 +349,13 @@ class DatabaseSnapshotTests: GRDBTestCase {
let snapshot = try dbPool.makeSnapshot()
try snapshot.read { db in
// Schema cache is updated
XCTAssertNil(db.schemaCache.primaryKey("t"))
XCTAssertNil(db.schemaCache[.main].primaryKey("t"))
_ = try db.primaryKey("t")
XCTAssertNotNil(db.schemaCache.primaryKey("t"))
XCTAssertNotNil(db.schemaCache[.main].primaryKey("t"))
}
snapshot.read { db in
// Schema cache is not cleared between reads
XCTAssertNotNil(db.schemaCache.primaryKey("t"))
XCTAssertNotNil(db.schemaCache[.main].primaryKey("t"))
}
}
}