Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cursor type for more safety. #726

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Sources/SQLite/Core/Statement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,14 @@ public final class Statement {

}

extension Statement {

func rowCursorNext() throws -> [Binding?]? {
return try step() ? Array(row) : nil
}

}

extension Statement : Sequence {

public func makeIterator() -> Statement {
Expand Down
111 changes: 71 additions & 40 deletions Sources/SQLite/Typed/Query.swift
Original file line number Diff line number Diff line change
Expand Up @@ -894,58 +894,89 @@ public struct Delete : ExpressionType {

}

public struct RowCursor {
let statement: Statement
let columnNames: [String: Int]

public func next() throws -> Row? {
return try statement.rowCursorNext().flatMap { Row(columnNames, $0) }
}

public func map<T>(_ transform: (Row) throws -> T) throws -> [T] {
var elements = [T]()
while true {
if let row = try next() {
elements.append(try transform(row))
} else {
break
}
}

return elements
}
}

extension Connection {

public func prepareCursor(_ query: QueryType) throws -> RowCursor {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)
return RowCursor(statement: statement, columnNames: try columnNamesForQuery(query))
}

public func prepare(_ query: QueryType) throws -> AnySequence<Row> {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)

let columnNames: [String: Int] = try {
var (columnNames, idx) = ([String: Int](), 0)
column: for each in query.clauses.select.columns {
var names = each.expression.template.characters.split { $0 == "." }.map(String.init)
let column = names.removeLast()
let namespace = names.joined(separator: ".")

func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) {
return { (query: QueryType) throws -> (Void) in
var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database)
q.clauses.select = query.clauses.select
let e = q.expression
var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() }
if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } }
for name in names { columnNames[name] = idx; idx += 1 }
}
}
let columnNames = try columnNamesForQuery(query)

if column == "*" {
var select = query
select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible])
let queries = [select] + query.clauses.join.map { $0.query }
if !namespace.isEmpty {
for q in queries {
if q.tableName().expression.template == namespace {
try expandGlob(true)(q)
continue column
}
return AnySequence {
AnyIterator { statement.next().map { Row(columnNames, $0) } }
}
}

private func columnNamesForQuery(_ query: QueryType) throws -> [String: Int] {
var (columnNames, idx) = ([String: Int](), 0)
column: for each in query.clauses.select.columns {
var names = each.expression.template.characters.split { $0 == "." }.map(String.init)
let column = names.removeLast()
let namespace = names.joined(separator: ".")

func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) {
return { (query: QueryType) throws -> (Void) in
var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database)
q.clauses.select = query.clauses.select
let e = q.expression
var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() }
if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } }
for name in names { columnNames[name] = idx; idx += 1 }
}
}

if column == "*" {
var select = query
select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible])
let queries = [select] + query.clauses.join.map { $0.query }
if !namespace.isEmpty {
for q in queries {
if q.tableName().expression.template == namespace {
try expandGlob(true)(q)
continue column
}
throw QueryError.noSuchTable(name: namespace)
}
for q in queries {
try expandGlob(query.clauses.join.count > 0)(q)
}
continue
fatalError("no such table: \(namespace)")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should probably be QueryError.noSuchTable?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call. Sorry I took so long to make this simple change.

}

columnNames[each.expression.template] = idx
idx += 1
for q in queries {
try expandGlob(query.clauses.join.count > 0)(q)
}
continue
}
return columnNames
}()

return AnySequence {
AnyIterator { statement.next().map { Row(columnNames, $0) } }

columnNames[each.expression.template] = idx
idx += 1
}
return columnNames
}

public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V {
Expand All @@ -971,7 +1002,7 @@ extension Connection {
}

public func pluck(_ query: QueryType) throws -> Row? {
return try prepare(query.limit(1, query.clauses.limit?.offset)).makeIterator().next()
return try prepareCursor(query.limit(1, query.clauses.limit?.offset)).next()
}

/// Runs an `Insert` query.
Expand Down
10 changes: 10 additions & 0 deletions Tests/SQLiteTests/QueryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,16 @@ class QueryIntegrationTests : SQLiteTestCase {
_ = user[users[managerId]]
}
}

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

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

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

func test_select_optional() {
for _ in try! db.prepare(users) {
Expand Down