e059a6e70aaaba664af9ca5fd428d765ff4201ee
[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 the following 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   # :joins     array of joins: either [] or ["JOIN containers ON ..."]
26   def record_filters filters, model_class
27     conds_out = []
28     param_out = []
29     joins = []
30
31     model_table_name = model_class.table_name
32     filters.each do |filter|
33       attrs_in, operator, operand = filter
34       if attrs_in == 'any' && operator != '@@'
35         attrs = model_class.searchable_columns(operator)
36       elsif attrs_in.is_a? Array
37         attrs = attrs_in
38       else
39         attrs = [attrs_in]
40       end
41       if !filter.is_a? Array
42         raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
43       elsif !operator.is_a? String
44         raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
45       end
46
47       cond_out = []
48
49       if attrs_in == 'any' && (operator.casecmp('ilike').zero? || operator.casecmp('like').zero?) && (operand.is_a? String) && operand.match('^[%].*[%]$')
50         # Trigram index search
51         cond_out << model_class.full_text_trgm + " #{operator} ?"
52         param_out << operand
53         # Skip the generic per-column operator loop below
54         attrs = []
55       end
56
57       if operator == '@@'
58         # Full-text search
59         if attrs_in != 'any'
60           raise ArgumentError.new("Full text search on individual columns is not supported")
61         end
62         if operand.is_a? Array
63           raise ArgumentError.new("Full text search not supported for array operands")
64         end
65
66         # Skip the generic per-column operator loop below
67         attrs = []
68         # Use to_tsquery since plainto_tsquery does not support prefix
69         # search. And, split operand and join the words with ' & '
70         cond_out << model_class.full_text_tsvector+" @@ to_tsquery(?)"
71         param_out << operand.split.join(' & ')
72       end
73       attrs.each do |attr|
74         subproperty = attr.split(".", 2)
75
76         if subproperty.length == 2 && subproperty[0] == 'container' && model_table_name == "container_requests"
77           # attr is "tablename.colname" -- e.g., ["container.state", "=", "Complete"]
78           joins = ["JOIN containers ON container_requests.container_uuid = containers.uuid"]
79           attr_model_class = Container
80           attr_table_name = "containers"
81           subproperty = subproperty[1].split(".", 2)
82         else
83           attr_model_class = model_class
84           attr_table_name = model_table_name
85         end
86
87         attr = subproperty[0]
88         proppath = subproperty[1]
89         col = attr_model_class.columns.select { |c| c.name == attr }.first
90
91         if proppath
92           if col.nil? or col.type != :jsonb
93             raise ArgumentError.new("Invalid attribute '#{attr}' for subproperty filter")
94           end
95
96           if proppath[0] == "<" and proppath[-1] == ">"
97             proppath = proppath[1..-2]
98           end
99
100           # jsonb search
101           case operator.downcase
102           when '=', '!='
103             not_in = if operator.downcase == "!=" then "NOT " else "" end
104             cond_out << "#{not_in}(#{attr_table_name}.#{attr} @> ?::jsonb)"
105             param_out << SafeJSON.dump({proppath => operand})
106           when 'in'
107             if operand.is_a? Array
108               operand.each do |opr|
109                 cond_out << "#{attr_table_name}.#{attr} @> ?::jsonb"
110                 param_out << SafeJSON.dump({proppath => opr})
111               end
112             else
113               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
114                                       "for '#{operator}' operator in filters")
115             end
116           when '<', '<=', '>', '>='
117             cond_out << "#{attr_table_name}.#{attr}->? #{operator} ?::jsonb"
118             param_out << proppath
119             param_out << SafeJSON.dump(operand)
120           when 'like', 'ilike'
121             cond_out << "#{attr_table_name}.#{attr}->>? #{operator} ?"
122             param_out << proppath
123             param_out << operand
124           when 'not in'
125             if operand.is_a? Array
126               cond_out << "#{attr_table_name}.#{attr}->>? NOT IN (?) OR #{attr_table_name}.#{attr}->>? IS NULL"
127               param_out << proppath
128               param_out << operand
129               param_out << proppath
130             else
131               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
132                                       "for '#{operator}' operator in filters")
133             end
134           when 'exists'
135             if operand == true
136               cond_out << "jsonb_exists(#{attr_table_name}.#{attr}, ?)"
137             elsif operand == false
138               cond_out << "(NOT jsonb_exists(#{attr_table_name}.#{attr}, ?)) OR #{attr_table_name}.#{attr} is NULL"
139             else
140               raise ArgumentError.new("Invalid operand '#{operand}' for '#{operator}' must be true or false")
141             end
142             param_out << proppath
143           when 'contains'
144             cond_out << "#{attr_table_name}.#{attr} @> ?::jsonb"
145             param_out << SafeJSON.dump({proppath => [operand]})
146           else
147             raise ArgumentError.new("Invalid operator for subproperty search '#{operator}'")
148           end
149         elsif operator.downcase == "exists"
150           if col.type != :jsonb
151             raise ArgumentError.new("Invalid attribute '#{attr}' for operator '#{operator}' in filter")
152           end
153
154           cond_out << "jsonb_exists(#{attr_table_name}.#{attr}, ?)"
155           param_out << operand
156         else
157           if !attr_model_class.searchable_columns(operator).index attr
158             raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
159           end
160
161           case operator.downcase
162           when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
163             attr_type = attr_model_class.attribute_column(attr).type
164             operator = '<>' if operator == '!='
165             if operand.is_a? String
166               if attr_type == :boolean
167                 if not ['=', '<>'].include?(operator)
168                   raise ArgumentError.new("Invalid operator '#{operator}' for " \
169                                           "boolean attribute '#{attr}'")
170                 end
171                 case operand.downcase
172                 when '1', 't', 'true', 'y', 'yes'
173                   operand = true
174                 when '0', 'f', 'false', 'n', 'no'
175                   operand = false
176                 else
177                   raise ArgumentError("Invalid operand '#{operand}' for " \
178                                       "boolean attribute '#{attr}'")
179                 end
180               end
181               if operator == '<>'
182                 # explicitly allow NULL
183                 cond_out << "#{attr_table_name}.#{attr} #{operator} ? OR #{attr_table_name}.#{attr} IS NULL"
184               else
185                 cond_out << "#{attr_table_name}.#{attr} #{operator} ?"
186               end
187               if (# any operator that operates on value rather than
188                 # representation:
189                 operator.match(/[<=>]/) and (attr_type == :datetime))
190                 operand = Time.parse operand
191               end
192               param_out << operand
193             elsif operand.nil? and operator == '='
194               cond_out << "#{attr_table_name}.#{attr} is null"
195             elsif operand.nil? and operator == '<>'
196               cond_out << "#{attr_table_name}.#{attr} is not null"
197             elsif (attr_type == :boolean) and ['=', '<>'].include?(operator) and
198                  [true, false].include?(operand)
199               cond_out << "#{attr_table_name}.#{attr} #{operator} ?"
200               param_out << operand
201             elsif (attr_type == :integer)
202               cond_out << "#{attr_table_name}.#{attr} #{operator} ?"
203               param_out << operand
204             else
205               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
206                                       "for '#{operator}' operator in filters")
207             end
208           when 'in', 'not in'
209             if operand.is_a? Array
210               cond_out << "#{attr_table_name}.#{attr} #{operator} (?)"
211               param_out << operand
212               if operator == 'not in' and not operand.include?(nil)
213                 # explicitly allow NULL
214                 cond_out[-1] = "(#{cond_out[-1]} OR #{attr_table_name}.#{attr} IS NULL)"
215               end
216             else
217               raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
218                                       "for '#{operator}' operator in filters")
219             end
220           when 'is_a'
221             operand = [operand] unless operand.is_a? Array
222             cond = []
223             operand.each do |op|
224               cl = ArvadosModel::kind_class op
225               if cl
226                 if attr == 'uuid'
227                   if attr_model_class.uuid_prefix == cl.uuid_prefix
228                     cond << "1=1"
229                   else
230                     cond << "1=0"
231                   end
232                 else
233                   # Use a substring query to support remote uuids
234                   cond << "substring(#{attr_table_name}.#{attr}, 7, 5) = ?"
235                   param_out << cl.uuid_prefix
236                 end
237               else
238                 cond << "1=0"
239               end
240             end
241             cond_out << cond.join(' OR ')
242           else
243             raise ArgumentError.new("Invalid operator '#{operator}'")
244           end
245         end
246       end
247       conds_out << cond_out.join(' OR ') if cond_out.any?
248     end
249
250     {:cond_out => conds_out, :param_out => param_out, :joins => joins}
251   end
252
253 end