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