簡體   English   中英

Hstore上的Rails Postgres查詢可避免SQL注入

[英]Rails Postgres query on hstore to avoid SQL injection

我有一個User類,它具有一個hstore屬性:preferences 如果我想找到所有在首選項中startpage鍵為nil用戶,我可以這樣做:

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

如何構造該查詢,從而避免SQL查詢注入?

嘗試:

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的方法。 精美的手冊中

功能: hstore(text, text)
返回類型: hstore
說明:使單項hstore

因此,您可以切換到更明確的hstore(text, text)函數,並讓ActiveRecord使用占位符和字符串來完成其正常工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM