Compare commits

...
Author SHA1 Message Date
Gwendal Roué 9318693fe4 Attached Cache 2023-03-20 13:19:18 +01:00
12 changed files with 225 additions and 21 deletions

No files matched your search

+4
View File
@@ -374,6 +374,7 @@
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
@@ -777,6 +778,7 @@
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
@@ -1444,6 +1446,7 @@
56A238701B9C75030082EB20 /* Configuration.swift */,
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
@@ -2023,6 +2026,7 @@
buildActionMask = 2147483647;
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
+74
View File
@@ -0,0 +1,74 @@
extension Database {
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
return try throwingFirstError {
attachedCache = AttachedCache(
schema: .attached("cache"),
statementCache: StatementCache(database: self))
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
return try execute()
} finally: {
attachedCache = nil
try self.execute(sql: "DETACH DATABASE cache")
}
}
}
extension Statement {
/// Returns a statement ready for iterating the results of this statement
/// with a DatabaseCursor.
///
/// The result is not the same statement as the receiver if we cache the
/// statement's results.
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
// Should we cache statement results and return a new statement on the cached values?
guard
// Don't cache until we were instructed to.
let attachedCache = database.attachedCache,
// Only cache read-only statements.
isReadonly,
// Only cache statements that access user tables.
databaseRegion
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
.isEmpty == false,
// Only cache statements that can build a name for the cache table.
let cacheTableName,
// Only cache statements for which we can guarantee rowid ordering
// without ambiguity.
case let statementColumns = columnNames.map({ $0.lowercased() }),
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
else {
// Don't cache: return self.
// Reset before cursor iteration: the statement may be reused.
try prepareExecution(withArguments: arguments)
return self
}
// Cache the results if not done yet
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
try database.execute(sql: """
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
""", arguments: arguments ?? self.arguments)
// Return a statement on the cached values, preserving the order of the
// original rows.
//
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
//
// > Tables created using CREATE TABLE AS are initially populated with
// > the rows of data returned by the SELECT statement. Rows are
// > assigned contiguously ascending rowid values, starting with 1, in
// > the order that they are returned by the SELECT statement.
let statement = try attachedCache.statementCache.statement("""
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
""")
// Reset before cursor iteration: the statement may be reused.
try statement.reset()
return statement
}
}
+5 -1
View File
@@ -57,6 +57,10 @@ extension Database {
case let .attached(name): return "\(name).sqlite_master"
}
}
func table(_ name: String) -> TableIdentifier {
TableIdentifier(schemaID: self, name: name)
}
}
/// The identifier of a database table or view.
@@ -210,7 +214,7 @@ extension Database {
}
}
private func tableExists(_ table: TableIdentifier) throws -> Bool {
func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
}
+14
View File
@@ -331,6 +331,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
class AttachedCache {
var schema: SchemaIdentifier
var statementCache: StatementCache
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
self.schema = schema
self.statementCache = statementCache
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The attached database that caches the results of requests.
var attachedCache: AttachedCache?
// MARK: - Private properties
/// Support for ``Configuration/busyMode``.
+9 -4
View File
@@ -168,9 +168,14 @@ public struct DatabaseRegion {
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
//
// We also remove GRDB internal tables (cache tables).
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods.
try ignoringInternalSQLiteTables().canonicalTables(db)
let notInternalTables = filteringTables {
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
}
return try notInternalTables.canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
@@ -190,11 +195,11 @@ public struct DatabaseRegion {
return region
}
/// Returns a region which doesn't contain any SQLite internal table.
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
/// Returns a region which only contains the filtered tables
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter {
!Database.isSQLiteInternalTable($0.key.rawValue)
predicate($0.key.rawValue)
}
return DatabaseRegion(tableRegions: filteredRegions)
}
+19
View File
@@ -342,6 +342,25 @@ extension DatabaseValue: CustomStringConvertible {
}
}
extension DatabaseValue {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
switch storage {
case .null:
return "NULL"
case let .string(string):
return String(reflecting: string)
case let .double(double):
return double.description
case let .int64(int64):
return int64.description
case let .blob(data):
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
}
}
}
/// Compares DatabaseValue like SQLite.
///
/// See RxGRDB for tests.
+1 -3
View File
@@ -147,6 +147,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
private let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -154,9 +155,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+1 -3
View File
@@ -1360,11 +1360,9 @@ public final class RowCursor: DatabaseCursor {
@usableFromInline let _row: Row // Reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+34 -4
View File
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -95,6 +96,23 @@ public final class Statement {
authorizerEventKinds.contains(where: \.isDelete)
}
/// A string that represented the statement in a lossless and
/// unambiguous way.
lazy var losslessDescription: String = {
"\(sql); -- \(arguments.losslessDescription)"
}()
/// A table name for caching the results of this statement
lazy var cacheTableName: String? = {
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
let losslessDescription = losslessDescription.data(using: .utf8)
else {
return nil
}
let digest = Insecure.SHA1.hash(data: losslessDescription)
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
}()
@usableFromInline
unowned let database: Database
@@ -779,10 +797,7 @@ final class StatementCursor: DatabaseCursor {
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
self._statement = statement
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
_statement = try statement.databaseCursorStatement(with: arguments)
}
deinit {
@@ -1389,4 +1404,19 @@ extension StatementArguments: CustomStringConvertible {
}
}
extension StatementArguments {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
var chunks: [String] = []
for value in values {
chunks.append(value.losslessDescription)
}
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
chunks.append("\(key): \(value.losslessDescription)")
}
return chunks.joined(separator: ",")
}
}
extension StatementArguments: Sendable { }
+1 -3
View File
@@ -214,6 +214,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@usableFromInline let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -221,9 +222,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+1 -3
View File
@@ -803,11 +803,9 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
let _row: Row // Instantiated once, reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+62
View File
@@ -622,4 +622,66 @@ class DatabaseTests : GRDBTestCase {
// 999 should be safe: https://www.sqlite.org/limits.html
XCTAssertGreaterThanOrEqual(count, 999)
}
func testCache() throws {
// See "In-memory Databases And Shared Cache" in https://www.sqlite.org/inmemorydb.html
dbConfiguration.prepareDatabase { db in
db.trace { print($0)}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in // transaction prevents DETACH DATABASE from wording
var region = DatabaseRegion()
try db.recordingSelection(&region) {
try db.withCache(atPath: ":memory:") {
try db.execute(sql: """
CREATE TABLE player(id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE award(id INTEGER PRIMARY KEY, playerId INTEGER REFERENCES player(id), color TEXT);
INSERT INTO player (name) VALUES ('Barbara');
INSERT INTO player (name) VALUES ('Zoe');
INSERT INTO player (name) VALUES ('Gaston');
INSERT INTO player (name) VALUES ('Bernard');
INSERT INTO player (name) VALUES ('Henri');
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
INSERT INTO award(playerId, color) VALUES (1, 'Silver');
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
INSERT INTO award(playerId, color) VALUES (2, 'Silver');
INSERT INTO award(playerId, color) VALUES (3, 'Gold');
INSERT INTO award(playerId, color) VALUES (4, 'Silver');
""")
struct Player: TableRecord, FetchableRecord, Decodable {
static let awards = hasMany(Award.self)
var id: Int64
var name: String
}
struct Award: TableRecord, FetchableRecord, Decodable {
var id: Int64
var playerId: Int64
var color: String
}
do {
_ = try Row.fetchAll(db, sql: "SELECT * FROM player ORDER BY name")
}
do {
// Test cache ordering with rowid disambiguation
_ = try Row.fetchAll(db, sql: "SELECT rowid AS rowID, * FROM player ORDER BY name")
}
do {
struct PlayerWithAwards: FetchableRecord, Decodable {
var player: Player
var awards: [Award]
}
_ = try Player
.filter(Column("name") != "Gaston")
.including(all: Player.awards.filter(Column("color") != "Gold"))
.asRequest(of: PlayerWithAwards.self)
.fetchAll(db)
}
}
}
try print(region.observableRegion(db))
}
}
}