简体   繁体   English

滑轨。 使用占位符和字符串时,如何从查询条件中删除引号?

[英]Rails. How to remove quotation marks from query conditions when using a placeholder and string?

I'm trying to create a search form (rails 3.1) where one of the search parameters allows the user to pick math symbols like <, >, = etc. I then want to use the value chosen as part of my query. 我正在尝试创建一个搜索表单(rails 3.1),其中的一个搜索参数允许用户选择<,>,=等数学符号。然后,我想使用选择的值作为查询的一部分。 The only problem is it puts quotation marks around it and results in invalid sql. 唯一的问题是它将引号引起来并导致无效的sql。

simplified example 简化的例子

params[:comparison] = '>'
params[:rank] = '3'

.where("rank ? ?", params[:comparison], params[:rank].to_i)

results in 结果是

PGError: ERROR:  syntax error at or near "3"
LINE 1: ... WHERE (rank '>' 3)

I want to make it so its 我想做到这一点

WHERE (rank > 3)

How can I create this active record query without the quotation marks around the greater than symbol in a way thats argument safe and not vulnerable to SQL injection exploits? 我该如何创建这种活动记录查询,而不用大号符号引起来的引号,使参数安全且不易受到SQL注入漏洞的侵害?

In this very specific case, I would suggest you just check the value of params[:comparison] since you can easily "whitelist" it against the known safe values you are expecting which I assume are <, > and = 在这种非常特殊的情况下,我建议您只检查params[:comparison]的值,因为您可以轻松地将其与您期望的已知安全值“白名单”(我假定为<,>和=)

Example code: 示例代码:

known_comparisons = %w{< > =}
params_comparison = ">"

if known_comparisons.any? { |i| i === params_comparison }
  puts "were good"
else
  puts "bad value"
end

Then embed the value directly with string interpolation since you now are sure it is safe. 然后,由于您确定它是安全的,因此可以直接使用字符串插值嵌入该值。

.where("rank #{params[:comparison]} ?", params[:rank].to_i)

This problem reminds me Query class at Redmine. 这个问题让我想起了Redmine的Query类。 Source code at here . 源代码在这里

class Query < ActiveRecord::Base

@@operators = { "="   => :label_equals,
                "!"   => :label_not_equals,
                "o"   => :label_open_issues,
                "c"   => :label_closed_issues,
                "!*"  => :label_none,
                "*"   => :label_all,
                ">="  => :label_greater_or_equal,
                "<="  => :label_less_or_equal,
                "<t+" => :label_in_less_than,
                ">t+" => :label_in_more_than,
                "t+"  => :label_in,
                "t"   => :label_today,
                "w"   => :label_this_week,
                ">t-" => :label_less_than_ago,
                "<t-" => :label_more_than_ago,
                "t-"  => :label_ago,
                "~"   => :label_contains,
                "!~"  => :label_not_contains }

cattr_reader :operators

@@operators_by_filter_type = { :list => [ "=", "!" ],
                               :list_status => [ "o", "=", "!", "c", "*" ],
                               :list_optional => [ "=", "!", "!*", "*" ],
                               :list_subprojects => [ "*", "!*", "=" ],
                               :date => [ "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-" ],
                               :date_past => [ ">t-", "<t-", "t-", "t", "w" ],
                               :string => [ "=", "~", "!", "!~" ],
                               :text => [  "~", "!~" ],
                               :integer => [ "=", ">=", "<=", "!*", "*" ] }


