Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[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   def default_orders
51     ["#{table_name}.modified_at desc"]
52   end
53
54   # Load params[:limit], params[:offset] and params[:order]
55   # into @limit, @offset, @orders
56   def load_limit_offset_order_params
57     if params[:limit]
58       unless params[:limit].to_s.match(/^\d+$/)
59         raise ArgumentError.new("Invalid value for limit parameter")
60       end
61       @limit = [params[:limit].to_i, MAX_LIMIT].min
62     else
63       @limit = DEFAULT_LIMIT
64     end
65
66     if params[:offset]
67       unless params[:offset].to_s.match(/^\d+$/)
68         raise ArgumentError.new("Invalid value for offset parameter")
69       end
70       @offset = params[:offset].to_i
71     else
72       @offset = 0
73     end
74
75     @orders = []
76     if (params[:order].is_a?(Array) && !params[:order].empty?) || !params[:order].blank?
77       od = []
78       (case params[:order]
79        when String
80          if params[:order].starts_with? '['
81            od = Oj.load(params[:order])
82            raise unless od.is_a? Array
83            od
84          else
85            params[:order].split(',')
86          end
87        when Array
88          params[:order]
89        else
90          []
91        end).each do |order|
92         order = order.to_s
93         attr, direction = order.strip.split " "
94         direction ||= 'asc'
95         # The attr can have its table unspecified if it happens to be for the current "model_class" (the first case)
96         # or it can be fully specified with the database tablename (the second case) (e.g. "collections.name").
97         # NB that the security check for the second case table_name will not work if the model
98         # has used set_table_name to use an alternate table name from the Rails standard.
99         # I could not find a perfect way to handle this well, but ActiveRecord::Base.send(:descendants)
100         # would be a place to start if this ever becomes necessary.
101         if attr.match /^[a-z][_a-z0-9]+$/ and
102             model_class.columns.collect(&:name).index(attr) and
103             ['asc','desc'].index direction.downcase
104           @orders << "#{table_name}.#{attr} #{direction.downcase}"
105         elsif attr.match /^([a-z][_a-z0-9]+)\.([a-z][_a-z0-9]+)$/ and
106             ['asc','desc'].index(direction.downcase) and
107             ActiveRecord::Base.connection.tables.include?($1) and
108             $1.classify.constantize.columns.collect(&:name).index($2)
109           # $1 in the above checks references the first match from the regular expression, which is expected to be the database table name
110           # $2 is of course the actual database column name
111           @orders << "#{attr} #{direction.downcase}"
112         end
113       end
114     end
115
116     if @orders.empty?
117       @orders = default_orders
118     end
119
120     case params[:select]
121     when Array
122       @select = params[:select]
123     when String
124       begin
125         @select = Oj.load params[:select]
126         raise unless @select.is_a? Array or @select.nil?
127       rescue
128         raise ArgumentError.new("Could not parse \"select\" param as an array")
129       end
130     end
131
132     if @select
133       # Any ordering columns must be selected when doing select,
134       # otherwise it is an SQL error, so filter out invaliding orderings.
135       @orders.select! { |o|
136         # match select column against order array entry
137         @select.select { |s| /^#{table_name}.#{s}( (asc|desc))?$/.match o }.any?
138       }
139     end
140
141     @distinct = true if (params[:distinct] == true || params[:distinct] == "true")
142     @distinct = false if (params[:distinct] == false || params[:distinct] == "false")
143   end
144
145 end