13006: Fail when using is_a filter on uuid attr and prefix_uuid doesn't match.
[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         col = model_class.columns.select { |c| c.name == subproperty[0] }.first
67
68         if subproperty.length == 2
69           if col.nil? or col.type != :jsonb
70             raise ArgumentError.new("Invalid attribute '#{subproperty[0]}' for subproperty filter")
71           end
72
73           if subproperty[1][0] == "<" and subproperty[1][-1] == ">"
74             subproperty[1] = subproperty[1][1..-2]
75           end
76
77           # jsonb search
78           case operator.downcase
79           when '=', '!='
80             not_in = if operator.downcase == "!=" then "NOT " else "" end
81             cond_out << "#{not_in}(#{ar_table_name}.#{subproperty[0]} @> ?::jsonb)"
82             param_out << SafeJSON.dump({subproperty[1] => operand})
83           when 'in'
84             if operand.is_a? Array
85               operand.each do |opr|
86                 cond_out << "#{ar_table_name}.#{subproperty[0]} @> ?::jsonb"
87                 param_out << SafeJSON.dump({subproperty[1] => opr})
88               end
89             else
90               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
91                                       "for '#{operator}' operator in filters")
92             end
93           when '<', '<=', '>', '>='
94             cond_out << "#{ar_table_name}.#{subproperty[0]}->? #{operator} ?::jsonb"
95             param_out << subproperty[1]
96             param_out << SafeJSON.dump(operand)
97           when 'like', 'ilike'
98             cond_out << "#{ar_table_name}.#{subproperty[0]}->>? #{operator} ?"
99             param_out << subproperty[1]
100             param_out << operand
101           when 'not in'
102             if operand.is_a? Array
103               cond_out << "#{ar_table_name}.#{subproperty[0]}->>? NOT IN (?) OR #{ar_table_name}.#{subproperty[0]}->>? IS NULL"
104               param_out << subproperty[1]
105               param_out << operand
106               param_out << subproperty[1]
107             else
108               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
109                                       "for '#{operator}' operator in filters")
110             end
111           when 'exists'
112             if operand == true
113               cond_out << "jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)"
114             elsif operand == false
115               cond_out << "(NOT jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)) OR #{ar_table_name}.#{subproperty[0]} is NULL"
116             else
117               raise ArgumentError.new("Invalid operand '#{operand}' for '#{operator}' must be true or false")
118             end
119             param_out << subproperty[1]
120           else
121             raise ArgumentError.new("Invalid operator for subproperty search '#{operator}'")
122           end
123         elsif operator.downcase == "exists"
124           if col.type != :jsonb
125             raise ArgumentError.new("Invalid attribute '#{subproperty[0]}' for operator '#{operator}' in filter")
126           end
127
128           cond_out << "jsonb_exists(#{ar_table_name}.#{subproperty[0]}, ?)"
129           param_out << operand
130         else
131           if !model_class.searchable_columns(operator).index subproperty[0]
132             raise ArgumentError.new("Invalid attribute '#{subproperty[0]}' in filter")
133           end
134
135           case operator.downcase
136           when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
137             attr_type = model_class.attribute_column(attr).type
138             operator = '<>' if operator == '!='
139             if operand.is_a? String
140               if attr_type == :boolean
141                 if not ['=', '<>'].include?(operator)
142                   raise ArgumentError.new("Invalid operator '#{operator}' for " \
143                                           "boolean attribute '#{attr}'")
144                 end
145                 case operand.downcase
146                 when '1', 't', 'true', 'y', 'yes'
147                   operand = true
148                 when '0', 'f', 'false', 'n', 'no'
149                   operand = false
150                 else
151                   raise ArgumentError("Invalid operand '#{operand}' for " \
152                                       "boolean attribute '#{attr}'")
153                 end
154               end
155               if operator == '<>'
156                 # explicitly allow NULL
157                 cond_out << "#{ar_table_name}.#{attr} #{operator} ? OR #{ar_table_name}.#{attr} IS NULL"
158               else
159                 cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
160               end
161               if (# any operator that operates on value rather than
162                 # representation:
163                 operator.match(/[<=>]/) and (attr_type == :datetime))
164                 operand = Time.parse operand
165               end
166               param_out << operand
167             elsif operand.nil? and operator == '='
168               cond_out << "#{ar_table_name}.#{attr} is null"
169             elsif operand.nil? and operator == '<>'
170               cond_out << "#{ar_table_name}.#{attr} is not null"
171             elsif (attr_type == :boolean) and ['=', '<>'].include?(operator) and
172                  [true, false].include?(operand)
173               cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
174               param_out << operand
175             elsif (attr_type == :integer)
176               cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
177               param_out << operand
178             else
179               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
180                                       "for '#{operator}' operator in filters")
181             end
182           when 'in', 'not in'
183             if operand.is_a? Array
184               cond_out << "#{ar_table_name}.#{attr} #{operator} (?)"
185               param_out << operand
186               if operator == 'not in' and not operand.include?(nil)
187                 # explicitly allow NULL
188                 cond_out[-1] = "(#{cond_out[-1]} OR #{ar_table_name}.#{attr} IS NULL)"
189               end
190             else
191               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
192                                       "for '#{operator}' operator in filters")
193             end
194           when 'is_a'
195             operand = [operand] unless operand.is_a? Array
196             cond = []
197             operand.each do |op|
198               cl = ArvadosModel::kind_class op
199               if cl
200                 if attr == 'uuid'
201                   if model_class.uuid_prefix == cl.uuid_prefix
202                     cond << "1=1"
203                   else
204                     cond << "1=0"
205                   end
206                 else
207                   # Use a substring query to support remote uuids
208                   cond << "substring(#{ar_table_name}.#{attr}, 7, 5) = ?"
209                   param_out << cl.uuid_prefix
210                 end
211               else
212                 cond << "1=0"
213               end
214             end
215             cond_out << cond.join(' OR ')
216           else
217             raise ArgumentError.new("Invalid operator '#{operator}'")
218           end
219         end
220       end
221       conds_out << cond_out.join(' OR ') if cond_out.any?
222     end
223
224     {:cond_out => conds_out, :param_out => param_out}
225   end
226
227 end