def statement
  # filters clauses
  filters_clauses = []
  filters.each_key do |field|
    next if field == "subproject_id"
    v = values_for(field).clone
    next unless v and !v.empty?
    operator = operator_for(field)

    # "me" value subsitution
    if %w(assigned_to_id author_id watcher_id).include?(field)
      v.push(User.current.logged? ? User.current.id.to_s : "0") if v.delete("me")
    end

    sql = ''
    if field =~ /^cf_(\d+)$/
      # custom field
      db_table = CustomValue.table_name
      db_field = 'value'
      is_custom_filter = true
      sql << "#{Issue.table_name}.id IN (SELECT #{Issue.table_name}.id FROM #{Issue.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{$1} WHERE "
      sql << sql_for_field(field, operator, v, db_table, db_field, true) + ')'
    elsif field == 'watcher_id'
      db_table = Watcher.table_name
      db_field = 'user_id'
      sql << "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND "
      sql << sql_for_field(field, '=', v, db_table, db_field) + ')'
    elsif field == "member_of_group" # named field
      if operator == '*' # Any group
        groups = Group.all
        operator = '=' # Override the operator since we want to find by assigned_to
      elsif operator == "!*"
        groups = Group.all
        operator = '!' # Override the operator since we want to find by assigned_to
      else
        groups = Group.find_all_by_id(v)
      end
      groups ||= []

      members_of_groups = groups.inject([]) {|user_ids, group|
        if group && group.user_ids.present?
          user_ids << group.user_ids
        end
        user_ids.flatten.uniq.compact
      }.sort.collect(&:to_s)

      sql << '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'

    elsif field == "assigned_to_role" # named field
      if operator == "*" # Any Role
        roles = Role.givable
        operator = '=' # Override the operator since we want to find by assigned_to
      elsif operator == "!*" # No role
        roles = Role.givable
        operator = '!' # Override the operator since we want to find by assigned_to
      else
        roles = Role.givable.find_all_by_id(v)
      end
      roles ||= []

      members_of_roles = roles.inject([]) {|user_ids, role|
        if role && role.members
          user_ids << role.members.collect(&:user_id)
        end
        user_ids.flatten.uniq.compact
      }.sort.collect(&:to_s)

      sql << '(' + sql_for_field("assigned_to_id", operator, members_of_roles, Issue.table_name, "assigned_to_id", false) + ')'
    else
      # regular field
      db_table = Issue.table_name
      db_field = field
      sql << '(' + sql_for_field(field, operator, v, db_table, db_field) + ')'
    end
    filters_clauses << sql

  end if filters and valid?

  filters_clauses << project_statement
  filters_clauses.reject!(&:blank?)

  filters_clauses.any? ? filters_clauses.join(' AND ') : nil
end

private

# Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
  sql = ''
  case operator
  when "="
    if value.any?
      sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
    else
      # IN an empty set
      sql = "1=0"
    end
  when "!"
    if value.any?
      sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
    else
      # NOT IN an empty set
      sql = "1=1"
    end
  when "!*"
    sql = "#{db_table}.#{db_field} IS NULL"
    sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
  when "*"
    sql = "#{db_table}.#{db_field} IS NOT NULL"
    sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
  when ">="
    sql = "#{db_table}.#{db_field} >= #{value.first.to_i}"
  when "<="
    sql = "#{db_table}.#{db_field} <= #{value.first.to_i}"
  when "o"
    sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_false}" if field == "status_id"
  when "c"
    sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_true}" if field == "status_id"
  when ">t-"
    sql = date_range_clause(db_table, db_field, - value.first.to_i, 0)
  when "<t-"
    sql = date_range_clause(db_table, db_field, nil, - value.first.to_i)
  when "t-"
    sql = date_range_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
  when ">t+"
    sql = date_range_clause(db_table, db_field, value.first.to_i, nil)
  when "<t+"
    sql = date_range_clause(db_table, db_field, 0, value.first.to_i)
  when "t+"
    sql = date_range_clause(db_table, db_field, value.first.to_i, value.first.to_i)
  when "t"
    sql = date_range_clause(db_table, db_field, 0, 0)
  when "w"
    first_day_of_week = l(:general_first_day_of_week).to_i
    day_of_week = Date.today.cwday
    days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
    sql = date_range_clause(db_table, db_field, - days_ago, - days_ago + 6)
  when "~"
    sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
  when "!~"
    sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
  end

  return sql
end

...

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM