File tree Expand file tree Collapse file tree 3 files changed +34
-0
lines changed Expand file tree Collapse file tree 3 files changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -1963,6 +1963,14 @@ using the following functions.
19631963 }
19641964 }
19651965 ```
1966+ Statements with results may be iterated over, using a `RowIterator` if
1967+ useful.
1968+
1969+ ```swift
1970+ let emailColumn = Expression< String > (" email" )
1971+ let stmt = try db.prepare (" SELECT id, email FROM users" )
1972+ let emails = try ! stmt.prepareRowIterator ().map { $0 [emailColumn] }
1973+ ```
19661974
19671975 - `run` prepares a single `Statement` object from a SQL string, optionally
19681976 binds values to it (using the statement’s `bind` function), executes,
Original file line number Diff line number Diff line change @@ -228,6 +228,21 @@ extension Statement: FailableIterator {
228228 }
229229}
230230
231+ extension Statement {
232+ public func prepareRowIterator( ) -> RowIterator {
233+ return RowIterator ( statement: self , columnNames: self . columnNameMap)
234+ }
235+
236+ var columnNameMap : [ String : Int ] {
237+ var result = [ String: Int] ( )
238+ for (index, name) in self . columnNames. enumerated ( ) {
239+ result [ name. quote ( ) ] = index
240+ }
241+
242+ return result
243+ }
244+ }
245+
231246extension Statement : CustomStringConvertible {
232247
233248 public var description : String {
Original file line number Diff line number Diff line change @@ -23,4 +23,15 @@ class StatementTests: SQLiteTestCase {
2323 let blobValue = try ! db. scalar ( blobs. select ( blobColumn) . limit ( 1 , offset: 0 ) )
2424 XCTAssertEqual ( [ ] , blobValue. bytes)
2525 }
26+
27+ func test_prepareRowIterator( ) {
28+ let names = [ " a " , " b " , " c " ]
29+ try ! insertUsers ( names)
30+
31+ let emailColumn = Expression < String > ( " email " )
32+ let statement = try ! db. prepare ( " SELECT email FROM users " )
33+ let emails = try ! statement. prepareRowIterator ( ) . map { $0 [ emailColumn] }
34+
35+ XCTAssertEqual ( names. map ( { " \( $0) @example.com " } ) , emails. sorted ( ) )
36+ }
2637}
You can’t perform that action at this time.
0 commit comments