diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index a32903377..13ca11e41 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -21,6 +21,8 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. public init(_ cursor: C) throws where C.Element == Element { self.init() + // Use `forEach` in order to deal with . + // See `Statement.forEachStep(_:)` for more information. try cursor.forEach { append($0) } } @@ -768,6 +770,13 @@ public final class EnumeratedCursor: Cursor { defer { index += 1 } return (index, element) } + + public func forEach(_ body: ((Int, Base.Element)) throws -> Void) throws { + try base.forEach { element in + defer { index += 1 } + try body((index, element)) + } + } } /// A cursor whose elements consist of the elements of some base cursor that @@ -791,6 +800,14 @@ public final class FilterCursor: Cursor { } return nil } + + public func forEach(_ body: (Base.Element) throws -> Void) throws { + try base.forEach { element in + if try isIncluded(element) { + try body(element) + } + } + } } /// A cursor consisting of all the elements contained in each segment contained @@ -839,6 +856,12 @@ public final class MapCursor: Cursor { guard let element = try base.next() else { return nil } return try transform(element) } + + public func forEach(_ body: (Element) throws -> Void) throws { + try base.forEach { element in + try body(transform(element)) + } + } } /// A cursor that only consumes up to `n` elements from an underlying diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index d1d517617..cabe9073e 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -542,49 +542,6 @@ public class SQLStatementCursor: Cursor { } extension Database { - func executeStatement(_ statement: Statement) throws { - let authorizer = try statementWillExecute(statement) - let sqliteStatement = statement.sqliteStatement - - var code: Int32 = SQLITE_OK - withAuthorizer(authorizer) { - while true { - code = sqlite3_step(sqliteStatement) - if code == SQLITE_ROW { - // Statement returns a row, but the user ignores the - // content of this row: - // - // try db.execute(sql: "SELECT ...") - // - // That's OK: maybe the selected rows perform side effects. - // For example: - // - // try db.execute(sql: "SELECT sqlcipher_export(...)") - // - // Or maybe the user doesn't know that the executed statement - // return rows (https://github.com/groue/GRDB.swift/issues/15); - // - // try db.execute(sql: "PRAGMA journal_mode=WAL") - // - // It is thus important that we consume *all* rows. - continue - } else { - break - } - } - } - - // Statement has been fully executed, and authorizer has been reset. - // We can now move on further tasks. - - if code == SQLITE_DONE { - try statementDidExecute(statement) - } else { - assert(code != SQLITE_ROW) - try statementDidFail(statement, withResultCode: code) - } - } - /// Returns the authorizer that should be used during statement execution /// (this allows preventing the truncate optimization when there exists a /// transaction observer for row deletion). diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 21ab900c4..515fd6fc1 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -583,6 +583,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Authorizer + @usableFromInline func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { SchedulingWatchdog.preconditionValidQueue(self) let old = self._authorizer diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 98c63165a..e04f83765 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -126,24 +126,20 @@ extension DatabaseValueConvertible { /// print(url) /// } /// } -public final class DatabaseValueCursor: Cursor { - private enum _State { - case idle, busy, done, failed - } - - private let _statement: Statement - private let _sqliteStatement: SQLiteStatement - private let _columnIndex: Int32 - private var _state = _State.idle +public final class DatabaseValueCursor: DatabaseCursor { + public typealias Element = Value + public let statement: Statement + /// :nodoc: + public var _isDone = false + private let columnIndex: Int32 init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - _statement = statement - _sqliteStatement = statement.sqliteStatement + self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - _columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { - _columnIndex = 0 + columnIndex = 0 } // Assume cursor is created for immediate iteration: reset and set arguments @@ -151,49 +147,18 @@ public final class DatabaseValueCursor: Cursor } deinit { - if _state == .busy { - try? _statement.database.statementDidExecute(_statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? _statement.reset() + try? statement.reset() } - public func next() throws -> Value? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - // TODO GRDB6: don't crash on decoding errors - return try! Value.decode( - fromStatement: _sqliteStatement, - atUncheckedIndex: _columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } + /// :nodoc: + public func _element(sqliteStatement: SQLiteStatement) -> Value { + // TODO GRDB6: don't crash on decoding errors + try! Value.decode( + fromStatement: sqliteStatement, + atUncheckedIndex: columnIndex, + context: RowDecodingContext(statement: statement, index: Int(columnIndex))) } } @@ -206,24 +171,20 @@ public final class DatabaseValueCursor: Cursor /// print(url) /// } /// } -public final class NullableDatabaseValueCursor: Cursor { - private enum _State { - case idle, busy, done, failed - } - - private let _statement: Statement - private let _sqliteStatement: SQLiteStatement - private let _columnIndex: Int32 - private var _state = _State.idle +public final class NullableDatabaseValueCursor: DatabaseCursor { + public typealias Element = Value? + public let statement: Statement + /// :nodoc: + public var _isDone = false + private let columnIndex: Int32 init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - _statement = statement - _sqliteStatement = statement.sqliteStatement + self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - _columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { - _columnIndex = 0 + columnIndex = 0 } // Assume cursor is created for immediate iteration: reset and set arguments @@ -231,49 +192,18 @@ public final class NullableDatabaseValueCursor: } deinit { - if _state == .busy { - try? _statement.database.statementDidExecute(_statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? _statement.reset() + try? statement.reset() } - public func next() throws -> Value?? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - // TODO GRDB6: don't crash on decoding errors - return try! Value.decodeIfPresent( - fromStatement: _sqliteStatement, - atUncheckedIndex: _columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } + /// :nodoc: + public func _element(sqliteStatement: SQLiteStatement) -> Value? { + // TODO GRDB6: don't crash on decoding errors + try! Value.decodeIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: columnIndex, + context: RowDecodingContext(statement: statement, index: Int(columnIndex))) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 406645e99..e6e7e67d7 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1199,67 +1199,30 @@ extension Row { /// try dbQueue.read { db in /// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RowCursor: Cursor { - private enum _State { - case idle, busy, done, failed - } - - /// The statement iterated by this cursor +public final class RowCursor: DatabaseCursor { + public typealias Element = Row public let statement: Statement - private let _sqliteStatement: SQLiteStatement - private let _row: Row // Reused for performance - private var _state = _State.idle + /// :nodoc: + public var _isDone = false + @usableFromInline let _row: Row // Reused for performance init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { self.statement = statement self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) - self._sqliteStatement = statement.sqliteStatement // Assume cursor is created for immediate iteration: reset and set arguments statement.reset(withArguments: arguments) } deinit { - if _state == .busy { - try? statement.database.statementDidExecute(statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. try? statement.reset() } - public func next() throws -> Row? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try statement.database.statementWillExecute(statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: statement.sql, - arguments: statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try statement.database.statementDidExecute(statement) - return nil - case SQLITE_ROW: - return _row - case let code: - _state = .failed - try statement.database.statementDidFail(statement, withResultCode: code) - } - } + /// :nodoc: + @inlinable + public func _element(sqliteStatement: SQLiteStatement) -> Row { _row } } extension Row { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index b7b11bd20..e43b78fed 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -288,6 +288,78 @@ public final class Statement { try! validateArguments(self.arguments) } } + + /// Calls the given closure after one successful call to `sqlite3_step()`. + /// + /// This method is unable to deal with statements that need a specific + /// authorizer. See `forEachStep(_:)`. + @usableFromInline + func step(_ body: (SQLiteStatement) throws -> Element) throws -> Element? { + // This check takes 0 time when profiled. It is, practically speaking, free. + if sqlite3_stmt_busy(sqliteStatement) == 0 { + guard try database.statementWillExecute(self) == nil else { + fatalError("Can't execute step by step a statement that requires a customized authorizer.") + } + } + + switch sqlite3_step(sqliteStatement) { + case SQLITE_DONE: + try database.statementDidExecute(self) + return nil + case SQLITE_ROW: + return try body(sqliteStatement) + case let code: + try database.statementDidFail(self, withResultCode: code) + } + } + + /// Calls the given closure after each successful call to `sqlite3_step()`. + /// + /// Unlike multiple calls to `step(_:)`, this method is able to deal with + /// statements that need a specific authorizer. + /// + /// That's how we deal with TransactionObservers that observe deletion: + /// the authorizer prevents the truncate optimization + /// . + /// + /// That's also how we deal with , + /// in four steps: + /// + /// 1. `T.fetchAll(...)` calls `Array(T.fetchCursor(...))` + /// 2. `Array(T.fetchCursor(...))` calls `Cursor.forEach(...)` + /// 3. `DatabaseCursor.forEach(...)` calls `Statement.forEachStep(...)` + /// 4. `Statement.forEachStep(...)` deals with the eventual authorizer. + @usableFromInline + func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws { + guard sqlite3_stmt_busy(sqliteStatement) == 0 else { + // We can't deal with possible authorizer + fatalError("Statement is busy") + } + if let authorizer = try database.statementWillExecute(self) { + try database.withAuthorizer(authorizer) { + try uncheckedForEach(body) + } + } else { + try uncheckedForEach(body) + } + } + + /// Implementation detail of `forEach(_:)`. + /// Does not check for sqlite3_stmt_busy and eventual authorizer. + @usableFromInline + func uncheckedForEach(_ body: (SQLiteStatement) throws -> Void) throws { + while true { + switch sqlite3_step(sqliteStatement) { + case SQLITE_DONE: + try database.statementDidExecute(self) + return + case SQLITE_ROW: + try body(sqliteStatement) + case let code: + try database.statementDidFail(self, withResultCode: code) + } + } + } } @available(*, deprecated, renamed: "Statement") @@ -324,6 +396,51 @@ extension Statement { } } +// MARK: - Cursors + +/// Implementation details of `DatabaseCursor`. +/// +/// :nodoc: +public protocol _DatabaseCursor: Cursor { + /// Reserved to `_DatabaseCursor` implementation. + /// Must be initialized to false. + var _isDone: Bool { get set } + + /// Called after one successful call to `sqlite3_step()`. Returns the + /// element for the current statement step. + func _element(sqliteStatement: SQLiteStatement) throws -> Element +} + +/// A protocol for cursors that iterate a database statement. +public protocol DatabaseCursor: _DatabaseCursor { + /// The statement iterated by the cursor + var statement: Statement { get } +} + +extension DatabaseCursor { + @inlinable + public func next() throws -> Element? { + if _isDone { + return nil + } + if let element = try statement.step(_element) { + return element + } + _isDone = true + return nil + } + + // Specific implementation of `forEach` in order to deal with + // . + // See `Statement.forEachStep(_:)` for more information. + @inlinable + public func forEach(_ body: (Element) throws -> Void) throws { + if _isDone { return } + try statement.forEachStep { try body(_element(sqliteStatement: $0)) } + _isDone = true + } +} + /// A cursor that iterates a database statement without producing any value. /// Each call to the next() cursor method calls the sqlite3_step() C function. /// @@ -334,66 +451,25 @@ extension Statement { /// let cursor = statement.makeCursor() /// try cursor.next() /// } -final class StatementCursor: Cursor { - private enum _State { - case idle, busy, done, failed - } - - /* private, internal for testability */ let _statement: Statement - private let _sqliteStatement: SQLiteStatement - private var _state = _State.idle +final class StatementCursor: DatabaseCursor { + typealias Element = Void + let statement: Statement + var _isDone = false // Use Statement.makeCursor() instead init(statement: Statement, arguments: StatementArguments? = nil) throws { - _statement = statement - _sqliteStatement = statement.sqliteStatement - - // Assume cursor is created for immediate iteration: reset and set arguments + self.statement = statement statement.reset(withArguments: arguments) } deinit { - if _state == .busy { - try? _statement.database.statementDidExecute(_statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? _statement.reset() + try? statement.reset() } - /// :nodoc: - func next() throws -> Void? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - return .some(()) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } - } + @usableFromInline + func _element(sqliteStatement: SQLiteStatement) throws { } } // MARK: - Update Statements @@ -426,10 +502,8 @@ extension Statement { SchedulingWatchdog.preconditionValidQueue(database) reset(withArguments: arguments) - // Statement does not know how to execute itself, because it does not - // know how to handle its errors, or if truncate optimisation should be - // prevented or not. Database knows. - try database.executeStatement(self) + // Iterate all rows, since they may execute side effects. + try forEachStep { _ in } } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index a6afb9d20..d0abc3de5 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -138,25 +138,22 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// print(name) /// } /// } -public final class FastDatabaseValueCursor : Cursor { - @usableFromInline - enum _State { - case idle, busy, done, failed - } - - @usableFromInline let _statement: Statement - @usableFromInline let _columnIndex: Int32 - @usableFromInline let _sqliteStatement: SQLiteStatement - @usableFromInline var _state = _State.idle +public final class FastDatabaseValueCursor: DatabaseCursor +where Value: DatabaseValueConvertible & StatementColumnConvertible +{ + public typealias Element = Value + public let statement: Statement + /// :nodoc: + public var _isDone = false + @usableFromInline let columnIndex: Int32 init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - _statement = statement - _sqliteStatement = statement.sqliteStatement + self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - _columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { - _columnIndex = 0 + columnIndex = 0 } // Assume cursor is created for immediate iteration: reset and set arguments @@ -164,50 +161,19 @@ public final class FastDatabaseValueCursor Value? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - // TODO GRDB6: don't crash on decoding errors - return try! Value.fastDecode( - fromStatement: _sqliteStatement, - atUncheckedIndex: _columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } + public func _element(sqliteStatement: SQLiteStatement) -> Value { + // TODO GRDB6: don't crash on decoding errors + try! Value.fastDecode( + fromStatement: sqliteStatement, + atUncheckedIndex: columnIndex, + context: RowDecodingContext(statement: statement, index: Int(columnIndex))) } } @@ -221,27 +187,22 @@ public final class FastDatabaseValueCursor") /// } /// } -public final class FastNullableDatabaseValueCursor: Cursor +public final class FastNullableDatabaseValueCursor: DatabaseCursor where Value: DatabaseValueConvertible & StatementColumnConvertible { - @usableFromInline - enum _State { - case idle, busy, done, failed - } - - @usableFromInline let _statement: Statement - @usableFromInline let _columnIndex: Int32 - @usableFromInline let _sqliteStatement: SQLiteStatement - @usableFromInline var _state = _State.idle + public typealias Element = Value? + public let statement: Statement + /// :nodoc: + public var _isDone = false + @usableFromInline let columnIndex: Int32 init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - _statement = statement - _sqliteStatement = statement.sqliteStatement + self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column - _columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) + columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { - _columnIndex = 0 + columnIndex = 0 } // Assume cursor is created for immediate iteration: reset and set arguments @@ -249,50 +210,19 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible } deinit { - if _state == .busy { - try? _statement.database.statementDidExecute(_statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? _statement.reset() + try? statement.reset() } + /// :nodoc: @inlinable - public func next() throws -> Value?? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - // TODO GRDB6: don't crash on decoding errors - return try! Value.fastDecodeIfPresent( - fromStatement: _sqliteStatement, - atUncheckedIndex: _columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } + public func _element(sqliteStatement: SQLiteStatement) -> Value? { + // TODO GRDB6: don't crash on decoding errors + try! Value.fastDecodeIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: columnIndex, + context: RowDecodingContext(statement: statement, index: Int(columnIndex))) } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 22b274b7c..5a3859005 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -196,6 +196,8 @@ extension FetchableRecord { adapter: RowAdapter? = nil) throws -> [Self] { + // Use Array initializer in order to deal with . + // See `Statement.forEachStep(_:)` for more information. try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -511,93 +513,28 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// try dbQueue.read { db in /// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RecordCursor: Cursor { - private enum _State { - case idle, busy, done, failed - } - - private let _statement: Statement - private let _row: Row // Reused for performance - private let _sqliteStatement: SQLiteStatement - private var _state = _State.idle +public final class RecordCursor: DatabaseCursor { + public typealias Element = Record + public let statement: Statement + /// :nodoc: + public var _isDone = false + private let row: Row // Instanciated once, reused for performance init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - _statement = statement - _row = try Row(statement: statement).adapted(with: adapter, layout: statement) - _sqliteStatement = statement.sqliteStatement - - // Assume cursor is created for immediate iteration: reset and set arguments + self.statement = statement + row = try Row(statement: statement).adapted(with: adapter, layout: statement) statement.reset(withArguments: arguments) } deinit { - if _state == .busy { - try? _statement.database.statementDidExecute(_statement) - } - // Statement reset fails when sqlite3_step has previously failed. // Just ignore reset error. - try? _statement.reset() + try? statement.reset() } - public func next() throws -> Record? { - switch _state { - case .done: - // make sure this instance never yields a value again, even if the - // statement is reset by another cursor. - return nil - case .idle: - guard try _statement.database.statementWillExecute(_statement) == nil else { - throw DatabaseError( - resultCode: SQLITE_MISUSE, - message: "Can't run statement that requires a customized authorizer from a cursor", - sql: _statement.sql, - arguments: _statement.arguments) - } - _state = .busy - default: - break - } - - switch sqlite3_step(_sqliteStatement) { - case SQLITE_DONE: - _state = .done - try _statement.database.statementDidExecute(_statement) - return nil - case SQLITE_ROW: - return Record(row: _row) - case let code: - _state = .failed - try _statement.database.statementDidFail(_statement, withResultCode: code) - } - } - - // Specific override in order to deal with https://github.com/groue/GRDB.swift/issues/1124 /// :nodoc: - public func forEach(_ body: (Record) throws -> Void) throws { - switch _state { - case .busy: - // We can't deal with possible authorizer - fatalError("Not implemented") - case .idle: - if let authorizer = try _statement.database.statementWillExecute(_statement) { - _state = .busy - try _statement.database.withAuthorizer(authorizer) { - while let element = try next() { - try body(element) - } - } - } else { - _state = .busy - while let element = try next() { - try body(element) - } - } - default: - while let element = try next() { - try body(element) - } - } + public func _element(sqliteStatement: SQLiteStatement) -> Record { + Record(row: row) } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index be78267a9..3174db7b7 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -246,4 +246,24 @@ class CursorTests: GRDBTestCase { XCTAssertEqual(dictionary, [1: "a", 2: "b", 3: "a"]) } } + + func testArrayInitializer() throws { + // Test that Array initializer calls `forEach`. + // This is important in order to prevent + // + class TestCursor: Cursor { + func next() -> Int? { + fatalError("Must not be called during Array creation") + } + + func forEach(_ body: (Int) throws -> Void) throws { + try body(0) + try body(1) + } + } + + let cursor = TestCursor() + let elements = try Array(cursor) + XCTAssertEqual(elements, [0, 1]) + } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index c74f53e55..0eec5784c 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -166,4 +166,121 @@ class DatabaseCursorTests: GRDBTestCase { // sqlite3_close_v2(connection) // } } + + // For profiling tests + let profilingSQL = """ + WITH RECURSIVE + cnt(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM cnt WHERE x<10000000) + SELECT x FROM cnt + """ + + // Profiling test + func testRowCursorStep() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: RowCursor = try Row.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testRowCursorForEach() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: RowCursor = try Row.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } + + // Profiling test + func testDatabaseValueCursorStep() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: DatabaseValueCursor = try Int.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testDatabaseValueCursorForEach() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: DatabaseValueCursor = try Int.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } + + // Profiling test + func testNullableDatabaseValueCursorStep() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: NullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testNullableDatabaseValueCursorForEach() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: NullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } + + // Profiling test + func testFastDatabaseValueCursorStep() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: FastDatabaseValueCursor = try Int.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testFastDatabaseValueCursorForEach() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: FastDatabaseValueCursor = try Int.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } + + // Profiling test + func testFastNullableDatabaseValueCursorStep() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: FastNullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testFastNullableDatabaseValueCursorForEach() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: FastNullableDatabaseValueCursor = try Optional.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } + + // Profiling test + func testRecordCursorStep() throws { + struct S: FetchableRecord { init(row: Row) { } } + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: RecordCursor = try S.fetchCursor(db, sql: profilingSQL) + while let _ = try cursor.next() { } + } + } + + // Profiling test + func testRecordCursorForEach() throws { + struct S: FetchableRecord { init(row: Row) { } } + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let cursor: RecordCursor = try S.fetchCursor(db, sql: profilingSQL) + try cursor.forEach { _ in } + } + } } diff --git a/Tests/GRDBTests/EnumeratedCursorTests.swift b/Tests/GRDBTests/EnumeratedCursorTests.swift index f88165a2c..aff45dfb1 100644 --- a/Tests/GRDBTests/EnumeratedCursorTests.swift +++ b/Tests/GRDBTests/EnumeratedCursorTests.swift @@ -18,6 +18,31 @@ class EnumeratedCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } + func testEnumeratedCursorForEach() throws { + // Test that enumerated().forEach() calls base.forEach(). + // This is important in order to prevent + // + class TestCursor: Cursor { + func next() -> String? { + fatalError("Must not be called during forEach") + } + + func forEach(_ body: (String) throws -> Void) throws { + try body("foo") + try body("bar") + } + } + + let base = TestCursor() + let cursor = base.enumerated() + let elements = try Array(cursor) + XCTAssertEqual(elements.count, 2) + XCTAssertEqual(elements[0].0, 0) + XCTAssertEqual(elements[0].1, "foo") + XCTAssertEqual(elements[1].0, 1) + XCTAssertEqual(elements[1].1, "bar") + } + func testEnumeratedCursorFromThrowingCursor() throws { var i = 0 let strings = ["foo", "bar"] diff --git a/Tests/GRDBTests/FilterCursorTests.swift b/Tests/GRDBTests/FilterCursorTests.swift index 6fb58faa5..b15accaf0 100644 --- a/Tests/GRDBTests/FilterCursorTests.swift +++ b/Tests/GRDBTests/FilterCursorTests.swift @@ -14,6 +14,28 @@ class FilterCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } + func testFilterCursorForEach() throws { + // Test that filter().forEach() calls base.forEach(). + // This is important in order to prevent + // + class TestCursor: Cursor { + func next() -> Int? { + fatalError("Must not be called during forEach") + } + + func forEach(_ body: (Int) throws -> Void) throws { + try body(1) + try body(2) + try body(3) + try body(4) + } + } + + let base = TestCursor() + let cursor = base.filter { $0 % 2 == 0 } + try XCTAssertEqual(Array(cursor), [2, 4]) + } + func testFilterCursorFromThrowingCursor() { var i = 0 let base: AnyCursor = AnyCursor { diff --git a/Tests/GRDBTests/MapCursorTests.swift b/Tests/GRDBTests/MapCursorTests.swift index 44e294287..423d4bea9 100644 --- a/Tests/GRDBTests/MapCursorTests.swift +++ b/Tests/GRDBTests/MapCursorTests.swift @@ -13,6 +13,26 @@ class MapCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) } + func testMapCursorForEach() throws { + // Test that map().forEach() calls base.forEach(). + // This is important in order to prevent + // + class TestCursor: Cursor { + func next() -> Int? { + fatalError("Must not be called during forEach") + } + + func forEach(_ body: (Int) throws -> Void) throws { + try body(1) + try body(2) + } + } + + let base = TestCursor() + let cursor = base.map { $0 * $0 } + try XCTAssertEqual(Array(cursor), [1, 4]) + } + func testMapThrowingCursor() { var i = 0 let base: AnyCursor = AnyCursor { diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b6471ff35..b03d8560e 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -29,7 +29,7 @@ class SelectStatementTests : GRDBTestCase { let cursor = try statement.makeCursor() // Check that StatementCursor gives access to the raw SQLite API - XCTAssertEqual(String(cString: sqlite3_column_name(cursor._statement.sqliteStatement, 0)), "firstName") + XCTAssertEqual(String(cString: sqlite3_column_name(cursor.statement.sqliteStatement, 0)), "firstName") XCTAssertFalse(try cursor.next() == nil) XCTAssertFalse(try cursor.next() == nil) @@ -44,7 +44,7 @@ class SelectStatementTests : GRDBTestCase { let customError = NSError(domain: "Custom", code: 0xDEAD) db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) func test(_ cursor: StatementCursor) throws { - let sql = cursor._statement.sql + let sql = cursor.statement.sql do { _ = try cursor.next() XCTFail() diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index 8fa998997..e8c161540 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -202,7 +202,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.write(_insertPositionalValues) - dbQueue.read { db in + try dbQueue.read { db in assert(try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")! == insertedRowCount) assert(try! Int.fetchOne(db, sql: "SELECT MIN(i0) FROM items")! == 0) assert(try! Int.fetchOne(db, sql: "SELECT MAX(i9) FROM items")! == insertedRowCount - 1) @@ -231,7 +231,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.write(_insertNamedValues) - dbQueue.read { db in + try dbQueue.read { db in assert(try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")! == insertedRowCount) assert(try! Int.fetchOne(db, sql: "SELECT MIN(i0) FROM items")! == 0) assert(try! Int.fetchOne(db, sql: "SELECT MAX(i9) FROM items")! == insertedRowCount - 1) @@ -260,7 +260,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.write(_insertStructs) - dbQueue.read { db in + try dbQueue.read { db in assert(try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")! == insertedRowCount) assert(try! Int.fetchOne(db, sql: "SELECT MIN(i0) FROM items")! == 0) assert(try! Int.fetchOne(db, sql: "SELECT MAX(i9) FROM items")! == insertedRowCount - 1) @@ -288,7 +288,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.write(_insertCodables) - dbQueue.read { db in + try dbQueue.read { db in assert(try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")! == insertedRowCount) assert(try! Int.fetchOne(db, sql: "SELECT MIN(i0) FROM items")! == 0) assert(try! Int.fetchOne(db, sql: "SELECT MAX(i9) FROM items")! == insertedRowCount - 1) @@ -316,7 +316,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.write(_insertRecords) - dbQueue.read { db in + try dbQueue.read { db in assert(try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")! == insertedRowCount) assert(try! Int.fetchOne(db, sql: "SELECT MIN(i0) FROM items")! == 0) assert(try! Int.fetchOne(db, sql: "SELECT MAX(i9) FROM items")! == insertedRowCount - 1)