Project

General

Profile

Defect #9904 ยป query.rb

Mike Dubman, 2012-01-04 09:28

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2011  Jean-Philippe Lang
3
#
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
#
9
# 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
#
14
# 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
class QueryColumn
19
  attr_accessor :name, :sortable, :groupable, :default_order
20
  include Redmine::I18n
21

    
22
  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
    @caption_key = options[:caption] || "field_#{name}"
31
  end
32

    
33
  def caption
34
    l(@caption_key)
35
  end
36

    
37
  # Returns true if the column is sortable, otherwise false
38
  def sortable?
39
    !@sortable.nil?
40
  end
41
  
42
  def sortable
43
    @sortable.is_a?(Proc) ? @sortable.call : @sortable
44
  end
45

    
46
  def value(issue)
47
    issue.send name
48
  end
49

    
50
  def css_classes
51
    name
52
  end
53
end
54

    
55
class QueryCustomFieldColumn < QueryColumn
56

    
57
  def initialize(custom_field)
58
    self.name = "cf_#{custom_field.id}".to_sym
59
    self.sortable = custom_field.order_statement || false
60
    if %w(list date bool int).include?(custom_field.field_format)
61
      self.groupable = custom_field.order_statement
62
    end
63
    self.groupable ||= false
64
    @cf = custom_field
65
  end
66

    
67
  def caption
68
    @cf.name
69
  end
70

    
71
  def custom_field
72
    @cf
73
  end
74

    
75
  def value(issue)
76
    cv = issue.custom_values.detect {|v| v.custom_field_id == @cf.id}
77
    cv && @cf.cast_value(cv.value)
78
  end
79

    
80
  def css_classes
81
    @css_classes ||= "#{name} #{@cf.field_format}"
82
  end
83
end
84

    
85
class Query < ActiveRecord::Base
86
  class StatementInvalid < ::ActiveRecord::StatementInvalid
87
  end
88

    
89
  belongs_to :project
90
  belongs_to :user
91
  serialize :filters
92
  serialize :column_names
93
  serialize :sort_criteria, Array
94

    
95
  attr_protected :project_id, :user_id
96

    
97
  validates_presence_of :name, :on => :save
98
  validates_length_of :name, :maximum => 255
99
  validate :validate_query_filters
100

    
101
  @@operators = { "="   => :label_equals,
102
                  "!"   => :label_not_equals,
103
                  "o"   => :label_open_issues,
104
                  "c"   => :label_closed_issues,
105
                  "!*"  => :label_none,
106
                  "*"   => :label_all,
107
                  ">="  => :label_greater_or_equal,
108
                  "<="  => :label_less_or_equal,
109
                  "><"  => :label_between,
110
                  "<t+" => :label_in_less_than,
111
                  ">t+" => :label_in_more_than,
112
                  "t+"  => :label_in,
113
                  "t"   => :label_today,
114
                  "w"   => :label_this_week,
115
                  ">t-" => :label_less_than_ago,
116
                  "<t-" => :label_more_than_ago,
117
                  "t-"  => :label_ago,
118
                  "~"   => :label_contains,
119
                  "!~"  => :label_not_contains }
120

    
121
  cattr_reader :operators
122

    
123
  @@operators_by_filter_type = { :list => [ "=", "!" ],
124
                                 :list_status => [ "o", "=", "!", "c", "*" ],
125
                                 :list_optional => [ "=", "!", "!*", "*" ],
126
                                 :list_subprojects => [ "*", "!*", "=" ],
127
                                 :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-", "!*", "*" ],
128
                                 :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "t-", "t", "w", "!*", "*" ],
129
                                 :string => [ "=", "~", "!", "!~" ],
130
                                 :text => [  "~", "!~" ],
131
                                 :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
132
                                 :float => [ "=", ">=", "<=", "><", "!*", "*" ] }
133

    
134
  cattr_reader :operators_by_filter_type
