ruby-on-rails - Hstore 上的 Rails Postgres 查询以避免 SQL 注入(inject)

标签 ruby-on-rails postgresql rails-activerecord sql-injection hstore

我有一个 User 类,它有一个 hstore 属性 :preferences。如果我想找到他们首选项中 startpage 键为 nil 的所有用户,我可以这样做:

User.where("preferences @> 'startpage=>NULL'")

我如何构建该查询以避免 SQL 查询注入(inject)?

尝试过:

User.where("preferences @> :key '=>NULL'", key: 'startpage')
User.where("preferences @> :key IS 'NULL'", key: 'startpage')
User.where("preferences @> :key IS NULL", key: 'startpage')
User.where("preferences @> ? IS NULL", 'startpage')

没有运气。有人知道怎么做吗?

最佳答案

@> 运算符需要两边的 hstores。当你说:

some_hstore @> 'startpage=>NULL'

PostgreSQL 将隐式添加 ::hstore 强制转换,就像您说的那样:

some_hstore @> 'startpage=>NULL'::hstore

但是还有其他方法可以创建 hstore。来自fine manual :

Function: hstore(text, text)
Return Type: hstore
Description: make single-item hstore

因此您可以切换到更明确的 hstore(text, text) 函数,让 ActiveRecord 使用占位符和字符串执行其正常操作:

User.where("preferences @> hstore(:key, null)", :key => 'start page')

关于ruby-on-rails - Hstore 上的 Rails Postgres 查询以避免 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667828/

相关文章:

ruby-on-rails - 按返回整数的模型方法进行扫描排序

ruby-on-rails - 在我的 Controller 中,我想接收一些参数,例如 params[ :test][:test_page]

sql - 关系型数据库查询问题

ruby-on-rails - 在一次查询中按不同属性对两个模型进行排序

ruby-on-rails - ActiveRecord/Rails 中的原子插入或增量

ruby-on-rails - Ruby - 忽略 protected 属性

ruby-on-rails - 如何使用默认的 app/policies/application_policy.rb?

javascript - Ruby on Rails ExecJS::Pages 中的运行时错误#home

PostgreSQL 与子字符串比较不起作用

postgresql - docker postgres,无法在 Windows 中映射卷