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