135

    
136
  @@available_columns = [
137
    QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
138
    QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
139
    QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
140
    QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
141
    QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
142
    QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
143
    QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
144
    QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
145
    QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
146
    QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
147
    QueryColumn.new(:fixed_version, :sortable => ["#{Version.table_name}.effective_date", "#{Version.table_name}.name"], :default_order => 'desc', :groupable => true),
148
    QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
149
    QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
150
    QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
151
    QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
152
    QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
153
  ]
154
  cattr_reader :available_columns
155

    
156
  named_scope :visible, lambda {|*args|
157
    user = args.shift || User.current
158
    base = Project.allowed_to_condition(user, :view_issues, *args)
159
    user_id = user.logged? ? user.id : 0
160
    {
161
      :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id],
162
      :include => :project
163
    }
164
  }
165

    
166
  def initialize(attributes = nil)
167
    super attributes
168
    self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
169
  end
170

    
171
  def after_initialize
172
    # Store the fact that project is nil (used in #editable_by?)
173
    @is_for_all = project.nil?
174
  end
175

    
176
  def validate_query_filters
177
    filters.each_key do |field|
178
      if values_for(field)
179
        case type_for(field)
180
        when :integer
181
          errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
182
        when :float
183
          errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+(\.\d*)?$/) }
184
        when :date, :date_past
185
          case operator_for(field)
186
          when "=", ">=", "<=", "><"
187
            errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
188
          when ">t-", "<t-", "t-"
189
            errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
190
          end
191
        end
192
      end
193

    
194
      errors.add label_for(field), :blank unless
195
          # filter requires one or more values
196
          (values_for(field) and !values_for(field).first.blank?) or
197
          # filter doesn't require any value
198
          ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
199
    end if filters
200
  end
201

    
202
  # Returns true if the query is visible to +user+ or the current user.
203
  def visible?(user=User.current)
204
    (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id)
205
  end
206

    
207
  def editable_by?(user)
208
    return false unless user
209
    # Admin can edit them all and regular users can edit their private queries
210
    return true if user.admin? || (!is_public && self.user_id == user.id)
211
    # Members can not edit public queries that are for all project (only admin is allowed to)
212
    is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
213
  end
214

    
215
  def available_filters
216
    return @available_filters if @available_filters
217

    
218
    trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
219

    
220
    @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
221
                           "tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
222
                           "priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
223
                           "subject" => { :type => :text, :order => 8 },
224
                           "created_on" => { :type => :date_past, :order => 9 },
225
                           "updated_on" => { :type => :date_past, :order => 10 },
226
                           "start_date" => { :type => :date, :order => 11 },
227
                           "due_date" => { :type => :date, :order => 12 },
228
                           "estimated_hours" => { :type => :float, :order => 13 },
229
                           "done_ratio" =>  { :type => :integer, :order => 14 }}
230

    
231
    principals = []
232
    if project
233
      principals += project.principals.sort
234
    else
235
      all_projects = Project.visible.all
236
      if all_projects.any?
237
        # members of visible projects
238
        principals += Principal.active.find(:all, :conditions => ["#{User.table_name}.id IN (SELECT DISTINCT user_id FROM members WHERE project_id IN (?))", all_projects.collect(&:id)]).sort
239

    
240
        # project filter
241
        project_values = []
242
        Project.project_tree(all_projects) do |p, level|
243
          prefix = (level > 0 ? ('--' * level + ' ') : '')
244
          project_values << ["#{prefix}#{p.name}", p.id.to_s]
245
        end
246
        @available_filters["project_id"] = { :type => :list, :order => 1, :values => project_values} unless project_values.empty?
247
      end
248
    end
249
    users = principals.select {|p| p.is_a?(User)}
250

    
251
    assigned_to_values = []
252
    assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
253
    assigned_to_values += (Setting.issue_group_assignment? ? principals : users).collect{|s| [s.name, s.id.to_s] }
254
    @available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => assigned_to_values } unless assigned_to_values.empty?
255

    
256
    author_values = []
257
    author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
258
    author_values += users.collect{|s| [s.name, s.id.to_s] }
259
    @available_filters["author_id"] = { :type => :list, :order => 5, :values => author_values } unless author_values.empty?
260

    
261
    group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
262
    @available_filters["member_of_group"] = { :type => :list_optional, :order => 6, :values => group_values } unless group_values.empty?
263

    
264
    role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
265
    @available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
266

    
267
    if User.current.logged?
268
      @available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
269
    end
270

    
271
    if project
272
      # project specific filters
273
      categories = project.issue_categories.all
274
      unless categories.empty?
275
        @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
276
      end
277
      versions = project.shared_versions.all
278
      unless versions.empty?
279
        @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
280
      end
281
      unless project.leaf?
282
        subprojects = project.descendants.visible.all
283
        unless subprojects.empty?
284
          @available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
285
        end
286
      end
287
      add_custom_fields_filters(project.all_issue_custom_fields)
288
    else
289
      # global filters for cross project issue list
290
      system_shared_versions = Version.visible.find_all_by_sharing('system')
291
      unless system_shared_versions.empty?
292
        @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => system_shared_versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
293
      end
294
      add_custom_fields_filters(IssueCustomField.find(:all, :conditions => {:is_filter => true, :is_for_all => true}))
295
    end
296
    @available_filters
297
  end
298

    
299
  def add_filter(field, operator, values)
300
    # values must be an array
301
    return unless values.nil? || values.is_a?(Array)
302
    # check if field is defined as an available filter
303
    if available_filters.has_key? field
304
      filter_options = available_filters[field]
305
      # check if operator is allowed for that filter
306
      #if @@operators_by_filter_type[filter_options[:type]].include? operator
307
      #  allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
308
      #  filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
309
      #end
310
      filters[field] = {:operator => operator, :values => (values || [''])}
311
    end
312
  end
313

    
314
  def add_short_filter(field, expression)
315
    return unless expression && available_filters.has_key?(field)
316
    field_type = available_filters[field][:type]
317
    @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
318
      next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
319
      add_filter field, operator, $1.present? ? $1.split('|') : ['']
320
    end || add_filter(field, '=', expression.split('|'))
321
  end
322

    
323
  # Add multiple filters using +add_filter+
324
  def add_filters(fields, operators, values)
325
    if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
326
      fields.each do |field|
327
        add_filter(field, operators[field], values && values[field])
328
      end
329
    end
330
  end
331

    
332
  def has_filter?(field)
333
    filters and filters[field]
334
  end
335

    
336
  def type_for(field)
337
    available_filters[field][:type] if available_filters.has_key?(field)
338
  end
339

    
340
  def operator_for(field)
341
    has_filter?(field) ? filters[field][:operator] : nil
342
  end
343

    
344
  def values_for(field)
345
    has_filter?(field) ? filters[field][:values] : nil
346
  end
347

    
348
  def value_for(field, index=0)
349
    (values_for(field) || [])[index]
350
  end
351

    
352
  def label_for(field)
353
    label = available_filters[field][:name] if available_filters.has_key?(field)
354
    label ||= field.gsub(/\_id$/, "")
355
  end
356

    
357
  def available_columns
358
    return @available_columns if @available_columns
359
    @available_columns = ::Query.available_columns
360
    @available_columns += (project ?
361
                            project.all_issue_custom_fields :
362
                            IssueCustomField.find(:all)
363
                           ).collect {|cf| QueryCustomFieldColumn.new(cf) }
364
  end
365

    
366
  def self.available_columns=(v)
367
    self.available_columns = (v)
368
  end
369

    
370
  def self.add_available_column(column)
371
    self.available_columns << (column) if column.is_a?(QueryColumn)
372
  end
373

    
374
  # Returns an array of columns that can be used to group the results
375
  def groupable_columns
376
    available_columns.select {|c| c.groupable}
377
  end
378

    
379
  # Returns a Hash of columns and the key for sorting
380
  def sortable_columns
381
    {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
382
                                               h[column.name.to_s] = column.sortable
383
                                               h
384
                                             })
385
  end
386

    
387
  def columns
388
    # preserve the column_names order
389
    (has_default_columns? ? default_columns_names : column_names).collect do |name|
390
       available_columns.find { |col| col.name == name }
391
    end.compact
392
  end
393

    
394
  def default_columns_names
395
    @default_columns_names ||= begin
396
      default_columns = Setting.issue_list_default_columns.map(&:to_sym)
397

    
398
      project.present? ? default_columns : [:project] | default_columns
399
    end
400
  end
401

    
402
  def column_names=(names)
403
    if names
404
      names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
405
      names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
406
      # Set column_names to nil if default columns
407
      if names == default_columns_names
408
        names = nil
409
      end
410
    end
411
    write_attribute(:column_names, names)
412
  end
413

    
414
  def has_column?(column)
415
    column_names && column_names.include?(column.name)
416
  end
417

    
418
  def has_default_columns?
419
    column_names.nil? || column_names.empty?
420
  end
421

    
422
  def sort_criteria=(arg)
423
    c = []
424
    if arg.is_a?(Hash)
425
      arg = arg.keys.sort.collect {|k| arg[k]}
426
    end
427
    c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
428
    write_attribute(:sort_criteria, c)
429
  end
430

    
431
  def sort_criteria
432
    read_attribute(:sort_criteria) || []
433
  end
434

    
435
  def sort_criteria_key(arg)
436
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
437
  end
438

    
439
  def sort_criteria_order(arg)
440
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
441
  end
442

    
443
  # Returns the SQL sort order that should be prepended for grouping
444
  def group_by_sort_order
445
    if grouped? && (column = group_by_column)
446
      column.sortable.is_a?(Array) ?
447
        column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
448
        "#{column.sortable} #{column.default_order}"
449
    end
450
  end
451

    
452
  # Returns true if the query is a grouped query
453
  def grouped?
454
    !group_by_column.nil?
455
  end
456

    
457
  def group_by_column
458
    groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
459
  end
460

    
461
  def group_by_statement
462
    group_by_column.try(:groupable)
463
  end
464

    
465
  def project_statement
466
    project_clauses = []
467
    if project && !project.descendants.active.empty?
468
      ids = [project.id]
469
      if has_filter?("subproject_id")
470
        case operator_for("subproject_id")
471
        when '='
472
          # include the selected subprojects
473
          ids += values_for("subproject_id").each(&:to_i)
474
        when '!*'
475
          # main project only
476
        else
477
          # all subprojects
478
          ids += project.descendants.collect(&:id)
479
        end
480
      elsif Setting.display_subprojects_issues?
481
        ids += project.descendants.collect(&:id)
482
      end
483
      project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
484
    elsif project
485
      project_clauses << "#{Project.table_name}.id = %d" % project.id
486
    end
487
    project_clauses.any? ? project_clauses.join(' AND ') : nil
488
  end
489

    
490
  def statement
491
    # filters clauses
492
    filters_clauses = []
493
    filters.each_key do |field|
494
      next if field == "subproject_id"
495
      v = values_for(field).clone
496
      next unless v and !v.empty?
497
      operator = operator_for(field)
498

    
499
      # "me" value subsitution
500
      if %w(assigned_to_id author_id watcher_id).include?(field)
501
        if v.delete("me")
502
          if User.current.logged?
503
            v.push(User.current.id.to_s)
504
            v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
505
          else
506
            v.push("0")
507
          end
508
        end
509
      end
510

    
511
      if field =~ /^cf_(\d+)$/
512
        # custom field
513
        filters_clauses << sql_for_custom_field(field, operator, v, $1)
514
      elsif respond_to?("sql_for_#{field}_field")
515
        # specific statement
516
        filters_clauses << send("sql_for_#{field}_field", field, operator, v)
517
      else
518
        # regular field
519
        filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')'
520
      end
521
    end if filters and valid?
522

    
523
    filters_clauses << project_statement
524
    filters_clauses.reject!(&:blank?)
525

    
526
    filters_clauses.any? ? filters_clauses.join(' AND ') : nil
527
  end
528

    
529
  # Returns the issue count
530
  def issue_count
531
    Issue.visible.count(:include => [:status, :project], :conditions => statement)
532
  rescue ::ActiveRecord::StatementInvalid => e
533
    raise StatementInvalid.new(e.message)
534
  end
535

    
536
  # Returns the issue count by group or nil if query is not grouped
537
  def issue_count_by_group
538
    r = nil
539
    if grouped?
540
      begin
541
        # Rails will raise an (unexpected) RecordNotFound if there's only a nil group value
542
        r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
543
      rescue ActiveRecord::RecordNotFound
544
        r = {nil => issue_count}
545
      end
546
      c = group_by_column
547
      if c.is_a?(QueryCustomFieldColumn)
548
        r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
549
      end
550
    end
551
    r
552
  rescue ::ActiveRecord::StatementInvalid => e
553
    raise StatementInvalid.new(e.message)
554
  end
555

    
556
  # Returns the issues
557
  # Valid options are :order, :offset, :limit, :include, :conditions
558
  def issues(options={})
559
    order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
560
    order_option = nil if order_option.blank?
561
    
562
    joins = (order_option && order_option.include?('authors')) ? "LEFT OUTER JOIN users authors ON authors.id = #{Issue.table_name}.author_id" : nil
563

    
564
    Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
565
                     :conditions => statement,
566
                     :order => order_option,
567
                     :joins => joins,
568
                     :limit  => options[:limit],
569
                     :offset => options[:offset]
570
  rescue ::ActiveRecord::StatementInvalid => e
571
    raise StatementInvalid.new(e.message)
572
  end
573

    
574
  # Returns the journals
575
  # Valid options are :order, :offset, :limit
576
  def journals(options={})
577
    Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
578
                       :conditions => statement,
579
                       :order => options[:order],
580
                       :limit => options[:limit],
581
                       :offset => options[:offset]
582
  rescue ::ActiveRecord::StatementInvalid => e
583
    raise StatementInvalid.new(e.message)
584
  end
585

    
586
  # Returns the versions
587
  # Valid options are :conditions
588
  def versions(options={})
589
    Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement
590
  rescue ::ActiveRecord::StatementInvalid => e
591
    raise StatementInvalid.new(e.message)
592
  end
593

    
594
  def sql_for_watcher_id_field(field, operator, value)
595
    db_table = Watcher.table_name
596
    "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
597
      sql_for_field(field, '=', value, db_table, 'user_id') + ')'
598
  end
599

    
600
  def sql_for_member_of_group_field(field, operator, value)
601
    if operator == '*' # Any group
602
      groups = Group.all
603
      operator = '=' # Override the operator since we want to find by assigned_to
604
    elsif operator == "!*"
605
      groups = Group.all
606
      operator = '!' # Override the operator since we want to find by assigned_to
607
    else
608
      groups = Group.find_all_by_id(value)
609
    end
610
    groups ||= []
611

    
612
    members_of_groups = groups.inject([]) {|user_ids, group|
613
      if group && group.user_ids.present?
614
        user_ids << group.user_ids
615
      end
616
      user_ids.flatten.uniq.compact
617
    }.sort.collect(&:to_s)
618

    
619
    '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
620
  end
621

    
622
  def sql_for_assigned_to_role_field(field, operator, value)
623
    case operator
624
    when "*", "!*" # Member / Not member
625
      sw = operator == "!*" ? 'NOT' : ''
626
      nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
627
      "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
628
        " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
629
    when "=", "!"
630
      role_cond = value.any? ? 
631
        "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
632
        "1=0"
633
      
634
      sw = operator == "!" ? 'NOT' : ''
635
      nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
636
      "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
637
        " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
638
    end
639
  end
640

    
641
  private
642

    
643
  def sql_for_custom_field(field, operator, value, custom_field_id)
644
    db_table = CustomValue.table_name
645
    db_field = 'value'
646
    "#{Issue.table_name}.id IN (SELECT #{Issue.table_name}.id FROM #{Issue.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
