diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 8f34f2851..e9589ee63 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -154,7 +154,20 @@ public final class Row { let sqliteStatement: SQLiteStatement? /// The number of columns in the row. - public let count: Int + @inlinable + public var count: Int { + // Rows that map an SQLite statement don't cache the number of + // columns, because SQLite may recompile the statement after a + // schema change, with a different number of columns. + if let sqliteStatement { + return Int(sqlite3_column_count(sqliteStatement)) + } + return cachedCount + } + + /// The number of columns, when the row does not map an SQLite statement. + @usableFromInline + let cachedCount: Int /// A view on the prefetched associated rows. /// @@ -238,7 +251,7 @@ public final class Row { self.statement = statement self.sqliteStatement = statement.sqliteStatement self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement) - self.count = Int(sqlite3_column_count(sqliteStatement)) + self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count` } /// Creates a row that maps an SQLite statement. Further calls to @@ -247,7 +260,7 @@ public final class Row { self.statement = nil self.sqliteStatement = sqliteStatement self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement) - self.count = Int(sqlite3_column_count(sqliteStatement)) + self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count` } /// Creates a row that contain a copy of the current state of the @@ -269,7 +282,7 @@ public final class Row { self.statement = nil self.sqliteStatement = nil self.impl = impl - self.count = impl.count + self.cachedCount = impl.count } } @@ -2785,19 +2798,10 @@ private struct StatementCopyRowImpl: RowImpl { private struct StatementRowImpl: RowImpl { let statement: Statement let sqliteStatement: SQLiteStatement - let lowercaseColumnIndexes: [String: Int] init(sqliteStatement: SQLiteStatement, statement: Statement) { self.statement = statement self.sqliteStatement = sqliteStatement - // Optimize row[columnName] - let lowercaseColumnNames = (0.. Int? { + let lowercaseColumnIndexes = statement.columnIndexes if let index = lowercaseColumnIndexes[name] { return index } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 31a1abd16..28788dddb 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -47,6 +47,25 @@ public final class Statement { case rollbackSavepoint(String) } + /// The column names and indexes of a statement, for a given compilation + /// of the statement. + private struct ColumnCache { + var reprepareCount: CInt + var columnNames: [String] + /// Indexes of the leftmost columns. Keys are lowercase. + var columnIndexes: [String: Int] + + init(sqliteStatement: SQLiteStatement, reprepareCount: CInt) { + self.reprepareCount = reprepareCount + self.columnNames = (0..), and this can change + /// the result columns (think `SELECT *` after a column was added). + /// So the cache is rebuilt whenever the statement is recompiled. + private var columnCache: ColumnCache { + let reprepareCount = sqlite3_stmt_status(sqliteStatement, SQLITE_STMTSTATUS_REPREPARE, 0) + if let _columnCache, _columnCache.reprepareCount == reprepareCount { + return _columnCache + } + let columnCache = ColumnCache(sqliteStatement: sqliteStatement, reprepareCount: reprepareCount) + _columnCache = columnCache + return columnCache + } /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. diff --git a/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift b/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift index 426dca46a..297f521ad 100644 --- a/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift +++ b/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift @@ -405,4 +405,31 @@ class RowFromStatementTests : RowTestCase { ]) } } + + func testRowsAfterSchemaChange() throws { + // SQLite recompiles statements after a schema change, and this can + // change the result columns. + try makeDatabaseQueue().inDatabase { db in + try db.execute(sql: """ + CREATE TABLE t(a); + INSERT INTO t VALUES (1); + """) + let statement = try db.makeStatement(sql: "SELECT * FROM t") + XCTAssertEqual(try Row.fetchAll(statement), [["a": 1]]) + + try db.execute(sql: "ALTER TABLE t ADD COLUMN b DEFAULT 2") + + // The cursor is created before the statement is recompiled, + // on the first step. + let rows = try Row.fetchCursor(statement) + let row = try XCTUnwrap(rows.next()) + XCTAssertEqual(row.count, 2) + XCTAssertEqual(Array(row.columnNames), ["a", "b"]) + XCTAssertEqual(row["b"], 2) + XCTAssertEqual(row.copy(), ["a": 1, "b": 2]) + XCTAssertNil(try rows.next()) + + XCTAssertEqual(try Row.fetchAll(statement), [["a": 1, "b": 2]]) + } + } } diff --git a/Tests/GRDBTests/Core/SQLRequestTests.swift b/Tests/GRDBTests/Core/SQLRequestTests.swift index 2c95c8012..ecb3eccd1 100644 --- a/Tests/GRDBTests/Core/SQLRequestTests.swift +++ b/Tests/GRDBTests/Core/SQLRequestTests.swift @@ -47,6 +47,33 @@ class SQLRequestTests: GRDBTestCase { } } + func testCachedSQLRequestAfterSchemaChange() throws { + // SQLite recompiles statements after a schema change, and this can + // change the result columns. + let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE t(a); + INSERT INTO t VALUES (1); + """) + } + + let request = SQLRequest(sql: "SELECT * FROM t", cached: true) + try dbQueue.read { db in + XCTAssertEqual(try request.fetchAll(db), [["a": 1]]) + } + + // Schema change performed by another connection + let otherQueue = try makeDatabaseQueue(filename: "test.sqlite") + try otherQueue.write { db in + try db.execute(sql: "ALTER TABLE t ADD COLUMN b DEFAULT 2") + } + + try dbQueue.inDatabase { db in + XCTAssertEqual(try request.fetchAll(db), [["a": 1, "b": 2]]) + } + } + func testSQLLiteralInitializer() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift b/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift index 95d8d39c4..324608dfa 100644 --- a/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift +++ b/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift @@ -388,4 +388,26 @@ class SelectStatementTests : GRDBTestCase { XCTAssertEqual(observers.map(\.triggered), [true, true, true, true]) } } + + func testColumnsAfterSchemaChange() throws { + // SQLite recompiles statements after a schema change, and this can + // change the result columns. + try makeDatabaseQueue().inDatabase { db in + try db.execute(sql: """ + CREATE TABLE t(a); + INSERT INTO t VALUES (1); + """) + let statement = try db.makeStatement(sql: "SELECT * FROM t") + XCTAssertEqual(statement.columnNames, ["a"]) + XCTAssertEqual(statement.index(ofColumn: "a"), 0) + XCTAssertNil(statement.index(ofColumn: "b")) + + try db.execute(sql: "ALTER TABLE t ADD COLUMN b") + try statement.execute() // Recompile + XCTAssertEqual(statement.columnCount, 2) + XCTAssertEqual(statement.columnNames, ["a", "b"]) + XCTAssertEqual(statement.index(ofColumn: "a"), 0) + XCTAssertEqual(statement.index(ofColumn: "b"), 1) + } + } }