To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / query.rb @ 1298:4f746d8966dd

History | View | Annotate | Download (27.4 KB)

1 0:513646585e45 Chris
# Redmine - project management software
2 1295:622f24f53b42 Chris
# Copyright (C) 2006-2013  Jean-Philippe Lang
3 0:513646585e45 Chris
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8 441:cbce1fd3b1b7 Chris
#
9 0:513646585e45 Chris
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13 441:cbce1fd3b1b7 Chris
#
14 0:513646585e45 Chris
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18 441:cbce1fd3b1b7 Chris
class QueryColumn
19 0:513646585e45 Chris
  attr_accessor :name, :sortable, :groupable, :default_order
20
  include Redmine::I18n
21 441:cbce1fd3b1b7 Chris
22 0:513646585e45 Chris
  def initialize(name, options={})
23
    self.name = name
24
    self.sortable = options[:sortable]
25
    self.groupable = options[:groupable] || false
26
    if groupable == true
27
      self.groupable = name.to_s
28
    end
29
    self.default_order = options[:default_order]
30 1115:433d4f72a19b Chris
    @inline = options.key?(:inline) ? options[:inline] : true
31 1295:622f24f53b42 Chris
    @caption_key = options[:caption] || "field_#{name}".to_sym
32
    @frozen = options[:frozen]
33 0:513646585e45 Chris
  end
34 441:cbce1fd3b1b7 Chris
35 0:513646585e45 Chris
  def caption
36 1295:622f24f53b42 Chris
    @caption_key.is_a?(Symbol) ? l(@caption_key) : @caption_key
37 0:513646585e45 Chris
  end
38 441:cbce1fd3b1b7 Chris
39 0:513646585e45 Chris
  # Returns true if the column is sortable, otherwise false
40
  def sortable?
41 909:cbb26bc654de Chris
    !@sortable.nil?
42
  end
43 1115:433d4f72a19b Chris
44 909:cbb26bc654de Chris
  def sortable
45
    @sortable.is_a?(Proc) ? @sortable.call : @sortable
46 0:513646585e45 Chris
  end
47 441:cbce1fd3b1b7 Chris
48 1115:433d4f72a19b Chris
  def inline?
49
    @inline
50
  end
51
52 1295:622f24f53b42 Chris
  def frozen?
53
    @frozen
54
  end
55
56
  def value(object)
57
    object.send name
58 0:513646585e45 Chris
  end
59 441:cbce1fd3b1b7 Chris
60
  def css_classes
61
    name
62
  end
63 0:513646585e45 Chris
end
64
65
class QueryCustomFieldColumn < QueryColumn
66
67
  def initialize(custom_field)
68
    self.name = "cf_#{custom_field.id}".to_sym
69
    self.sortable = custom_field.order_statement || false
70 1115:433d4f72a19b Chris
    self.groupable = custom_field.group_statement || false
71
    @inline = true
72 0:513646585e45 Chris
    @cf = custom_field
73
  end
74 441:cbce1fd3b1b7 Chris
75 0:513646585e45 Chris
  def caption
76
    @cf.name
77
  end
78 441:cbce1fd3b1b7 Chris
79 0:513646585e45 Chris
  def custom_field
80
    @cf
81
  end
82 441:cbce1fd3b1b7 Chris
83 1295:622f24f53b42 Chris
  def value(object)
84
    cv = object.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)}
85 1115:433d4f72a19b Chris
    cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first
86 0:513646585e45 Chris
  end
87 441:cbce1fd3b1b7 Chris
88
  def css_classes
89
    @css_classes ||= "#{name} #{@cf.field_format}"
90
  end
91 0:513646585e45 Chris
end
92
93 1295:622f24f53b42 Chris
class QueryAssociationCustomFieldColumn < QueryCustomFieldColumn
94
95
  def initialize(association, custom_field)
96
    super(custom_field)
97
    self.name = "#{association}.cf_#{custom_field.id}".to_sym
98
    # TODO: support sorting/grouping by association custom field
99
    self.sortable = false
100
    self.groupable = false
101
    @association = association
102
  end
103
104
  def value(object)
105
    if assoc = object.send(@association)
106
      super(assoc)
107
    end
108
  end
109
110
  def css_classes
111
    @css_classes ||= "#{@association}_cf_#{@cf.id} #{@cf.field_format}"
112
  end
113
end
114
115 0:513646585e45 Chris
class Query < ActiveRecord::Base
116
  class StatementInvalid < ::ActiveRecord::StatementInvalid
117
  end
118 441:cbce1fd3b1b7 Chris
119 0:513646585e45 Chris
  belongs_to :project
120
  belongs_to :user
121
  serialize :filters
