4019: Update docs. Tweak syntax of 'exists' and add alternate form.
[arvados.git] / services / api / lib / record_filters.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Mixin module providing a method to convert filters into a list of SQL
6 # fragments suitable to be fed to ActiveRecord #where.
7 #
8 # Expects:
9 #   model_class
10 # Operates on:
11 #   @objects
12
13 require 'safe_json'
14
15 module RecordFilters
16
17   # Input:
18   # +filters+        array of conditions, each being [column, operator, operand]
19   # +model_class+    subclass of ActiveRecord being filtered
20   #
21   # Output:
22   # Hash with two keys:
23   # :cond_out  array of SQL fragments for each filter expression
24   # :param_out  array of values for parameter substitution in cond_out
25   def record_filters filters, model_class
26     conds_out = []
27     param_out = []
28
29     ar_table_name = model_class.table_name
30     filters.each do |filter|
31       attrs_in, operator, operand = filter
32       if attrs_in == 'any' && operator != '@@'
33         attrs = model_class.searchable_columns(operator)
34       elsif attrs_in.is_a? Array
35         attrs = attrs_in
36       else
37         attrs = [attrs_in]
38       end
39       if !filter.is_a? Array
40         raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
41       elsif !operator.is_a? String
42         raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
43       end
44
45       cond_out = []
46
47       if operator == '@@'
48         # Full-text search
49         if attrs_in != 'any'
50           raise ArgumentError.new("Full text search on individual columns is not supported")
51         end
52         if operand.is_a? Array
53           raise ArgumentError.new("Full text search not supported for array operands")
54         end
55
56         # Skip the generic per-column operator loop below
57         attrs = []
58         # Use to_tsquery since plainto_tsquery does not support prefix
59         # search. And, split operand and join the words with ' & '
60         cond_out << model_class.full_text_tsvector+" @@ to_tsquery(?)"
61         param_out << operand.split.join(' & ')
62       end
63       attrs.each do |attr|
64         subproperty = attr.split(".", 2)
65
66         if !model_class.searchable_columns(operator).index subproperty[0]
67           raise ArgumentError.new("Invalid attribute '#{subproperty[0]}' in filter")
68         end
69
70         if subproperty.length == 2
71         # jsonb search
72           case operator.downcase
73           when '=', '!='
74             not_in = if operator.downcase == "!=" then "NOT " else "" end
75             cond_out << "#{not_in}(#{ar_table_name}.#{subproperty[0]} @> ?::jsonb)"
76             param_out << SafeJSON.dump({subproperty[1] => operand})
77           when 'in'
78             if operand.is_a? Array
79               operand.each do |opr|
80                 cond_out << "#{ar_table_name}.#{subproperty[0]} @> ?::jsonb"
81                 param_out << SafeJSON.dump({subproperty[1] => opr})
82               end
83             else
84               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
85                                       "for '#{operator}' operator in filters")
86             end
87           when '<', '<=', '>', '>='
88             cond_out << "#{ar_table_name}.#{subproperty[0]}->? #{operator} ?::jsonb"
89             param_out << subproperty[1]
90             param_out << SafeJSON.dump(operand)
91           when 'like', 'ilike'
92             cond_out << "#{ar_table_name}.#{subproperty[0]}->>? #{operator} ?"
93             param_out << subproperty[1]
94             param_out << operand
95           when 'not in'
96             if operand.is_a? Array
97               cond_out << "#{ar_table_name}.#{subproperty[0]}->>? NOT IN (?) OR #{ar_table_name}.#{subproperty[0]}->>? IS NULL"
98               param_out << subproperty[1]
99               param_out << operand
100               param_out << subproperty[1]
101             else
102               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
103                                       "for '#{operator}' operator in filters")
104             end
105           when 'exists'
106           if operand
107             cond_out << "jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)"
108           else
109             cond_out << "(NOT jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)) OR #{ar_table_name}.#{subproperty[0]} is NULL"
110           end
111           param_out << subproperty[1]
112           else
113             raise ArgumentError.new("Invalid operator for subproperty search '#{operator}'")
114           end
115         else
116           case operator.downcase
117           when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
118             attr_type = model_class.attribute_column(attr).type
119             operator = '<>' if operator == '!='
120             if operand.is_a? String
121               if attr_type == :boolean
122                 if not ['=', '<>'].include?(operator)
123                   raise ArgumentError.new("Invalid operator '#{operator}' for " \
124                                           "boolean attribute '#{attr}'")
125                 end
126                 case operand.downcase
127                 when '1', 't', 'true', 'y', 'yes'
128                   operand = true
129                 when '0', 'f', 'false', 'n', 'no'
130                   operand = false
131                 else
132                   raise ArgumentError("Invalid operand '#{operand}' for " \
133                                       "boolean attribute '#{attr}'")
134                 end
135               end
136               if operator == '<>'
137                 # explicitly allow NULL
138                 cond_out << "#{ar_table_name}.#{attr} #{operator} ? OR #{ar_table_name}.#{attr} IS NULL"
139               else
140                 cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
141               end
142               if (# any operator that operates on value rather than
143                 # representation:
144                 operator.match(/[<=>]/) and (attr_type == :datetime))
145                 operand = Time.parse operand
146               end
147               param_out << operand
148             elsif operand.nil? and operator == '='
149               cond_out << "#{ar_table_name}.#{attr} is null"
150             elsif operand.nil? and operator == '<>'
151               cond_out << "#{ar_table_name}.#{attr} is not null"
152             elsif (attr_type == :boolean) and ['=', '<>'].include?(operator) and
153                  [true, false].include?(operand)
154               cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
155               param_out << operand
156             elsif (attr_type == :integer)
157               cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
158               param_out << operand
159             else
160               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
161                                       "for '#{operator}' operator in filters")
162             end
163           when 'in', 'not in'
164             if operand.is_a? Array
165               cond_out << "#{ar_table_name}.#{attr} #{operator} (?)"
166               param_out << operand
167               if operator == 'not in' and not operand.include?(nil)
168                 # explicitly allow NULL
169                 cond_out[-1] = "(#{cond_out[-1]} OR #{ar_table_name}.#{attr} IS NULL)"
170               end
171             else
172               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
173                                       "for '#{operator}' operator in filters")
174             end
175           when 'is_a'
176             operand = [operand] unless operand.is_a? Array
177             cond = []
178             operand.each do |op|
179               cl = ArvadosModel::kind_class op
180               if cl
181                 cond << "#{ar_table_name}.#{attr} like ?"
182                 param_out << cl.uuid_like_pattern
183               else
184                 cond << "1=0"
185               end
186             end
187             cond_out << cond.join(' OR ')
188           when 'exists'
189             cond_out << "jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)"
190             param_out << operand
191           else
192             raise ArgumentError.new("Invalid operator '#{operator}'")
193           end
194         end
195       end
196       conds_out << cond_out.join(' OR ') if cond_out.any?
197     end
198
199     {:cond_out => conds_out, :param_out => param_out}
200   end
201
202 end