在传递给数据库之前手动引用值

时间:2014-06-06 14:16:22

标签: ruby escaping sinatra sequel quoting

WHERE条款涉及时,一切都很清楚:

puts $DB[:users].where('field = ?', "'").sql   # SELECT * FROM `users` WHERE (field = '\'')
puts $DB[:users].where(field: "'").sql   # SELECT * FROM `users` WHERE (`field` = '\'')

但是ORDER BY呢?

puts $DB[:users].order_by(
    ("field = '%s'" % "'").lit
).sql   # SELECT * FROM `users` ORDER BY field = '''

1 个答案:

答案 0 :(得分:1)

您可以quote清理字符串:

puts $DB[:users].order_by(
    ("field = %s" % ActiveRecord::Base.connection.quote("'")).lit
).sql    # SELECT * FROM `users` ORDER BY field = ''''

对于sequel,您应该使用literal_append

puts $DB[:users].order_by(
    ($DB[:users].literal_append("field = ", "'")).lit
).sql    # SELECT * FROM `users` ORDER BY field = ''''