转义包含通配符字符(如%和_)的LIKE参数。

huangapple go评论99阅读模式
英文:

Escape LIKE parameters containing wildcard characters like % (and _)

问题

GORM文档中有一个示例,展示了如何使用LIKE条件:

// LIKE
db.Where("name LIKE ?", "%jin%").Find(&users)
// SELECT * FROM users WHERE name LIKE '%jin%';

我对这种方法的问题是,如果jin是用户输入的变量,它可能包含通配符符号,比如%。我该如何转义这些通配符符号?

对我来说,这些符号必须在左侧使用,比如:

db.Where("name LIKE %?%", "jin").Find(&users)

或者

db.Where("name LIKE '%' || ? || '%'", "jin").Find(&users)

ORM应该自动转义参数,但实际上它并不是这样工作的。

正确的解决方案是什么?

英文:

In GORM documentation there is an example how to use LIKE conditions:

// LIKE
db.Where("name LIKE ?", "%jin%").Find(&users)
// SELECT * FROM users WHERE name LIKE '%jin%';

The problem that I have with this approach is that if jin is user input variable it can contain wildcard symbols like %. How can I escape such wildcard symbols?

For me these symbols must be used in the left part like:

db.Where("name LIKE %?%", "jin").Find(&users)

OR

db.Where("name LIKE '%' || ? || '%'", "jin").Find(&users)

and the ORM should escape automatically the parameter, but this is not how it behaves.

What is the right solution?

答案1

得分: 1

尝试明确替换通配符:

db.Where("name LIKE '%' || replace(replace(?, '%', '\\%'), '_', '\\_') || '%'", "jin").Find(&users)
英文:

Try to explicitly replace the wildcards:

db.Where("name LIKE '%' || replace(replace(?, '%', '\%), '_', '\_') || '%'", "jin").Find(&users)

答案2

得分: 0

明白了,以下是翻译好的内容:

明确进行转义。

db.Where("name like '%'||?||'%' escape '\'", userinput)

并且在将用户输入传递给 db.Where 之前,提前转义用户输入中的通配符符号。用户输入中的反斜杠也应该加倍。

无关的是,我更喜欢使用正则表达式的 ~~* 运算符,而不是 like

英文:

Escape explicitly.

db.Where("name like '%'||?||'%' escape '\'", userinput)

and escape wildcard symbols in the user input upfront before passing to db.Where. Backslashes in the user input shall be doubled too.

Unrelated but I would much prefer the regexp ~ and ~* operators instead of like.

huangapple
  • 本文由 发表于 2022年10月31日 23:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/74265436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定