4523: Fix up whitespace.
[arvados.git] / services / api / lib / record_filters.rb
1 # Mixin module providing a method to convert filters into a list of SQL
2 # fragments suitable to be fed to ActiveRecord #where.
3 #
4 # Expects:
5 #   model_class
6 # Operates on:
7 #   @objects
8 module RecordFilters
9
10   # Input:
11   # +filters+        array of conditions, each being [column, operator, operand]
12   # +model_class+    subclass of ActiveRecord being filtered
13   #
14   # Output:
15   # Hash with two keys:
16   # :cond_out  array of SQL fragments for each filter expression
17   # :param_out  array of values for parameter substitution in cond_out
18   def record_filters filters, model_class
19     conds_out = []
20     param_out = []
21
22     ar_table_name = model_class.table_name
23     filters.each do |filter|
24       attrs_in, operator, operand = filter
25       if attrs_in == 'any' && operator != '@@'
26         attrs = model_class.searchable_columns(operator)
27       elsif attrs_in.is_a? Array
28         attrs = attrs_in
29       else
30         attrs = [attrs_in]
31       end
32       if !filter.is_a? Array
33         raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
34       elsif !operator.is_a? String
35         raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
36       end
37
38       cond_out = []
39
40       if operator == '@@'
41         # Full-text search
42         if attrs_in != 'any'
43           raise ArgumentError.new("Full text search on individual columns is not supported")
44         end
45         # Skip the generic per-column operator loop below
46         attrs = []
47         # Use to_tsquery since plainto_tsquery does not support prefix
48         # search.  Instead split operand, add ':*' to each word and
49         # join the words with ' & '
50         cond_out << model_class.full_text_tsvector+" @@ to_tsquery(?)"
51         param_out << operand.split.each {|s| s.concat(':*')}.join(' & ')
52       end
53       attrs.each do |attr|
54         if !model_class.searchable_columns(operator).index attr.to_s
55           raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
56         end
57         case operator.downcase
58         when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
59           attr_type = model_class.attribute_column(attr).type
60           operator = '<>' if operator == '!='
61           if operand.is_a? String
62             if attr_type == :boolean
63               if not ['=', '<>'].include?(operator)
64                 raise ArgumentError.new("Invalid operator '#{operator}' for " \
65                                         "boolean attribute '#{attr}'")
66               end
67               case operand.downcase
68               when '1', 't', 'true', 'y', 'yes'
69                 operand = true
70               when '0', 'f', 'false', 'n', 'no'
71                 operand = false
72               else
73                 raise ArgumentError("Invalid operand '#{operand}' for " \
74                                     "boolean attribute '#{attr}'")
75               end
76             end
77             cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
78             if (# any operator that operates on value rather than
79                 # representation:
80                 operator.match(/[<=>]/) and (attr_type == :datetime))
81               operand = Time.parse operand
82             end
83             param_out << operand
84           elsif operand.nil? and operator == '='
85             cond_out << "#{ar_table_name}.#{attr} is null"
86           elsif operand.nil? and operator == '<>'
87             cond_out << "#{ar_table_name}.#{attr} is not null"
88           elsif (attr_type == :boolean) and ['=', '<>'].include?(operator) and
89               [true, false].include?(operand)
90             cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
91             param_out << operand
92           else
93             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
94                                     "for '#{operator}' operator in filters")
95           end
96         when 'in', 'not in'
97           if operand.is_a? Array
98             cond_out << "#{ar_table_name}.#{attr} #{operator} (?)"
99             param_out << operand
100             if operator == 'not in' and not operand.include?(nil)
101               # explicitly allow NULL
102               cond_out[-1] = "(#{cond_out[-1]} OR #{ar_table_name}.#{attr} IS NULL)"
103             end
104           else
105             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
106                                     "for '#{operator}' operator in filters")
107           end
108         when 'is_a'
109           operand = [operand] unless operand.is_a? Array
110           cond = []
111           operand.each do |op|
112             cl = ArvadosModel::kind_class op
113             if cl
114               cond << "#{ar_table_name}.#{attr} like ?"
115               param_out << cl.uuid_like_pattern
116             else
117               cond << "1=0"
118             end
119           end
120           cond_out << cond.join(' OR ')
121         end
122       end
123       conds_out << cond_out.join(' OR ') if cond_out.any?
124     end
125
126     {:cond_out => conds_out, :param_out => param_out}
127   end
128
129 end