From ad61c72988453bed0ec8397c8107d42dcb6574bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Oct 2018 08:04:37 +0200 Subject: [PATCH 1/3] Remove two invalid tests that use cursor outside of their protected dispatch queue --- .../DatabasePoolReleaseMemoryTests.swift | 33 ------------------- .../DatabaseQueueReleaseMemoryTests.swift | 33 ------------------- 2 files changed, 66 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index f4c9f5c5e..491fb1199 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -188,39 +188,6 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { XCTAssertEqual(openConnectionCount, 0) } - // TODO: this test should be duplicated for all cursor types - func testDatabaseCursorRetainSQLiteConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - openConnectionCount += 1 - } - } - - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } - } - - var cursor: FastDatabaseValueCursor? = nil - do { - try! makeDatabasePool().write { db in - try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute("INSERT INTO items (id) VALUES (NULL)") - try db.execute("INSERT INTO items (id) VALUES (NULL)") - cursor = try Int.fetchCursor(db, "SELECT id FROM items") - XCTAssertTrue(try cursor!.next() != nil) - XCTAssertEqual(openConnectionCount, 1) - } - } - XCTAssertEqual(openConnectionCount, 0) - XCTAssertTrue(try! cursor!.next() != nil) - XCTAssertTrue(try! cursor!.next() == nil) - } - func testStatementDoNotRetainDatabaseConnection() throws { // Block 1 Block 2 // create statement INSERT diff --git a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift index 7f2426350..08707fd51 100644 --- a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift @@ -102,39 +102,6 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { // All connections are closed XCTAssertEqual(openConnectionCount, 0) } - - // TODO: this test should be duplicated for all cursor types - func testDatabaseCursorRetainSQLiteConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - openConnectionCount += 1 - } - } - - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } - } - - var cursor: FastDatabaseValueCursor? = nil - do { - try! makeDatabaseQueue().inDatabase { db in - try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute("INSERT INTO items (id) VALUES (NULL)") - try db.execute("INSERT INTO items (id) VALUES (NULL)") - cursor = try Int.fetchCursor(db, "SELECT id FROM items") - XCTAssertTrue(try cursor!.next() != nil) - XCTAssertEqual(openConnectionCount, 1) - } - } - XCTAssertEqual(openConnectionCount, 0) - XCTAssertTrue(try! cursor!.next() != nil) - XCTAssertTrue(try! cursor!.next() == nil) - } func testStatementDoNotRetainDatabaseConnection() throws { // Block 1 Block 2 From 6157ab0583ad7260391bfb734b8cbd6ba18a02c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Oct 2018 08:13:23 +0200 Subject: [PATCH 2/3] Have cursors reset their statement when they are deinitialized This is the real fix for #424. GRDB used to keep unfinished SQLite statements around. Now cursors properly reset their statement when they are done. We no longer have to clear the statement cache before a backup. --- GRDB/Core/Database.swift | 13 +++--------- GRDB/Core/DatabaseValueConvertible.swift | 12 +++++++++++ GRDB/Core/DatabaseWriter.swift | 4 ---- GRDB/Core/Row.swift | 13 ++++++++++-- GRDB/Core/Statement.swift | 24 ++++++++++++---------- GRDB/Core/StatementColumnConvertible.swift | 12 +++++++++++ GRDB/Record/FetchableRecord.swift | 6 ++++++ 7 files changed, 57 insertions(+), 27 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ce9c800f4..2a2a96714 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -778,16 +778,6 @@ extension Database { // MARK: - Backup static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws { - // The schema of the destination database will change: we need to clear - // the schema and statements cache. - // - // We especially need to clear the statements cache before calling - // sqlite3_backup_init, so that we avoid an SQLite error - // "destination database is in use" (SQLITE_ERROR). - // - // See https://github.com/groue/GRDB.swift/issues/424 - dbDest.clearSchemaCache() - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } @@ -820,6 +810,9 @@ extension Database { case let code: throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) } + + // The schema of the destination database has changed: + dbDest.clearSchemaCache() } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 1502d8a89..e0590e6cf 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -65,6 +65,12 @@ public final class DatabaseValueCursor : Cursor statement.reset(withArguments: arguments) } + deinit { + // Statement reset fails when sqlite3_step has previously failed. + // Just ignore reset error. + try? statement.reset() + } + /// :nodoc: public func next() throws -> Value? { if done { @@ -119,6 +125,12 @@ public final class NullableDatabaseValueCursor statement.reset(withArguments: arguments) } + deinit { + // Statement reset fails when sqlite3_step has previously failed. + // Just ignore reset error. + try? statement.reset() + } + /// :nodoc: public func next() throws -> Value?? { if done { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 9bac302ac..c1b77e010 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -153,10 +153,6 @@ extension DatabaseWriter { // SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 // So we'll drop all database objects one after the other. try writeWithoutTransaction { db in - // Clear schema and statement cache so that no prepared statement - // can prevent schema change. - db.clearSchemaCache() - // Prevent foreign keys from messing with drop table statements let foreignKeysEnabled = try Bool.fetchOne(db, "PRAGMA foreign_keys")! if foreignKeysEnabled { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 11d23e9e9..3643918c1 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -617,6 +617,12 @@ public final class RowCursor : Cursor { statement.reset(withArguments: arguments) } + deinit { + // Statement reset fails when sqlite3_step has previously failed. + // Just ignore reset error. + try? statement.reset() + } + /// :nodoc: public func next() throws -> Row? { if done { @@ -702,8 +708,11 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { - // The cursor reuses a single mutable row. Return an immutable copy. - return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().map { $0.copy() } + let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) + // Keep cursor alive until we can copy the fetched row + return try withExtendedLifetime(cursor) { + try cursor.next().map { $0.copy() } + } } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 9e772bf07..0d4bb6ccd 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -83,14 +83,11 @@ public class Statement { sqlite3_finalize(sqliteStatement) } - final func reset() { - // It looks like sqlite3_reset() does not access the file system. - // This function call should thus succeed, unless a GRDB bug, or a - // programmer error (reusing a failed statement): there is no point - // throwing any error. + final func reset() throws { + SchedulingWatchdog.preconditionValidQueue(database) let code = sqlite3_reset(sqliteStatement) guard code == SQLITE_OK else { - fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description) + throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql) } } @@ -136,7 +133,7 @@ public class Statement { _arguments = arguments argumentsNeedValidation = false - reset() + try! reset() clearBindings() var valuesIterator = arguments.values.makeIterator() @@ -159,7 +156,7 @@ public class Statement { argumentsNeedValidation = false // Apply - reset() + try reset() clearBindings() for (index, dbValue) in zip(Int32(1)..., bindings) { bind(dbValue, at: index) @@ -363,9 +360,8 @@ public final class SelectStatement : Statement { /// Utility function for cursors func reset(withArguments arguments: StatementArguments? = nil) { - SchedulingWatchdog.preconditionValidQueue(database) prepare(withArguments: arguments) - reset() + try! reset() } } @@ -392,6 +388,12 @@ public final class StatementCursor: Cursor { statement.reset(withArguments: arguments) } + deinit { + // Statement reset fails when sqlite3_step has previously failed. + // Just ignore reset error. + try? statement.reset() + } + /// :nodoc: public func next() throws -> Void? { if done { @@ -480,7 +482,7 @@ public final class UpdateStatement : Statement { public func execute(arguments: StatementArguments? = nil) throws { SchedulingWatchdog.preconditionValidQueue(database) prepare(withArguments: arguments) - reset() + try reset() database.updateStatementWillExecute(self) while true { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 656101e60..65650e0e3 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -77,6 +77,12 @@ public final class FastDatabaseValueCursor Value? { if done { @@ -127,6 +133,12 @@ public final class FastNullableDatabaseValueCursor Value?? { if done { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 3e54a2757..783ec7791 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -381,6 +381,12 @@ public final class RecordCursor : Cursor { statement.reset(withArguments: arguments) } + deinit { + // Statement reset fails when sqlite3_step has previously failed. + // Just ignore reset error. + try? statement.reset() + } + /// :nodoc: public func next() throws -> Record? { if done { From d963e688beb4e3bd9507ffec1c5eb7f6a702e5e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Oct 2018 08:24:34 +0200 Subject: [PATCH 3/3] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6657ef47..1120ec52d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Release Notes ### Fixed - [#425](https://github.com/groue/GRDB.swift/pull/425): Fix "destination database is in use " error during database backup +- [#427](https://github.com/groue/GRDB.swift/pull/427): Have cursors reset SQLite statements in deinit ### New