Skip to content

Commit c93728f

Browse files
authored
Merge pull request #1119 from GreenJell0/Statement_prepareRowIterator
Add prepareRowIterator method to an extension of Statement.
2 parents c897ce9 + 6c77a2d commit c93728f

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

Documentation/Index.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff 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,

Sources/SQLite/Core/Statement.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
231246
extension Statement: CustomStringConvertible {
232247

233248
public var description: String {

Tests/SQLiteTests/StatementTests.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)