Merge branch '8784-dir-listings'
[arvados.git] / services / api / lib / load_param.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Mixin module for reading out query parameters from request params.
6 #
7 # Expects:
8 #   +params+ Hash
9 # Sets:
10 #   @where, @filters, @limit, @offset, @orders
11 module LoadParam
12
13   # Default number of rows to return in a single query.
14   DEFAULT_LIMIT = 100
15
16   # Load params[:where] into @where
17   def load_where_param
18     if params[:where].nil? or params[:where] == ""
19       @where = {}
20     elsif params[:where].is_a? Hash
21       @where = params[:where]
22     elsif params[:where].is_a? String
23       begin
24         @where = SafeJSON.load(params[:where])
25         raise unless @where.is_a? Hash
26       rescue
27         raise ArgumentError.new("Could not parse \"where\" param as an object")
28       end
29     end
30     @where = @where.with_indifferent_access
31   end
32
33   # Load params[:filters] into @filters
34   def load_filters_param
35     @filters ||= []
36     if params[:filters].is_a? Array
37       @filters += params[:filters]
38     elsif params[:filters].is_a? String and !params[:filters].empty?
39       begin
40         f = SafeJSON.load(params[:filters])
41         if not f.nil?
42           raise unless f.is_a? Array
43           @filters += f
44         end
45       rescue
46         raise ArgumentError.new("Could not parse \"filters\" param as an array")
47       end
48     end
49   end
50
51   # Load params[:limit], params[:offset] and params[:order]
52   # into @limit, @offset, @orders
53   def load_limit_offset_order_params
54     if params[:limit]
55       unless params[:limit].to_s.match(/^\d+$/)
56         raise ArgumentError.new("Invalid value for limit parameter")
57       end
58       @limit = [params[:limit].to_i,
59                 Rails.configuration.max_items_per_response].min
60     else
61       @limit = DEFAULT_LIMIT
62     end
63
64     if params[:offset]
65       unless params[:offset].to_s.match(/^\d+$/)
66         raise ArgumentError.new("Invalid value for offset parameter")
67       end
68       @offset = params[:offset].to_i
69     else
70       @offset = 0
71     end
72
73     @orders = []
74     if (params[:order].is_a?(Array) && !params[:order].empty?) || !params[:order].blank?
75       od = []
76       (case params[:order]
77        when String
78          if params[:order].starts_with? '['
79            od = SafeJSON.load(params[:order])
80            raise unless od.is_a? Array
81            od
82          else
83            params[:order].split(',')
84          end
85        when Array
86          params[:order]
87        else
88          []
89        end).each do |order|
90         order = order.to_s
91         attr, direction = order.strip.split " "
92         direction ||= 'asc'
93         # The attr can have its table unspecified if it happens to be for the current "model_class" (the first case)
94         # or it can be fully specified with the database tablename (the second case) (e.g. "collections.name").
95         # NB that the security check for the second case table_name will not work if the model
96         # has used set_table_name to use an alternate table name from the Rails standard.
97         # I could not find a perfect way to handle this well, but ActiveRecord::Base.send(:descendants)
98         # would be a place to start if this ever becomes necessary.
99         if attr.match(/^[a-z][_a-z0-9]+$/) and
100             model_class.columns.collect(&:name).index(attr) and
101             ['asc','desc'].index direction.downcase
102           @orders << "#{table_name}.#{attr} #{direction.downcase}"
103         elsif attr.match(/^([a-z][_a-z0-9]+)\.([a-z][_a-z0-9]+)$/) and
104             ['asc','desc'].index(direction.downcase) and
105             ActiveRecord::Base.connection.tables.include?($1) and
106             $1.classify.constantize.columns.collect(&:name).index($2)
107           # $1 in the above checks references the first match from the regular expression, which is expected to be the database table name
108           # $2 is of course the actual database column name
109           @orders << "#{attr} #{direction.downcase}"
110         end
111       end
112     end
113
114     # If the client-specified orders don't amount to a full ordering
115     # (e.g., [] or ['owner_uuid desc']), fall back on the default
116     # orders to ensure repeating the same request (possibly with
117     # different limit/offset) will return records in the same order.
118     #
119     # Clean up the resulting list of orders such that no column
120     # uselessly appears twice (Postgres might not optimize this out
121     # for us) and no columns uselessly appear after a unique column
122     # (Postgres does not optimize this out for us; as of 9.2, "order
123     # by id, modified_at desc, uuid" is slow but "order by id" is
124     # fast).
125     orders_given_and_default = @orders + model_class.default_orders
126     order_cols_used = {}
127     @orders = []
128     orders_given_and_default.each do |order|
129       otablecol = order.split(' ')[0]
130
131       next if order_cols_used[otablecol]
132       order_cols_used[otablecol] = true
133
134       @orders << order
135
136       otable, ocol = otablecol.split('.')
137       if otable == table_name and model_class.unique_columns.include?(ocol)
138         # we already have a full ordering; subsequent entries would be
139         # superfluous
140         break
141       end
142     end
143
144     case params[:select]
145     when Array
146       @select = params[:select]
147     when String
148       begin
149         @select = SafeJSON.load(params[:select])
150         raise unless @select.is_a? Array or @select.nil?
151       rescue
152         raise ArgumentError.new("Could not parse \"select\" param as an array")
153       end
154     end
155
156     if @select
157       # Any ordering columns must be selected when doing select,
158       # otherwise it is an SQL error, so filter out invaliding orderings.
159       @orders.select! { |o|
160         col, _ = o.split
161         # match select column against order array entry
162         @select.select { |s| col == "#{table_name}.#{s}" }.any?
163       }
164     end
165
166     @distinct = true if (params[:distinct] == true || params[:distinct] == "true")
167     @distinct = false if (params[:distinct] == false || params[:distinct] == "false")
168   end
169
170 end