Skip to content

Commit

Permalink
Merge pull request #1119 from GreenJell0/Statement_prepareRowIterator
Browse files Browse the repository at this point in the history
Add prepareRowIterator method to an extension of Statement.
  • Loading branch information
nathanfallet authored Mar 27, 2022
2 parents c897ce9 + 6c77a2d commit c93728f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Documentation/Index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1963,6 +1963,14 @@ using the following functions.
}
}
```
Statements with results may be iterated over, using a `RowIterator` if
useful.

```swift
let emailColumn = Expression<String>("email")
let stmt = try db.prepare("SELECT id, email FROM users")
let emails = try! stmt.prepareRowIterator().map { $0[emailColumn] }
```

- `run` prepares a single `Statement` object from a SQL string, optionally
binds values to it (using the statement’s `bind` function), executes,
Expand Down
15 changes: 15 additions & 0 deletions Sources/SQLite/Core/Statement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,21 @@ extension Statement: FailableIterator {
}
}

extension Statement {
public func prepareRowIterator() -> RowIterator {
return RowIterator(statement: self, columnNames: self.columnNameMap)
}

var columnNameMap: [String: Int] {
var result = [String: Int]()
for (index, name) in self.columnNames.enumerated() {
result[name.quote()] = index
}

return result
}
}

extension Statement: CustomStringConvertible {

public var description: String {
Expand Down
11 changes: 11 additions & 0 deletions Tests/SQLiteTests/StatementTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,15 @@ class StatementTests: SQLiteTestCase {
let blobValue = try! db.scalar(blobs.select(blobColumn).limit(1, offset: 0))
XCTAssertEqual([], blobValue.bytes)
}

func test_prepareRowIterator() {
let names = ["a", "b", "c"]
try! insertUsers(names)

let emailColumn = Expression<String>("email")
let statement = try! db.prepare("SELECT email FROM users")
let emails = try! statement.prepareRowIterator().map { $0[emailColumn] }

XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
}

0 comments on commit c93728f

Please sign in to comment.