Merge branch '4523-full-text-search' into 5110-workbench-full-text-search
[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 == '@@' # full-text-search
41         if attrs_in != 'any'
42           raise ArgumentError.new("Full text search on individual columns is not supported")
43         end
44         attrs = [] #  skip the generic per-column operator loop below
45         # Use to_tsquery since plainto_tsquery does not support prefix search.
46         # Instead split operand, add ':*' to each word and join the words with ' & '
47         cond_out << model_class.full_text_tsvector+" @@ to_tsquery(?)"
48         param_out << operand.split.each {|s| s.concat(':*')}.join(' & ')
49       else
50        attrs.each do |attr|
51         if !model_class.searchable_columns(operator).index attr.to_s
52           raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
53         end
54         case operator.downcase
55         when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
56           attr_type = model_class.attribute_column(attr).type
57           operator = '<>' if operator == '!='
58           if operand.is_a? String
59             if attr_type == :boolean
60               if not ['=', '<>'].include?(operator)
61                 raise ArgumentError.new("Invalid operator '#{operator}' for " \
62                                         "boolean attribute '#{attr}'")
63               end
64               case operand.downcase
65               when '1', 't', 'true', 'y', 'yes'
66                 operand = true
67               when '0', 'f', 'false', 'n', 'no'
68                 operand = false
69               else
70                 raise ArgumentError("Invalid operand '#{operand}' for " \
71                                     "boolean attribute '#{attr}'")
72               end
73             end
74             cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
75             if (# any operator that operates on value rather than
76                 # representation:
77                 operator.match(/[<=>]/) and (attr_type == :datetime))
78               operand = Time.parse operand
79             end
80             param_out << operand
81           elsif operand.nil? and operator == '='
82             cond_out << "#{ar_table_name}.#{attr} is null"
83           elsif operand.nil? and operator == '<>'
84             cond_out << "#{ar_table_name}.#{attr} is not null"
85           elsif (attr_type == :boolean) and ['=', '<>'].include?(operator) and
86               [true, false].include?(operand)
87             cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
88             param_out << operand
89           else
90             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
91                                     "for '#{operator}' operator in filters")
92           end
93         when 'in', 'not in'
94           if operand.is_a? Array
95             cond_out << "#{ar_table_name}.#{attr} #{operator} (?)"
96             param_out << operand
97             if operator == 'not in' and not operand.include?(nil)
98               # explicitly allow NULL
99               cond_out[-1] = "(#{cond_out[-1]} OR #{ar_table_name}.#{attr} IS NULL)"
100             end
101           else
102             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
103                                     "for '#{operator}' operator in filters")
104           end
105         when 'is_a'
106           operand = [operand] unless operand.is_a? Array
107           cond = []
108           operand.each do |op|
109             cl = ArvadosModel::kind_class op
110             if cl
111               cond << "#{ar_table_name}.#{attr} like ?"
112               param_out << cl.uuid_like_pattern
113             else
114               cond << "1=0"
115             end
116           end
117           cond_out << cond.join(' OR ')
118         end
119        end
120       end
121       conds_out << cond_out.join(' OR ') if cond_out.any?
122     end
123
124     {:cond_out => conds_out, :param_out => param_out}
125   end
126
127 end