122
  serialize :column_names
123
  serialize :sort_criteria, Array
124 441:cbce1fd3b1b7 Chris
125 0:513646585e45 Chris
  attr_protected :project_id, :user_id
126 441:cbce1fd3b1b7 Chris
127 1115:433d4f72a19b Chris
  validates_presence_of :name
128 0:513646585e45 Chris
  validates_length_of :name, :maximum => 255
129 909:cbb26bc654de Chris
  validate :validate_query_filters
130 441:cbce1fd3b1b7 Chris
131 1295:622f24f53b42 Chris
  class_attribute :operators
132
  self.operators = {
133
    "="   => :label_equals,
134
    "!"   => :label_not_equals,
135
    "o"   => :label_open_issues,
136
    "c"   => :label_closed_issues,
137
    "!*"  => :label_none,
138
    "*"   => :label_any,
139
    ">="  => :label_greater_or_equal,
140
    "<="  => :label_less_or_equal,
141
    "><"  => :label_between,
142
    "<t+" => :label_in_less_than,
143
    ">t+" => :label_in_more_than,
144
    "><t+"=> :label_in_the_next_days,
145
    "t+"  => :label_in,
146
    "t"   => :label_today,
147
    "ld"  => :label_yesterday,
148
    "w"   => :label_this_week,
149
    "lw"  => :label_last_week,
150
    "l2w" => [:label_last_n_weeks, {:count => 2}],
151
    "m"   => :label_this_month,
152
    "lm"  => :label_last_month,
153
    "y"   => :label_this_year,
154
    ">t-" => :label_less_than_ago,
155
    "<t-" => :label_more_than_ago,
156
    "><t-"=> :label_in_the_past_days,
157
    "t-"  => :label_ago,
158
    "~"   => :label_contains,
159
    "!~"  => :label_not_contains,
160
    "=p"  => :label_any_issues_in_project,
161
    "=!p" => :label_any_issues_not_in_project,
162
    "!p"  => :label_no_issues_in_project
163
  }
164 0:513646585e45 Chris
165 1295:622f24f53b42 Chris
  class_attribute :operators_by_filter_type
166
  self.operators_by_filter_type = {
167
    :list => [ "=", "!" ],
168
    :list_status => [ "o", "=", "!", "c", "*" ],
169
    :list_optional => [ "=", "!", "!*", "*" ],
170
    :list_subprojects => [ "*", "!*", "=" ],
171
    :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "><t+", "t+", "t", "ld", "w", "lw", "l2w", "m", "lm", "y", ">t-", "<t-", "><t-", "t-", "!*", "*" ],
172
    :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "><t-", "t-", "t", "ld", "w", "lw", "l2w", "m", "lm", "y", "!*", "*" ],
173
    :string => [ "=", "~", "!", "!~", "!*", "*" ],
174
    :text => [  "~", "!~", "!*", "*" ],
175
    :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
176
    :float => [ "=", ">=", "<=", "><", "!*", "*" ],
177
    :relation => ["=", "=p", "=!p", "!p", "!*", "*"]
178
  }
179 441:cbce1fd3b1b7 Chris
180 1295:622f24f53b42 Chris
  class_attribute :available_columns
181
  self.available_columns = []
182 0:513646585e45 Chris
183 1295:622f24f53b42 Chris
  class_attribute :queried_class
184 0:513646585e45 Chris
185 1295:622f24f53b42 Chris
  def queried_table_name
186
    @queried_table_name ||= self.class.queried_class.table_name
187
  end
188 909:cbb26bc654de Chris
189 1115:433d4f72a19b Chris
  def initialize(attributes=nil, *args)
190 0:513646585e45 Chris
    super attributes
191
    @is_for_all = project.nil?
192
  end
193 441:cbce1fd3b1b7 Chris
194 1295:622f24f53b42 Chris
  # Builds the query from the given params
195
  def build_from_params(params)
196
    if params[:fields] || params[:f]
197
      self.filters = {}
198
      add_filters(params[:fields] || params[:f], params[:operators] || params[:op], params[:values] || params[:v])
199
    else
200
      available_filters.keys.each do |field|
201
        add_short_filter(field, params[field]) if params[field]
202
      end
203
    end
204
    self.group_by = params[:group_by] || (params[:query] && params[:query][:group_by])
205
    self.column_names = params[:c] || (params[:query] && params[:query][:column_names])
206
    self
207
  end
208
209
  # Builds a new query from the given params and attributes
210
  def self.build_from_params(params, attributes={})
211
    new(attributes).build_from_params(params)
212
  end
213
214 909:cbb26bc654de Chris
  def validate_query_filters
215 0:513646585e45 Chris
    filters.each_key do |field|
