Mik*_*ing 4 javascript sql postgresql knex.js
我最初发现当我尝试搜索带有主题标签的术语时,这是一个问题,事实证明它是SQL中的注释分隔符.搜索没有返回任何内容,因为它忽略了hashtag后面的#term.
所以现在我无法找到逃避用户输入的正确方法.在我看来,这既解决了标签问题,也解决了更大的问题,SQL注入.
以下是我正在使用的片段:
function (term) {
term = term.toLowerCase()
return db('ticket')
.select('*')
.where(db.raw('lower(question)'), 'like', `%${term}%`)
.orWhere(db.raw('lower(note)'), 'like', `%${term}%`)
.orWhere(db.raw('lower(user_name)'), 'like', `%${term}%`)
}
Run Code Online (Sandbox Code Playgroud)
我也发现这个和这个 SO文章似乎很近,还有几个其他的事情.此外,Knex的文档和其他来源建议参数化绑定作为防止SQL注入的方法.
我很难找到一个可以用JavaScript或使用Knex向我解释的明确示例.
我不是Knex.js用户,但是看看文档似乎Knex使用JavaScript对象语法来定义谓词就是它如何实现参数化.
但是,当您使用内置函数时,需要使用whereRaw.
查看文档(http://knexjs.org/#Builder-whereRaw)和(http://knexjs.org/#Raw-Bindings)我认为你想这样做:
.whereRaw('question LIKE :term OR note LIKE :term OR user_name LIKE :term', { term: '%' + term + '%' ] } )
Run Code Online (Sandbox Code Playgroud)
Knex没有orWhereRaw,所以如果你想在逻辑上分离谓词,你应该使用longhand版本:
term = '%' + term + '%';
.orWhere( knex.raw( 'question LIKE ?', [ term ] ) )
.orWhere( knex.raw( 'note LIKE ?', [ term ] ) )
.orWhere( knex.raw( 'user_name LIKE ?', [ term ] ) )
Run Code Online (Sandbox Code Playgroud)
注意?是位置参数,:term用于命名参数.