Merge branch '5554-delete-job-log-rows-wip'
[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   # Maximum number of rows to return in a single query, even if the client asks for more.
13   MAX_LIMIT = 1000
14
15   # Load params[:where] into @where
16   def load_where_param
17     if params[:where].nil? or params[:where] == ""
18       @where = {}
19     elsif params[:where].is_a? Hash
20       @where = params[:where]
21     elsif params[:where].is_a? String
22       begin
23         @where = Oj.load(params[:where])
24         raise unless @where.is_a? Hash
25       rescue
26         raise ArgumentError.new("Could not parse \"where\" param as an object")
27       end
28     end
29     @where = @where.with_indifferent_access
30   end
31
32   # Load params[:filters] into @filters
33   def load_filters_param
34     @filters ||= []
35     if params[:filters].is_a? Array
36       @filters += params[:filters]
37     elsif params[:filters].is_a? String and !params[:filters].empty?
38       begin
39         f = Oj.load params[:filters]
40         if not f.nil?
41           raise unless f.is_a? Array
42           @filters += f
43         end
44       rescue
45         raise ArgumentError.new("Could not parse \"filters\" param as an array")
46       end
47     end
48   end
49
50   # Load params[:limit], params[:offset] and params[:order]
51   # into @limit, @offset, @orders
52   def load_limit_offset_order_params
53     if params[:limit]
54       unless params[:limit].to_s.match(/^\d+$/)
55         raise ArgumentError.new("Invalid value for limit parameter")
56       end
57       @limit = [params[:limit].to_i, MAX_LIMIT].min
58     else
59       @limit = DEFAULT_LIMIT
60     end
61
62     if params[:offset]
63       unless params[:offset].to_s.match(/^\d+$/)
64         raise ArgumentError.new("Invalid value for offset parameter")
65       end
66       @offset = params[:offset].to_i
67     else
68       @offset = 0
69     end
70
71     @orders = []
72     if (params[:order].is_a?(Array) && !params[:order].empty?) || !params[:order].blank?
73       od = []
74       (case params[:order]
75        when String
76          if params[:order].starts_with? '['
77            od = Oj.load(params[:order])
78            raise unless od.is_a? Array
79            od
80          else
81            params[:order].split(',')
82          end
83        when Array
84          params[:order]
85        else
86          []
87        end).each do |order|
88         order = order.to_s
89         attr, direction = order.strip.split " "
90         direction ||= 'asc'
91         # The attr can have its table unspecified if it happens to be for the current "model_class" (the first case)
92         # or it can be fully specified with the database tablename (the second case) (e.g. "collections.name").
93         # NB that the security check for the second case table_name will not work if the model
94         # has used set_table_name to use an alternate table name from the Rails standard.
95         # I could not find a perfect way to handle this well, but ActiveRecord::Base.send(:descendants)
96         # would be a place to start if this ever becomes necessary.
97         if attr.match /^[a-z][_a-z0-9]+$/ and
98             model_class.columns.collect(&:name).index(attr) and
99             ['asc','desc'].index direction.downcase
100           @orders << "#{table_name}.#{attr} #{direction.downcase}"
101         elsif attr.match /^([a-z][_a-z0-9]+)\.([a-z][_a-z0-9]+)$/ and
102             ['asc','desc'].index(direction.downcase) and
103             ActiveRecord::Base.connection.tables.include?($1) and
104             $1.classify.constantize.columns.collect(&:name).index($2)
105           # $1 in the above checks references the first match from the regular expression, which is expected to be the database table name
106           # $2 is of course the actual database column name
107           @orders << "#{attr} #{direction.downcase}"
108         end
109       end
110     end
111
112     # If the client-specified orders don't amount to a full ordering
113     # (e.g., [] or ['owner_uuid desc']), fall back on the default
114     # orders to ensure repeating the same request (possibly with
115     # different limit/offset) will return records in the same order.
116     @orders += model_class.default_orders
117
118     case params[:select]
119     when Array
120       @select = params[:select]
121     when String
122       begin
123         @select = Oj.load params[:select]
124         raise unless @select.is_a? Array or @select.nil?
125       rescue
126         raise ArgumentError.new("Could not parse \"select\" param as an array")
127       end
128     end
129
130     if @select
131       # Any ordering columns must be selected when doing select,
132       # otherwise it is an SQL error, so filter out invaliding orderings.
133       @orders.select! { |o|
134         # match select column against order array entry
135         @select.select { |s| /^#{table_name}.#{s}( (asc|desc))?$/.match o }.any?
136       }
137     end
138
139     @distinct = true if (params[:distinct] == true || params[:distinct] == "true")
140     @distinct = false if (params[:distinct] == false || params[:distinct] == "false")
141   end
142
143 end