216 909:cbb26bc654de Chris
      if values_for(field)
217
        case type_for(field)
218
        when :integer
219 1115:433d4f72a19b Chris
          add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) }
220 909:cbb26bc654de Chris
        when :float
221 1115:433d4f72a19b Chris
          add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) }
222 909:cbb26bc654de Chris
        when :date, :date_past
223
          case operator_for(field)
224
          when "=", ">=", "<=", "><"
225 1115:433d4f72a19b Chris
            add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
226
          when ">t-", "<t-", "t-", ">t+", "<t+", "t+", "><t+", "><t-"
227
            add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
228 909:cbb26bc654de Chris
          end
229
        end
230
      end
231
232 1115:433d4f72a19b Chris
      add_filter_error(field, :blank) unless
233 0:513646585e45 Chris
          # filter requires one or more values
234 441:cbce1fd3b1b7 Chris
          (values_for(field) and !values_for(field).first.blank?) or
235 0:513646585e45 Chris
          # filter doesn't require any value
236 1295:622f24f53b42 Chris
          ["o", "c", "!*", "*", "t", "ld", "w", "lw", "l2w", "m", "lm", "y"].include? operator_for(field)
237 0:513646585e45 Chris
    end if filters
238
  end
239 909:cbb26bc654de Chris
240 1115:433d4f72a19b Chris
  def add_filter_error(field, message)
241
    m = label_for(field) + " " + l(message, :scope => 'activerecord.errors.messages')
242
    errors.add(:base, m)
243
  end
244
245 0:513646585e45 Chris
  def editable_by?(user)
246
    return false unless user
247
    # Admin can edit them all and regular users can edit their private queries
248
    return true if user.admin? || (!is_public && self.user_id == user.id)
249
    # Members can not edit public queries that are for all project (only admin is allowed to)
250
    is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
251
  end
252 441:cbce1fd3b1b7 Chris
253 1115:433d4f72a19b Chris
  def trackers
254 1295:622f24f53b42 Chris
    @trackers ||= project.nil? ? Tracker.sorted.all : project.rolled_up_trackers
255 1115:433d4f72a19b Chris
  end
256
257
  # Returns a hash of localized labels for all filter operators
258
  def self.operators_labels
259 1295:622f24f53b42 Chris
    operators.inject({}) {|h, operator| h[operator.first] = l(*operator.last); h}
260 0:513646585e45 Chris
  end
261 441:cbce1fd3b1b7 Chris
262 1115:433d4f72a19b Chris
  # Returns a representation of the available filters for JSON serialization
263
  def available_filters_as_json
264
    json = {}
265
    available_filters.each do |field, options|
266
      json[field] = options.slice(:type, :name, :values).stringify_keys
267
    end
268
    json
269
  end
270
271
  def all_projects
272
    @all_projects ||= Project.visible.all
273
  end
274
275
  def all_projects_values
276
    return @all_projects_values if @all_projects_values
277
278
    values = []
279
    Project.project_tree(all_projects) do |p, level|
280
      prefix = (level > 0 ? ('--' * level + ' ') : '')
281
      values << ["#{prefix}#{p.name}", p.id.to_s]
282
    end
283
    @all_projects_values = values
284
  end
285
286 1295:622f24f53b42 Chris
  # Adds available filters
287
  def initialize_available_filters
288
    # implemented by sub-classes
289
  end
290
  protected :initialize_available_filters
291
292
  # Adds an available filter
293
  def add_available_filter(field, options)
294
    @available_filters ||= ActiveSupport::OrderedHash.new
295
    @available_filters[field] = options
296
    @available_filters
297
  end
298
299
  # Removes an available filter
300
  def delete_available_filter(field)
301
    if @available_filters
302
      @available_filters.delete(field)
303
    end
304
  end
305
306
  # Return a hash of available filters
307
  def available_filters
308
    unless @available_filters
309
      initialize_available_filters
310
      @available_filters.each do |field, options|
311
        options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
312
      end
313
    end
314
    @available_filters
315
  end
316
317
  def add_filter(field, operator, values=nil)
318 0:513646585e45 Chris
    # values must be an array
319 909:cbb26bc654de Chris
    return unless values.nil? || values.is_a?(Array)
320 0:513646585e45 Chris
    # check if field is defined as an available filter
321
    if available_filters.has_key? field
322
      filter_options = available_filters[field]
323 909:cbb26bc654de Chris
      filters[field] = {:operator => operator, :values => (values || [''])}
324 0:513646585e45 Chris
    end
325
  end
326 441:cbce1fd3b1b7 Chris
327 0:513646585e45 Chris
  def add_short_filter(field, expression)
328 909:cbb26bc654de Chris
    return unless expression && available_filters.has_key?(field)
329
    field_type = available_filters[field][:type]
330 1295:622f24f53b42 Chris
    operators_by_filter_type[field_type].sort.reverse.detect do |operator|
331 909:cbb26bc654de Chris
      next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
332 1295:622f24f53b42 Chris
      values = $1
333
      add_filter field, operator, values.present? ? values.split('|') : ['']
334 909:cbb26bc654de Chris
    end || add_filter(field, '=', expression.split('|'))
335 0:513646585e45 Chris
  end
336
337
  # Add multiple filters using +add_filter+
338
  def add_filters(fields, operators, values)
339 909:cbb26bc654de Chris
    if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
340 37:94944d00e43c chris
      fields.each do |field|
341 909:cbb26bc654de Chris
        add_filter(field, operators[field], values && values[field])
342 37:94944d00e43c chris
      end
343 0:513646585e45 Chris
    end
344
  end
345 441:cbce1fd3b1b7 Chris
346 0:513646585e45 Chris
  def has_filter?(field)
347
    filters and filters[field]
348
  end
349 441:cbce1fd3b1b7 Chris
350 909:cbb26bc654de Chris
  def type_for(field)
351
    available_filters[field][:type] if available_filters.has_key?(field)
352
  end
353
354 0:513646585e45 Chris
  def operator_for(field)
355
    has_filter?(field) ? filters[field][:operator] : nil
356
  end
357 441:cbce1fd3b1b7 Chris
358 0:513646585e45 Chris
  def values_for(field)
359
    has_filter?(field) ? filters[field][:values] : nil
360
  end
361 441:cbce1fd3b1b7 Chris
362 909:cbb26bc654de Chris
  def value_for(field, index=0)
363
    (values_for(field) || [])[index]
364
  end
365
366 0:513646585e45 Chris
  def label_for(field)
367
    label = available_filters[field][:name] if available_filters.has_key?(field)
368 1115:433d4f72a19b Chris
    label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
369 0:513646585e45 Chris
  end
370
371
  def self.add_available_column(column)
372
    self.available_columns << (column) if column.is_a?(QueryColumn)
373
  end
374 441:cbce1fd3b1b7 Chris
375 0:513646585e45 Chris
  # Returns an array of columns that can be used to group the results
376
  def groupable_columns
377
    available_columns.select {|c| c.groupable}
378
  end
379
380
  # Returns a Hash of columns and the key for sorting
381
  def sortable_columns
382 1295:622f24f53b42 Chris
    available_columns.inject({}) {|h, column|
383
      h[column.name.to_s] = column.sortable
384
      h
385
    }
386 0:513646585e45 Chris
  end
387 441:cbce1fd3b1b7 Chris
388 0:513646585e45 Chris
  def columns
389 909:cbb26bc654de Chris
    # preserve the column_names order
390 1295:622f24f53b42 Chris
    cols = (has_default_columns? ? default_columns_names : column_names).collect do |name|
391 909:cbb26bc654de Chris
       available_columns.find { |col| col.name == name }
392
    end.compact
393 1295:622f24f53b42 Chris
    available_columns.select(&:frozen?) | cols
394 909:cbb26bc654de Chris
  end
395
396 1115:433d4f72a19b Chris
  def inline_columns
397
    columns.select(&:inline?)
398
  end
399
400
  def block_columns
401
    columns.reject(&:inline?)
402
  end
403
404
  def available_inline_columns
405
    available_columns.select(&:inline?)
406
  end
407
408
  def available_block_columns
409
    available_columns.reject(&:inline?)
410
  end
411
412 909:cbb26bc654de Chris
  def default_columns_names
413 1295:622f24f53b42 Chris
    []
414 0:513646585e45 Chris
  end
415 441:cbce1fd3b1b7 Chris
416 0:513646585e45 Chris
  def column_names=(names)
417
    if names
418
      names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
419
      names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
420
      # Set column_names to nil if default columns
421 909:cbb26bc654de Chris
      if names == default_columns_names
422 0:513646585e45 Chris
        names = nil
423
      end
424
    end
425
    write_attribute(:column_names, names)
426
  end
427 441:cbce1fd3b1b7 Chris
428 0:513646585e45 Chris
  def has_column?(column)
429 1115:433d4f72a19b Chris
    column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column)
430 0:513646585e45 Chris
  end
431 441:cbce1fd3b1b7 Chris
432 0:513646585e45 Chris
  def has_default_columns?
433
    column_names.nil? || column_names.empty?
434
  end
435 441:cbce1fd3b1b7 Chris
436 0:513646585e45 Chris
  def sort_criteria=(arg)
437
    c = []
438
    if arg.is_a?(Hash)
439
      arg = arg.keys.sort.collect {|k| arg[k]}
440
    end
441 1115:433d4f72a19b Chris
    c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, (o == 'desc' || o == false) ? 'desc' : 'asc']}
442 0:513646585e45 Chris
    write_attribute(:sort_criteria, c)
443
  end
444 441:cbce1fd3b1b7 Chris
445 0:513646585e45 Chris
  def sort_criteria
446
    read_attribute(:sort_criteria) || []
447
  end
448 441:cbce1fd3b1b7 Chris
449 0:513646585e45 Chris
  def sort_criteria_key(arg)
450
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
451
  end
452 441:cbce1fd3b1b7 Chris
453 0:513646585e45 Chris
  def sort_criteria_order(arg)
454
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
455
  end
456 441:cbce1fd3b1b7 Chris
457 1115:433d4f72a19b Chris
  def sort_criteria_order_for(key)
458
    sort_criteria.detect {|k, order| key.to_s == k}.try(:last)
459
  end
460
461 0:513646585e45 Chris
  # Returns the SQL sort order that should be prepended for grouping
462
  def group_by_sort_order
463
    if grouped? && (column = group_by_column)
464 1115:433d4f72a19b Chris
      order = sort_criteria_order_for(column.name) || column.default_order
465 0:513646585e45 Chris
      column.sortable.is_a?(Array) ?
466 1115:433d4f72a19b Chris
        column.sortable.collect {|s| "#{s} #{order}"}.join(',') :
467
        "#{column.sortable} #{order}"
468 0:513646585e45 Chris
    end
469
  end
470 441:cbce1fd3b1b7 Chris
471 0:513646585e45 Chris
  # Returns true if the query is a grouped query
472
  def grouped?
473 119:8661b858af72 Chris
    !group_by_column.nil?
474 0:513646585e45 Chris
  end
475 441:cbce1fd3b1b7 Chris
476 0:513646585e45 Chris
  def group_by_column
477 119:8661b858af72 Chris
    groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
478 0:513646585e45 Chris
  end
479 441:cbce1fd3b1b7 Chris
480 0:513646585e45 Chris
  def group_by_statement
481 119:8661b858af72 Chris
    group_by_column.try(:groupable)
482 0:513646585e45 Chris
  end
483 441:cbce1fd3b1b7 Chris
484 0:513646585e45 Chris
  def project_statement
485
    project_clauses = []
486 909:cbb26bc654de Chris
    if project && !project.descendants.active.empty?
487 0:513646585e45 Chris
      ids = [project.id]
488
      if has_filter?("subproject_id")
489
        case operator_for("subproject_id")
490
        when '='
491
          # include the selected subprojects
492
          ids += values_for("subproject_id").each(&:to_i)
493
        when '!*'
494
          # main project only
495
        else
496
          # all subprojects
497
          ids += project.descendants.collect(&:id)
498
        end
499
      elsif Setting.display_subprojects_issues?
500
        ids += project.descendants.collect(&:id)
501
      end
502
      project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
503
    elsif project
504
      project_clauses << "#{Project.table_name}.id = %d" % project.id
505
    end
506 441:cbce1fd3b1b7 Chris
    project_clauses.any? ? project_clauses.join(' AND ') : nil
507 0:513646585e45 Chris
  end
508
509
  def statement
510
    # filters clauses
511
    filters_clauses = []
512
    filters.each_key do |field|
513
      next if field == "subproject_id"
514
      v = values_for(field).clone
515
      next unless v and !v.empty?
516
      operator = operator_for(field)
517 441:cbce1fd3b1b7 Chris
518 0:513646585e45 Chris
      # "me" value subsitution
519 1295:622f24f53b42 Chris
      if %w(assigned_to_id author_id user_id watcher_id).include?(field)
520 909:cbb26bc654de Chris
        if v.delete("me")
521
          if User.current.logged?
522
            v.push(User.current.id.to_s)
523
            v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
524
          else
525
            v.push("0")
526
          end
527
        end
528 0:513646585e45 Chris
      end
529 441:cbce1fd3b1b7 Chris
530 1115:433d4f72a19b Chris
      if field == 'project_id'
531
        if v.delete('mine')
532
          v += User.current.memberships.map(&:project_id).map(&:to_s)
533
        end
534
      end
535
536
      if field =~ /cf_(\d+)$/
537 0:513646585e45 Chris
        # custom field
538 909:cbb26bc654de Chris
        filters_clauses << sql_for_custom_field(field, operator, v, $1)
539
      elsif respond_to?("sql_for_#{field}_field")
540
        # specific statement
541
        filters_clauses << send("sql_for_#{field}_field", field, operator, v)
542 0:513646585e45 Chris
      else
543
        # regular field
544 1295:622f24f53b42 Chris
        filters_clauses << '(' + sql_for_field(field, operator, v, queried_table_name, field) + ')'
545 0:513646585e45 Chris
      end
546
    end if filters and valid?
547 441:cbce1fd3b1b7 Chris
548
    filters_clauses << project_statement
549
    filters_clauses.reject!(&:blank?)
550
551
    filters_clauses.any? ? filters_clauses.join(' AND ') : nil
552 0:513646585e45 Chris
  end
553 441:cbce1fd3b1b7 Chris
554 0:513646585e45 Chris
  private
555 441:cbce1fd3b1b7 Chris
556 909:cbb26bc654de Chris
  def sql_for_custom_field(field, operator, value, custom_field_id)
557
    db_table = CustomValue.table_name
558
    db_field = 'value'
559 1115:433d4f72a19b Chris
    filter = @available_filters[field]
560
    return nil unless filter
561
    if filter[:format] == 'user'
562
      if value.delete('me')
563
        value.push User.current.id.to_s
564
      end
565
    end
566
    not_in = nil
567
    if operator == '!'
568
      # Makes ! operator work for custom fields with multiple values
569
      operator = '='
570
      not_in = 'NOT'
571
    end
572
    customized_key = "id"
573 1295:622f24f53b42 Chris
    customized_class = queried_class
574 1115:433d4f72a19b Chris
    if field =~ /^(.+)\.cf_/
575
      assoc = $1
576
      customized_key = "#{assoc}_id"
577 1295:622f24f53b42 Chris
      customized_class = queried_class.reflect_on_association(assoc.to_sym).klass.base_class rescue nil
578
      raise "Unknown #{queried_class.name} association #{assoc}" unless customized_class
579 1115:433d4f72a19b Chris
    end
580 1295:622f24f53b42 Chris
    where = sql_for_field(field, operator, value, db_table, db_field, true)
581
    if operator =~ /[<>]/
582
      where = "(#{where}) AND #{db_table}.#{db_field} <> ''"
583
    end
584
    "#{queried_table_name}.#{customized_key} #{not_in} IN (SELECT #{customized_class.table_name}.id FROM #{customized_class.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='#{customized_class}' AND #{db_table}.customized_id=#{customized_class.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE #{where})"
585 909:cbb26bc654de Chris
  end
586
587 0:513646585e45 Chris
  # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
588
  def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
589
    sql = ''
590
    case operator
591
    when "="
592 245:051f544170fe Chris
      if value.any?
593 909:cbb26bc654de Chris
        case type_for(field)
594
        when :date, :date_past
595
          sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
596
        when :integer
597 1115:433d4f72a19b Chris
          if is_custom_filter
598 1295:622f24f53b42 Chris
            sql = "(#{db_table}.#{db_field} <> '' AND CAST(CASE #{db_table}.#{db_field} WHEN '' THEN '0' ELSE #{db_table}.#{db_field} END AS decimal(30,3)) = #{value.first.to_i})"
599 1115:433d4f72a19b Chris
          else
600
            sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
601
          end
602 909:cbb26bc654de Chris
        when :float
603 1115:433d4f72a19b Chris
          if is_custom_filter
604 1295:622f24f53b42 Chris
            sql = "(#{db_table}.#{db_field} <> '' AND CAST(CASE #{db_table}.#{db_field} WHEN '' THEN '0' ELSE #{db_table}.#{db_field} END AS decimal(30,3)) BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5})"
605 1115:433d4f72a19b Chris
          else
606
            sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
607
          end
608 909:cbb26bc654de Chris
        else
609
          sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
610
        end
611 245:051f544170fe Chris
      else
612
        # IN an empty set
613
        sql = "1=0"
614
      end
615 0:513646585e45 Chris
    when "!"
616 245:051f544170fe Chris
      if value.any?
617
        sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
618
      else
619
        # NOT IN an empty set
620
        sql = "1=1"
621
      end
622 0:513646585e45 Chris
    when "!*"
623
      sql = "#{db_table}.#{db_field} IS NULL"
624
      sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
625
    when "*"
626
      sql = "#{db_table}.#{db_field} IS NOT NULL"
627
      sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
628
    when ">="
629 909:cbb26bc654de Chris
      if [:date, :date_past].include?(type_for(field))
630
        sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
631
      else
632
        if is_custom_filter
633 1295:622f24f53b42 Chris
          sql = "(#{db_table}.#{db_field} <> '' AND CAST(CASE #{db_table}.#{db_field} WHEN '' THEN '0' ELSE #{db_table}.#{db_field} END AS decimal(30,3)) >= #{value.first.to_f})"
