From 4edd76341eb50abfe0771fd8f019fe296f7d8266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 May 2017 18:05:36 +0200 Subject: [PATCH] There are two statement caches: one for statements generated by the user, and one for the statements generated by GRDB. Those are separated so that GRDB has no opportunity to inadvertently modify the arguments of user statements. --- GRDB/Core/Database.swift | 55 +++++++++++++++-------------------- GRDB/Core/Statement.swift | 48 ++++++++++++++++++++++++++++++ GRDB/Record/Persistable.swift | 8 ++--- 3 files changed, 76 insertions(+), 35 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d1cf164a4..e13104741 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -314,12 +314,19 @@ public final class Database { /// Schema Cache var schemaCache: DatabaseSchemaCache // internal so that it can be tested - - /// Statement cache. Not part of the schema cache because statements belong - /// to this connection, while schema cache can be shared with + + /// Statement caches. + /// + /// Statement caches are not part of the schema cache because statements + /// belong to this connection, while schema cache can be shared with /// other connections. - fileprivate var selectStatementCache: [String: SelectStatement] = [:] - fileprivate var updateStatementCache: [String: UpdateStatement] = [:] + /// + /// There are two statement caches: one for statements generated by the + /// user, and one for the statements generated by GRDB. Those are separated + /// so that GRDB has no opportunity to inadvertently modify the arguments of + /// user statements. + lazy var statementCache: StatementCache = StatementCache(database: self) + fileprivate lazy var userStatementCache: StatementCache = StatementCache(database: self) init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws { // Error log setup must happen before any database connection @@ -418,8 +425,8 @@ public final class Database { assert(!isClosed) configuration.SQLiteConnectionWillClose?(sqliteConnection) - updateStatementCache = [:] - selectStatementCache = [:] + statementCache.clear() + userStatementCache.clear() Database.close(connection: sqliteConnection) isClosed = true configuration.SQLiteConnectionDidClose?() @@ -433,8 +440,8 @@ public final class Database { func releaseMemory() { sqlite3_db_release_memory(sqliteConnection) schemaCache.clear() - updateStatementCache = [:] - selectStatementCache = [:] + statementCache.clear() + userStatementCache.clear() } private func setupForeignKeys() throws { @@ -627,13 +634,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { - if let statement = selectStatementCache[sql] { - return statement - } - - let statement = try makeSelectStatement(sql) - selectStatementCache[sql] = statement - return statement + return try userStatementCache.selectStatement(sql) } /// Returns a new prepared statement that can be reused. @@ -662,13 +663,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { - if let statement = updateStatementCache[sql] { - return statement - } - - let statement = try makeUpdateStatement(sql) - updateStatementCache[sql] = statement - return statement + return try userStatementCache.updateStatement(sql) } /// Executes one or several SQL statements, separated by semi-colons. @@ -1050,8 +1045,8 @@ extension Database { // the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html) // because the automatic statement recompilation only happens a // limited number of times. - updateStatementCache = [:] - selectStatementCache = [:] + statementCache.clear() + userStatementCache.clear() } /// Returns whether a table exists. @@ -1783,9 +1778,8 @@ extension Database { // https://www.sqlite.org/c3ref/reset.html // // So make sure we clear this statement from the cache. - if let index = selectStatementCache.index(where: { $0.1 === statement }) { - selectStatementCache.remove(at: index) - } + statementCache.remove(statement) + userStatementCache.remove(statement) } /// Some failed statements interest transaction observers. @@ -1803,9 +1797,8 @@ extension Database { // https://www.sqlite.org/c3ref/reset.html // // So make sure we clear this statement from the cache. - if let index = updateStatementCache.index(where: { $0.1 === statement }) { - updateStatementCache.remove(at: index) - } + statementCache.remove(statement) + userStatementCache.remove(statement) switch transactionHookState { case .rollback: diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 996d93684..d382bd4d3 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -837,3 +837,51 @@ extension StatementArguments : CustomStringConvertible { return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } } + +/// A thread-unsafe statement cache +struct StatementCache { + unowned let db: Database + private var selectStatements: [String: SelectStatement] = [:] + private var updateStatements: [String: UpdateStatement] = [:] + + init(database: Database) { + self.db = database + } + + mutating func selectStatement(_ sql: String) throws -> SelectStatement { + if let statement = selectStatements[sql] { + return statement + } + + let statement = try db.makeSelectStatement(sql) + selectStatements[sql] = statement + return statement + } + + mutating func updateStatement(_ sql: String) throws -> UpdateStatement { + if let statement = updateStatements[sql] { + return statement + } + + let statement = try db.makeUpdateStatement(sql) + updateStatements[sql] = statement + return statement + } + + mutating func clear() { + updateStatements = [:] + selectStatements = [:] + } + + mutating func remove(_ statement: SelectStatement) { + if let index = selectStatements.index(where: { $0.1 === statement }) { + selectStatements.remove(at: index) + } + } + + mutating func remove(_ statement: UpdateStatement) { + if let index = updateStatements.index(where: { $0.1 === statement }) { + updateStatements.remove(at: index) + } + } +} diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index c1578e410..df7770454 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -615,7 +615,7 @@ final class DAO { onConflict: onConflict, tableName: databaseTableName, insertedColumns: Array(persistentDictionary.keys)) - let statement = try db.cachedUpdateStatement(query.sql) + let statement = try db.statementCache.updateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(persistentDictionary.values)) return statement } @@ -657,7 +657,7 @@ final class DAO { tableName: databaseTableName, updatedColumns: updatedColumns, conditionColumns: primaryKeyColumns) - let statement = try db.cachedUpdateStatement(query.sql) + let statement = try db.statementCache.updateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues)) return statement } @@ -672,7 +672,7 @@ final class DAO { let query = DeleteQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - let statement = try db.cachedUpdateStatement(query.sql) + let statement = try db.statementCache.updateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement } @@ -687,7 +687,7 @@ final class DAO { let query = ExistsQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - let statement = try db.cachedSelectStatement(query.sql) + let statement = try db.statementCache.selectStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement }