diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index dd0062330..b59a5a564 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -1,59 +1,65 @@ +extension Array { + /// TODO + public init(_ cursor: C) throws where C.Element == Element { + // TODO: cursors should have an underestimatedCount + self.init() + while let element = try cursor.next() { + append(element) + } + } +} + /// A type that supplies the values of a sequence one at a time. -public protocol Cursor { +public protocol Cursor : class { + // TODO: explain that Cursor is a class because it is designed to wrap an + // external resource such as a SQLite statement. /// TODO associatedtype Element + /// TODO func next() throws -> Element? } +/// TODO +class AnyCursor : Cursor { + /// TODO + init(_ base: C) where C.Element == Element { + element = base.next + } + + /// TODO + func next() throws -> Element? { + return try element() + } + + private let element: () throws -> Element? +} + extension Cursor { /// TODO - public func enumerated() -> EnumeratedCursor { + public func enumerated() -> EnumeratedCursor { return EnumeratedCursor(self) } /// TODO - public func filter(_ isIncluded: (Element) throws -> Bool) throws -> [Element] { - var result: [Element] = [] - while let element = try next() { - if try isIncluded(element) { - result.append(element) - } - } - return result + public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor { + return FilterCursor(self, isIncluded) } /// TODO - public func flatMap(_ transform: (Element) throws -> ElementOfResult?) throws -> [ElementOfResult] { - var result: [ElementOfResult] = [] - while let element = try next() { - if let x = try transform(element) { - result.append(x) - } - } - return result + public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + return map(transform).filter { $0 != nil }.map { $0! } } /// TODO - public func flatMap(_ transform: (Element) throws -> SegmentOfResult) throws -> [SegmentOfResult.Iterator.Element] { - var result: [SegmentOfResult.Iterator.Element] = [] - while let element = try next() { - try result.append(contentsOf: transform(element)) - } - return result + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + return flatMap { try IteratorCursor(transform($0).makeIterator()) } } /// TODO - public func flatMap(_ transform: (Element) throws -> SegmentOfResult) throws -> [SegmentOfResult.Element] { - var result: [SegmentOfResult.Element] = [] - while let element1 = try next() { - let cursor = try transform(element1) - while let element2 = try cursor.next() { - result.append(element2) - } - } - return result + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor> { + return FlattenCursor(map(transform)) } /// TODO @@ -64,13 +70,13 @@ extension Cursor { } /// TODO - public func map(_ transform: (Element) throws -> T) throws -> [T] { - // TODO: cursors should have an underestimatedCount - var result: [T] = [] - while let element = try next() { - try result.append(transform(element)) - } - return result + public var lazy: CursorLazySequence { + return CursorLazySequence(self) + } + + /// TODO + public func map(_ transform: @escaping (Element) throws -> T) -> MapCursor { + return MapCursor(self, transform) } /// TODO @@ -83,48 +89,125 @@ extension Cursor { } } +/// TODO +public final class CursorLazySequence : LazySequenceProtocol, IteratorProtocol { + init(_ base: Base) { + self.base = base + } + + /// TODO + public func makeIterator() -> CursorLazySequence { + return self + } + + /// TODO + public func next() -> Base.Element? { + return try! base.next() + } + + private let base: Base +} + +/// TODO +public final class EnumeratedCursor : Cursor { + init(_ base: Base) { + self.index = 0 + self.base = base + } + + /// TODO + public func next() throws -> (Int, Base.Element)? { + guard let element = try base.next() else { return nil } + defer { index += 1 } + return (index, element) + } + + private var index: Int + private var base: Base +} + +/// TODO +public final class FilterCursor : Cursor { + init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) { + self.base = base + self.isIncluded = isIncluded + } + + /// TODO + public func next() throws -> Base.Element? { + while let element = try base.next() { + if try isIncluded(element) { + return element + } + } + return nil + } + + private let base: Base + private let isIncluded: (Base.Element) throws -> Bool +} + +/// TODO +public final class FlattenCursor : Cursor where Base.Element: Cursor { + init(_ base: Base) { + self.base = base + } + + /// TODO + public func next() throws -> Base.Element.Element? { + while true { + if let inner = inner { + if let element = try inner.next() { + return element + } + } + guard let inner = try base.next() else { + return nil + } + self.inner = inner + } + } + + private var inner: Base.Element? + private let base: Base +} + +/// TODO +public final class MapCursor : Cursor { + init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) { + self.base = base + self.transform = transform + } + + /// TODO + public func next() throws -> Element? { + guard let element = try base.next() else { return nil } + return try transform(element) + } + + private let base: Base + private let transform: (Base.Element) throws -> Element +} + +/// TODO +public final class IteratorCursor : Cursor { + // TODO: remove this type when `extension IteratorProtocol : Cursor { }` can be written + init(_ base: Base) { + self.base = base + } + + /// TODO + public func next() -> Base.Element? { + return base.next() + } + + private var base: Base +} + extension Sequence { /// TODO - public func flatMap(_ transform: (Iterator.Element) throws -> SegmentOfResult) throws -> [SegmentOfResult.Element] { - var result: [SegmentOfResult.Element] = [] - for element1 in self { - let cursor = try transform(element1) - while let element2 = try cursor.next() { - result.append(element2) - } - } - return result - } -} - - -/// TODO -public struct EnumeratedCursor : Cursor { - private var element: () throws -> (Int, Element)? - - init(_ cursor: C) where C.Element == Element { - var i = 0 - element = { - guard let elem = try cursor.next() else { return nil } - defer { i += 1 } - return (i, elem) - } - } - - /// TODO - public func next() throws -> (Int, Element)? { - return try element() - } -} - -extension Array { - /// TODO - public init(_ cursor: C) throws where C.Element == Element { - // TODO: cursors should have an underestimatedCount - self.init() - while let element = try cursor.next() { - append(element) - } + public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + return IteratorCursor(makeIterator()).flatMap(transform) } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 069c50237..ba7ed03ca 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1090,10 +1090,10 @@ extension Database { return indexes } - let indexes = try Row.fetchCursor(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in + let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in let indexName: String = row.value(atIndex: 1) let unique: Bool = row.value(atIndex: 2) - let columns = try Row.fetchCursor(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") + let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") .map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) } .sorted { $0.0 < $1.0 } .map { $0.1 } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 1e408082a..64d68b396 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -549,7 +549,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { - return try fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() } + return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) } /// Returns a single row fetched from a prepared statement. diff --git a/Tests/Public/Core/DatabaseCursor/DatabaseCursorTests.swift b/Tests/Public/Core/DatabaseCursor/DatabaseCursorTests.swift index 6d4775847..566b95d3f 100644 --- a/Tests/Public/Core/DatabaseCursor/DatabaseCursorTests.swift +++ b/Tests/Public/Core/DatabaseCursor/DatabaseCursorTests.swift @@ -57,8 +57,10 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT 1 AS i UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 ORDER BY i") - let odds = try cursor.filter { $0 % 2 == 1 } - XCTAssertEqual(odds, [1, 3]) + let odds = cursor.filter { $0 % 2 == 1 } + XCTAssertEqual(try odds.next()!, 1) + XCTAssertEqual(try odds.next()!, 3) + XCTAssertTrue(try odds.next() == nil) } } } @@ -68,8 +70,12 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT 1 AS i UNION ALL SELECT 2 ORDER BY i") - let ints = try cursor.flatMap { AnySequence([$0, $0 + 1]) } - XCTAssertEqual(ints, [1, 2, 2, 3]) + let ints = cursor.flatMap { AnySequence([$0, $0 + 1]) } + XCTAssertEqual(try ints.next()!, 1) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 3) + XCTAssertTrue(try ints.next() == nil) } } } @@ -79,10 +85,14 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT 1 AS i UNION ALL SELECT 2 ORDER BY i") - let ints = try cursor.flatMap { + let ints = cursor.flatMap { try Int.fetchCursor(db, "SELECT ? AS i UNION ALL SELECT ?+1 ORDER BY i", arguments: [$0, $0]) } - XCTAssertEqual(ints, [1, 2, 2, 3]) + XCTAssertEqual(try ints.next()!, 1) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 3) + XCTAssertTrue(try ints.next() == nil) } } } @@ -92,10 +102,14 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let sequence = AnySequence([1, 2]) - let ints = try sequence.flatMap { + let ints = sequence.flatMap { try Int.fetchCursor(db, "SELECT ? AS i UNION ALL SELECT ?+1 ORDER BY i", arguments: [$0, $0]) } - XCTAssertEqual(ints, [1, 2, 2, 3]) + XCTAssertEqual(try ints.next()!, 1) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 2) + XCTAssertEqual(try ints.next()!, 3) + XCTAssertTrue(try ints.next() == nil) } } } @@ -105,8 +119,9 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try DatabaseValue.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 1") - let ints = try cursor.flatMap(Int.fromDatabaseValue) - XCTAssertEqual(ints, [1]) + let ints = cursor.flatMap(Int.fromDatabaseValue) + XCTAssertEqual(try ints.next()!, 1) + XCTAssertTrue(try ints.next() == nil) } } } @@ -128,8 +143,10 @@ class DatabaseCursorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT 1 AS i UNION ALL SELECT 2 ORDER BY i") - let squares = try cursor.map { $0 * $0 } - XCTAssertEqual(squares, [1, 4]) + let squares = cursor.map { $0 * $0 } + XCTAssertEqual(try squares.next()!, 1) + XCTAssertEqual(try squares.next()!, 4) + XCTAssertTrue(try squares.next() == nil) } } } diff --git a/Tests/Public/Core/Row/MetalRowTests.swift b/Tests/Public/Core/Row/MetalRowTests.swift index cb048c566..f10dafa36 100644 --- a/Tests/Public/Core/Row/MetalRowTests.swift +++ b/Tests/Public/Core/Row/MetalRowTests.swift @@ -386,8 +386,11 @@ class MetalRowTests : RowTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let cursor = try Row.fetchCursor(db, "SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3") - let values = try cursor.map { $0.value(atIndex: 0) as Int } - XCTAssertEqual(values, [1, 2, 3]) + let values = cursor.map { $0.value(atIndex: 0) as Int } + XCTAssertEqual(try values.next()!, 1) + XCTAssertEqual(try values.next()!, 2) + XCTAssertEqual(try values.next()!, 3) + XCTAssertTrue(try values.next() == nil) } } } diff --git a/Tests/Public/QueryInterfaceRequest/Record+QueryInterfaceRequestTests.swift b/Tests/Public/QueryInterfaceRequest/Record+QueryInterfaceRequestTests.swift index 460489460..a90faae1f 100644 --- a/Tests/Public/QueryInterfaceRequest/Record+QueryInterfaceRequestTests.swift +++ b/Tests/Public/QueryInterfaceRequest/Record+QueryInterfaceRequestTests.swift @@ -91,9 +91,11 @@ class RecordQueryInterfaceRequestTests: GRDBTestCase { do { let cursor = try request.fetchCursor(db) - let names = try cursor.map { $0.name } + let names = cursor.map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") - XCTAssertEqual(names, [arthur.name, barbara.name]) + XCTAssertEqual(try names.next()!, arthur.name) + XCTAssertEqual(try names.next()!, barbara.name) + XCTAssertTrue(try names.next() == nil) } } } diff --git a/Tests/Public/QueryInterfaceRequest/RowConvertible+QueryInterfaceRequestTests.swift b/Tests/Public/QueryInterfaceRequest/RowConvertible+QueryInterfaceRequestTests.swift index 05f47dbf2..c6581e774 100644 --- a/Tests/Public/QueryInterfaceRequest/RowConvertible+QueryInterfaceRequestTests.swift +++ b/Tests/Public/QueryInterfaceRequest/RowConvertible+QueryInterfaceRequestTests.swift @@ -100,7 +100,9 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { do { let names = try request.fetchCursor(db).map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") - XCTAssertEqual(names, [arthur.name, barbara.name]) + XCTAssertEqual(try names.next()!, arthur.name) + XCTAssertEqual(try names.next()!, barbara.name) + XCTAssertTrue(try names.next() == nil) } } } @@ -137,9 +139,11 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { do { let cursor = try Reader.fetchCursor(db) - let names = try cursor.map { $0.name } + let names = cursor.map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") - XCTAssertEqual(names, [arthur.name, barbara.name]) + XCTAssertEqual(try names.next()!, arthur.name) + XCTAssertEqual(try names.next()!, barbara.name) + XCTAssertTrue(try names.next() == nil) } } } @@ -179,7 +183,9 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { do { let names = try AltReader.fetchCursor(db, request).map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") - XCTAssertEqual(names, [arthur.name, barbara.name]) + XCTAssertEqual(try names.next()!, arthur.name) + XCTAssertEqual(try names.next()!, barbara.name) + XCTAssertTrue(try names.next() == nil) } } }