634 909:cbb26bc654de Chris
        else
635
          sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
636
        end
637
      end
638 0:513646585e45 Chris
    when "<="
639 909:cbb26bc654de Chris
      if [:date, :date_past].include?(type_for(field))
640
        sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
641
      else
642
        if is_custom_filter
643 1295:622f24f53b42 Chris
          sql = "(#{db_table}.#{db_field} <> '' AND CAST(CASE #{db_table}.#{db_field} WHEN '' THEN '0' ELSE #{db_table}.#{db_field} END AS decimal(30,3)) <= #{value.first.to_f})"
644 909:cbb26bc654de Chris
        else
645
          sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
646
        end
647
      end
648
    when "><"
649
      if [:date, :date_past].include?(type_for(field))
650
        sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
651
      else
652
        if is_custom_filter
653 1295:622f24f53b42 Chris
          sql = "(#{db_table}.#{db_field} <> '' AND CAST(CASE #{db_table}.#{db_field} WHEN '' THEN '0' ELSE #{db_table}.#{db_field} END AS decimal(30,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f})"
654 909:cbb26bc654de Chris
        else
655
          sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
656
        end
657
      end
658 0:513646585e45 Chris
    when "o"
659 1295:622f24f53b42 Chris
      sql = "#{queried_table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id"
660 0:513646585e45 Chris
    when "c"
661 1295:622f24f53b42 Chris
      sql = "#{queried_table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id"
662 1115:433d4f72a19b Chris
    when "><t-"
663
      # between today - n days and today
664
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
665 0:513646585e45 Chris
    when ">t-"
666 1115:433d4f72a19b Chris
      # >= today - n days
667
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, nil)
668 0:513646585e45 Chris
    when "<t-"
669 1115:433d4f72a19b Chris
      # <= today - n days
670 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
671 0:513646585e45 Chris
    when "t-"
672 1115:433d4f72a19b Chris
      # = n days in past
673 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
674 1115:433d4f72a19b Chris
    when "><t+"
675
      # between today and today + n days
676
      sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
677 0:513646585e45 Chris
    when ">t+"
678 1115:433d4f72a19b Chris
      # >= today + n days
679 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
680 0:513646585e45 Chris
    when "<t+"
681 1115:433d4f72a19b Chris
      # <= today + n days
682
      sql = relative_date_clause(db_table, db_field, nil, value.first.to_i)
683 0:513646585e45 Chris
    when "t+"
684 1115:433d4f72a19b Chris
      # = today + n days
685 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
686 0:513646585e45 Chris
    when "t"
687 1115:433d4f72a19b Chris
      # = today
688 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, 0, 0)
689 1295:622f24f53b42 Chris
    when "ld"
690
      # = yesterday
691
      sql = relative_date_clause(db_table, db_field, -1, -1)
692 0:513646585e45 Chris
    when "w"
693 1115:433d4f72a19b Chris
      # = this week
694 441:cbce1fd3b1b7 Chris
      first_day_of_week = l(:general_first_day_of_week).to_i
695
      day_of_week = Date.today.cwday
696
      days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
697 909:cbb26bc654de Chris
      sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
698 1295:622f24f53b42 Chris
    when "lw"
699
      # = last week
700
      first_day_of_week = l(:general_first_day_of_week).to_i
701
      day_of_week = Date.today.cwday
702
      days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
703
      sql = relative_date_clause(db_table, db_field, - days_ago - 7, - days_ago - 1)
704
    when "l2w"
705
      # = last 2 weeks
706
      first_day_of_week = l(:general_first_day_of_week).to_i
707
      day_of_week = Date.today.cwday
708
      days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
709
      sql = relative_date_clause(db_table, db_field, - days_ago - 14, - days_ago - 1)
710
    when "m"
711
      # = this month
712
      date = Date.today
713
      sql = date_clause(db_table, db_field, date.beginning_of_month, date.end_of_month)
714
    when "lm"
715
      # = last month
716
      date = Date.today.prev_month
717
      sql = date_clause(db_table, db_field, date.beginning_of_month, date.end_of_month)
718
    when "y"
719
      # = this year
720
      date = Date.today
721
      sql = date_clause(db_table, db_field, date.beginning_of_year, date.end_of_year)
722 0:513646585e45 Chris
    when "~"
723
      sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
724
    when "!~"
725
      sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
726 909:cbb26bc654de Chris
    else
727
      raise "Unknown query operator #{operator}"
728 0:513646585e45 Chris
    end
729 441:cbce1fd3b1b7 Chris
730 0:513646585e45 Chris
    return sql
731
  end
