更正变量绑定并避免使用 SQLite.swift 查询进行 SQL 注入

Correct variable binding and avoiding SQL injection with SQLite.swift queries

SQLite.swift documentation for filtered queries给出了这个例子:

users.filter(email.like("%@mac.com"))
// SELECT * FROM "users" WHERE ("email" LIKE '%@mac.com')

因为我想根据用户输入搜索数据库,我想我可以这样做:

let stringPrefix = userInput + "%"
users.filter(email.like(stringPrefix))
// SELECT * FROM "users" WHERE ("email" LIKE 'johndoe%')

我这样做的方式正确吗?在过去的其他 SQLite 环境中,我使用了 variable binding with ? to avoid SQL injection. Is this done behind the scenes with SQLite.swift? I didn't see any information in the documentation except for a little bit about binding in the Executing Arbitrary SQL 部分。

取自 this 源文件:

@warn_unused_result public func like(pattern: String, escape character: Character? = nil) -> Expression<Bool> {
    guard let character = character else {
        return "LIKE".infix(self, pattern)
    }
    return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}

这只是 like 函数的重载之一。另一个重载看起来非常相似,并且确实也使用了参数绑定。自己去源码里逛一逛,自己验证一下。

但是,我希望您进行内部测试以验证 SQLite 注入是不可能的。