647
      sql_for_field(field, operator, value, db_table, db_field, true) + ')'
648
  end
649

    
650
  # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
651
  def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
652
    sql = ''
653
    case operator
654
    when "="
655
      if value.any?
656
        case type_for(field)
657
        when :date, :date_past
658
          sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
659
        when :integer
660
          sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
661
        when :float
662
          sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
663
        else
664
          sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
665
        end
666
      else
667
        # IN an empty set
668
        sql = "1=0"
669
      end
670
    when "!"
671
      if value.any?
672
        sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
673
      else
674
        # NOT IN an empty set
675
        sql = "1=1"
676
      end
677
    when "!*"
678
      sql = "#{db_table}.#{db_field} IS NULL"
679
      sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
680
    when "*"
681
      sql = "#{db_table}.#{db_field} IS NOT NULL"
682
      sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
683
    when ">="
684
      if [:date, :date_past].include?(type_for(field))
685
        sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
686
      else
687
        if is_custom_filter
688
          sql = "CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f}"
689
        else
690
          sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
691
        end
692
      end
693
    when "<="
694
      if [:date, :date_past].include?(type_for(field))
695
        sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
696
      else
697
        if is_custom_filter
698
          sql = "CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f}"
699
        else
700
          sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
701
        end
702
      end
703
    when "><"
704
      if [:date, :date_past].include?(type_for(field))
705
        sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
706
      else
707
        if is_custom_filter
708
          sql = "CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
709
        else
710
          sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
711
        end
712
      end
713
    when "o"
714
      sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_false}" if field == "status_id"
715
    when "c"
716
      sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_true}" if field == "status_id"
717
    when ">t-"
718
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
719
    when "<t-"
720
      sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
721
    when "t-"
722
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
723
    when ">t+"
724
      sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
725
    when "<t+"
726
      sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
727
    when "t+"
728
      sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
729
    when "t"
730
      sql = relative_date_clause(db_table, db_field, 0, 0)
731
    when "w"
732
      first_day_of_week = l(:general_first_day_of_week).to_i
733
      day_of_week = Date.today.cwday
734
      days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
735
      sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
736
    when "~"
737
      sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
738
    when "!~"
739
      sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
740
    else
741
      raise "Unknown query operator #{operator}"
742
    end
743

    
744
    return sql
745
  end
746

    
747
  def add_custom_fields_filters(custom_fields)
748
    @available_filters ||= {}
749

    
750
    custom_fields.select(&:is_filter?).each do |field|
751
      case field.field_format
752
      when "text"
753
        options = { :type => :text, :order => 20 }
754
      when "list"
755
        options = { :type => :list_optional, :values => field.possible_values, :order => 20}
756
      when "date"
757
        options = { :type => :date, :order => 20 }
758
      when "bool"
759
        options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
760
      when "int"
761
        options = { :type => :integer, :order => 20 }
762
      when "float"
763
        options = { :type => :float, :order => 20 }
764
      when "user", "version"
765
        next unless project
766
        options = { :type => :list_optional, :values => field.possible_values_options(project), :order => 20}
767
      else
768
        options = { :type => :string, :order => 20 }
769
      end
770
      @available_filters["cf_#{field.id}"] = options.merge({ :name => field.name })
771
    end
772
  end
773

    
774
  # Returns a SQL clause for a date or datetime field.
775
  def date_clause(table, field, from, to)
776
    s = []
777
    if from
778
      from_yesterday = from - 1
779
      from_yesterday_utc = Time.gm(from_yesterday.year, from_yesterday.month, from_yesterday.day)
780
      s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_utc.end_of_day)])
781
    end
782
    if to
783
      to_utc = Time.gm(to.year, to.month, to.day)
784
      s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_utc.end_of_day)])
785
    end
786
    s.join(' AND ')
787
  end
788

    
789
  # Returns a SQL clause for a date or datetime field using relative dates.
790
  def relative_date_clause(table, field, days_from, days_to)
791
    date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
792
  end
793
end
    (1-1/1)