732 441:cbce1fd3b1b7 Chris
733 1115:433d4f72a19b Chris
  def add_custom_fields_filters(custom_fields, assoc=nil)
734
    return unless custom_fields.present?
735 441:cbce1fd3b1b7 Chris
736 1295:622f24f53b42 Chris
    custom_fields.select(&:is_filter?).sort.each do |field|
737 0:513646585e45 Chris
      case field.field_format
738
      when "text"
739 1295:622f24f53b42 Chris
        options = { :type => :text }
740 0:513646585e45 Chris
      when "list"
741 1295:622f24f53b42 Chris
        options = { :type => :list_optional, :values => field.possible_values }
742 0:513646585e45 Chris
      when "date"
743 1295:622f24f53b42 Chris
        options = { :type => :date }
744 0:513646585e45 Chris
      when "bool"
745 1295:622f24f53b42 Chris
        options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]] }
746 909:cbb26bc654de Chris
      when "int"
747 1295:622f24f53b42 Chris
        options = { :type => :integer }
748 909:cbb26bc654de Chris
      when "float"
749 1295:622f24f53b42 Chris
        options = { :type => :float }
750 441:cbce1fd3b1b7 Chris
      when "user", "version"
751
        next unless project
752 1115:433d4f72a19b Chris
        values = field.possible_values_options(project)
753
        if User.current.logged? && field.field_format == 'user'
754
          values.unshift ["<< #{l(:label_me)} >>", "me"]
755
        end
756 1295:622f24f53b42 Chris
        options = { :type => :list_optional, :values => values }
757 0:513646585e45 Chris
      else
758 1295:622f24f53b42 Chris
        options = { :type => :string }
759 0:513646585e45 Chris
      end
760 1115:433d4f72a19b Chris
      filter_id = "cf_#{field.id}"
761
      filter_name = field.name
762
      if assoc.present?
763
        filter_id = "#{assoc}.#{filter_id}"
764
        filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
765
      end
766 1295:622f24f53b42 Chris
      add_available_filter filter_id, options.merge({
767 1115:433d4f72a19b Chris
               :name => filter_name,
768
               :format => field.field_format,
769
               :field => field
770
             })
771
    end
772
  end
773
774
  def add_associations_custom_fields_filters(*associations)
775
    fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
776
    associations.each do |assoc|
777 1295:622f24f53b42 Chris
      association_klass = queried_class.reflect_on_association(assoc).klass
778 1115:433d4f72a19b Chris
      fields_by_class.each do |field_class, fields|
779
        if field_class.customized_class <= association_klass
780
          add_custom_fields_filters(fields, assoc)
781
        end
782
      end
783 0:513646585e45 Chris
    end
784
  end
785 441:cbce1fd3b1b7 Chris
786 0:513646585e45 Chris
  # Returns a SQL clause for a date or datetime field.
787 909:cbb26bc654de Chris
  def date_clause(table, field, from, to)
788 0:513646585e45 Chris
    s = []
789
    if from
790 909:cbb26bc654de Chris
      from_yesterday = from - 1
791 1115:433d4f72a19b Chris
      from_yesterday_time = Time.local(from_yesterday.year, from_yesterday.month, from_yesterday.day)
792
      if self.class.default_timezone == :utc
793
        from_yesterday_time = from_yesterday_time.utc
794
      end
795
      s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_time.end_of_day)])
796 0:513646585e45 Chris
    end
797
    if to
798 1115:433d4f72a19b Chris
      to_time = Time.local(to.year, to.month, to.day)
799
      if self.class.default_timezone == :utc
800
        to_time = to_time.utc
801
      end
802
      s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_time.end_of_day)])
803 0:513646585e45 Chris
    end
804
    s.join(' AND ')
805
  end
806 909:cbb26bc654de Chris
807
  # Returns a SQL clause for a date or datetime field using relative dates.
808
  def relative_date_clause(table, field, days_from, days_to)
809
    date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
810
  end
811 1115:433d4f72a19b Chris
812
  # Additional joins required for the given sort options
813
  def joins_for_order_statement(order_options)
814
    joins = []
815
816
    if order_options
817
      if order_options.include?('authors')
818 1295:622f24f53b42 Chris
        joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{queried_table_name}.author_id"
819 1115:433d4f72a19b Chris
      end
820
      order_options.scan(/cf_\d+/).uniq.each do |name|
821
        column = available_columns.detect {|c| c.name.to_s == name}
822
        join = column && column.custom_field.join_for_order_statement
823
        if join
824
          joins << join
825
        end
826
      end
827
    end
828
829
    joins.any? ? joins.join(' ') : nil
830
  end
831 0:513646585e45 Chris
end