17417: Add arm64 packages for our Golang components.
[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 [Hash, ActionController::Parameters].include? params[:where].class
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(fill_table_names: true)
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.API.MaxItemsPerResponse].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]+$/) &&
100             model_class.columns.collect(&:name).index(attr) &&
101             ['asc','desc'].index(direction.downcase))
102           if fill_table_names
103             @orders << "#{table_name}.#{attr} #{direction.downcase}"
104           else
105             @orders << "#{attr} #{direction.downcase}"
106           end
107         elsif attr.match(/^([a-z][_a-z0-9]+)\.([a-z][_a-z0-9]+)$/) and
108             ['asc','desc'].index(direction.downcase) and
109             ActiveRecord::Base.connection.tables.include?($1) and
110             $1.classify.constantize.columns.collect(&:name).index($2)
111           # $1 in the above checks references the first match from the regular expression, which is expected to be the database table name
112           # $2 is of course the actual database column name
113           @orders << "#{attr} #{direction.downcase}"
114         end
115       end
116     end
117
118     # If the client-specified orders don't amount to a full ordering
119     # (e.g., [] or ['owner_uuid desc']), fall back on the default
120     # orders to ensure repeating the same request (possibly with
121     # different limit/offset) will return records in the same order.
122     #
123     # Clean up the resulting list of orders such that no column
124     # uselessly appears twice (Postgres might not optimize this out
125     # for us) and no columns uselessly appear after a unique column
126     # (Postgres does not optimize this out for us; as of 9.2, "order
127     # by id, modified_at desc, uuid" is slow but "order by id" is
128     # fast).
129     orders_given_and_default = @orders + model_class.default_orders
130     order_cols_used = {}
131     @orders = []
132     orders_given_and_default.each do |order|
133       otablecol = order.split(' ')[0]
134
135       next if order_cols_used[otablecol]
136       order_cols_used[otablecol] = true
137
138       @orders << order
139
140       otable, ocol = otablecol.split('.')
141       if otable == table_name and model_class.unique_columns.include?(ocol)
142         # we already have a full ordering; subsequent entries would be
143         # superfluous
144         break
145       end
146     end
147
148     case params[:select]
149     when Array
150       @select = params[:select]
151     when String
152       begin
153         @select = SafeJSON.load(params[:select])
154         raise unless @select.is_a? Array or @select.nil? or !@select
155       rescue
156         raise ArgumentError.new("Could not parse \"select\" param as an array")
157       end
158     end
159
160     if @select
161       # Any ordering columns must be selected when doing select,
162       # otherwise it is an SQL error, so filter out invaliding orderings.
163       @orders.select! { |o|
164         col, _ = o.split
165         # match select column against order array entry
166         @select.select { |s| col == "#{table_name}.#{s}" }.any?
167       }
168     end
169
170     @distinct = true if (params[:distinct] == true || params[:distinct] == "true")
171     @distinct = false if (params[:distinct] == false || params[:distinct] == "false")
172   end
173
174 end