Class: IssueQuery

Inherits:
Query
  • Object
show all
Defined in:
app/models/issue_query.rb

Overview

Redmine - project management software Copyright © 2006-2023 Jean-Philippe Lang

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Constant Summary

Constants inherited from Query

Query::VISIBILITY_PRIVATE, Query::VISIBILITY_PUBLIC, Query::VISIBILITY_ROLES

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Query

add_available_column, #add_available_filter, #add_filter, #add_filter_error, #add_filters, #add_short_filter, #all_projects, #all_projects_values, #as_params, #assigned_to_values, #author_values, #available_block_columns, #available_display_types, #available_filters, #available_filters_as_json, #available_inline_columns, #available_totalable_columns, #block_columns, build_from_params, #column_names=, #columns, #css_classes, #default_display_type, #delete_available_filter, #display_type, #display_type=, #editable_by?, #fixed_version_values, #group_by_column, #group_by_sort_order, #group_by_statement, #groupable_columns, #grouped?, #has_column?, #has_custom_field_column?, #has_default_columns?, #has_filter?, #inline_columns, #is_global?, #is_private?, #is_public?, #issue_custom_fields, #issue_statuses_values, #label_for, #operator_for, operators_labels, #principals, #project_custom_fields, #project_statement, #project_statuses_values, #project_values, #queried_table_name, #result_count_by_group, #sort_clause, #sort_criteria, #sort_criteria=, #sort_criteria_key, #sort_criteria_order, #sortable_columns, #statement, #subproject_values, #time_entry_custom_fields, #total_by_group_for, #total_for, #totalable_columns, #totalable_names, #totalable_names=, #totals, #totals_by_group, #trackers, #type_for, #users, #validate_query_filters, #value_for, #values_for, visible, #visible?, #watcher_values

Methods included from Redmine::SubclassFactory

included

Constructor Details

#initialize(attributes = nil, *args) ⇒ IssueQuery

Returns a new instance of IssueQuery.



99
100
101
102
# File 'app/models/issue_query.rb', line 99

def initialize(attributes=nil, *args)
  super attributes
  self.filters ||= {'status_id' => {:operator => "o", :values => [""]}}
end

Class Method Details

.default(project: nil, user: User.current) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/models/issue_query.rb', line 80

def self.default(project: nil, user: User.current)
  # user default
  if user&.logged? && (query_id = user.pref.default_issue_query).present?
    query = find_by(id: query_id)
    return query if query&.visible?(user)
  end

  # project default
  query = project&.default_issue_query
  return query if query&.visibility == VISIBILITY_PUBLIC

  # global default
  if (query_id = Setting.default_issue_query).present?
    query = find_by(id: query_id)
    return query if query&.visibility == VISIBILITY_PUBLIC
  end
  nil
end

Instance Method Details

#available_columnsObject



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'app/models/issue_query.rb', line 282

def available_columns
  return @available_columns if @available_columns

  @available_columns = self.class.available_columns.dup
  @available_columns += issue_custom_fields.visible.collect {|cf| QueryCustomFieldColumn.new(cf)}

  if User.current.allowed_to?(:view_time_entries, project, :global => true)
    # insert the columns after total_estimated_hours or at the end
    index = @available_columns.find_index {|column| column.name == :total_estimated_hours}
    index = (index ? index + 1 : -1)

    subselect = "SELECT SUM(hours) FROM #{TimeEntry.table_name}" +
      " JOIN #{Project.table_name} ON #{Project.table_name}.id = #{TimeEntry.table_name}.project_id" +
      " WHERE (#{TimeEntry.visible_condition(User.current)}) AND #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id"

    @available_columns.insert(
      index,
      QueryColumn.new(:spent_hours,
                      :sortable => "COALESCE((#{subselect}), 0)",
                      :default_order => 'desc',
                      :caption => :label_spent_time,
                      :totalable => true)
    )

    subselect = "SELECT SUM(hours) FROM #{TimeEntry.table_name}" +
      " JOIN #{Project.table_name} ON #{Project.table_name}.id = #{TimeEntry.table_name}.project_id" +
      " JOIN #{Issue.table_name} subtasks ON subtasks.id = #{TimeEntry.table_name}.issue_id" +
      " WHERE (#{TimeEntry.visible_condition(User.current)})" +
      " AND subtasks.root_id = #{Issue.table_name}.root_id AND subtasks.lft >= #{Issue.table_name}.lft AND subtasks.rgt <= #{Issue.table_name}.rgt"

    @available_columns.insert(
      index + 1,
      QueryColumn.new(:total_spent_hours,
                      :sortable => "COALESCE((#{subselect}), 0)",
                      :default_order => 'desc',
                      :caption => :label_total_spent_time)
    )
  end

  if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
    User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
    @available_columns <<
      QueryColumn.new(:is_private,
                      :sortable => "#{Issue.table_name}.is_private", :groupable => true)
  end

  disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
  disabled_fields << "total_estimated_hours" if disabled_fields.include?("estimated_hours")
  @available_columns.reject! do |column|
    disabled_fields.include?(column.name.to_s)
  end

  @available_columns
end

#base_scopeObject



353
354
355
# File 'app/models/issue_query.rb', line 353

def base_scope
  Issue.visible.joins(:status, :project).where(statement)
end

#build_from_params(params, defaults = {}) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'app/models/issue_query.rb', line 131

def build_from_params(params, defaults={})
  super
  self.draw_relations =
    params[:draw_relations] ||
      (params[:query] && params[:query][:draw_relations]) || options[:draw_relations]
  self.draw_progress_line =
    params[:draw_progress_line] ||
      (params[:query] && params[:query][:draw_progress_line]) ||
      options[:draw_progress_line]
  self.draw_selected_columns =
    params[:draw_selected_columns] ||
      (params[:query] && params[:query][:draw_selected_columns]) ||
      options[:draw_progress_line]
  self
end

#default_columns_namesObject



337
338
339
340
341
342
343
# File 'app/models/issue_query.rb', line 337

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

    project.present? ? default_columns : [:project] | default_columns
  end
end

#default_sort_criteriaObject



349
350
351
# File 'app/models/issue_query.rb', line 349

def default_sort_criteria
  [['id', 'desc']]
end

#default_totalable_namesObject



345
346
347
# File 'app/models/issue_query.rb', line 345

def default_totalable_names
  Setting.issue_list_default_totals.map(&:to_sym)
end

#draw_progress_lineObject



113
114
115
116
# File 'app/models/issue_query.rb', line 113

def draw_progress_line
  r = options[:draw_progress_line]
  r == '1'
end

#draw_progress_line=(arg) ⇒ Object



118
119
120
# File 'app/models/issue_query.rb', line 118

def draw_progress_line=(arg)
  options[:draw_progress_line] = (arg == '1' ? '1' : nil)
end

#draw_relationsObject



104
105
106
107
# File 'app/models/issue_query.rb', line 104

def draw_relations
  r = options[:draw_relations]
  r.nil? || r == '1'
end

#draw_relations=(arg) ⇒ Object



109
110
111
# File 'app/models/issue_query.rb', line 109

def draw_relations=(arg)
  options[:draw_relations] = (arg == '0' ? '0' : nil)
end

#draw_selected_columnsObject



122
123
124
125
# File 'app/models/issue_query.rb', line 122

def draw_selected_columns
  r = options[:draw_selected_columns]
  r == '1'
end

#draw_selected_columns=(arg) ⇒ Object



127
128
129
# File 'app/models/issue_query.rb', line 127

def draw_selected_columns=(arg)
  options[:draw_selected_columns] = (arg == '1' ? '1' : nil)
end

#find_assigned_to_id_filter_values(values) ⇒ Object Also known as: find_author_id_filter_values



827
828
829
# File 'app/models/issue_query.rb', line 827

def find_assigned_to_id_filter_values(values)
  Principal.visible.where(:id => values).map {|p| [p.name, p.id.to_s]}
end

#initialize_available_filtersObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'app/models/issue_query.rb', line 147

def initialize_available_filters
  add_available_filter(
    "status_id",
    :type => :list_status, :values => lambda {issue_statuses_values}
  )
  add_available_filter(
    "project_id",
    :type => :list, :values => lambda {project_values}
  ) if project.nil?
  add_available_filter(
    "tracker_id",
    :type => :list_with_history, :values => trackers.collect{|s| [s.name, s.id.to_s]}
  )
  add_available_filter(
    "priority_id",
    :type => :list_with_history, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s]}
  )
  add_available_filter(
    "author_id",
    :type => :list, :values => lambda {author_values}
  )
  add_available_filter(
    "assigned_to_id",
    :type => :list_optional_with_history, :values => lambda {assigned_to_values}
  )
  add_available_filter(
    "member_of_group",
    :type => :list_optional, :values => lambda {Group.givable.visible.collect {|g| [g.name, g.id.to_s]}}
  )
  add_available_filter(
    "assigned_to_role",
    :type => :list_optional, :values => lambda {Role.givable.collect {|r| [r.name, r.id.to_s]}}
  )
  add_available_filter(
    "fixed_version_id",
    :type => :list_optional_with_history, :values => lambda {fixed_version_values}
  )
  add_available_filter(
    "fixed_version.due_date",
    :type => :date,
    :name => l(:label_attribute_of_fixed_version, :name => l(:field_effective_date))
  )
  add_available_filter(
    "fixed_version.status",
    :type => :list,
    :name => l(:label_attribute_of_fixed_version, :name => l(:field_status)),
    :values => Version::VERSION_STATUSES.map{|s| [l("version_status_#{s}"), s]}
  )
  add_available_filter(
    "category_id",
    :type => :list_optional_with_history,
    :values => lambda {project.issue_categories.collect{|s| [s.name, s.id.to_s]}}
  ) if project
  add_available_filter "subject", :type => :text
  add_available_filter "description", :type => :text
  add_available_filter "notes", :type => :text
  add_available_filter "created_on", :type => :date_past
  add_available_filter "updated_on", :type => :date_past
  add_available_filter "closed_on", :type => :date_past
  add_available_filter "start_date", :type => :date
  add_available_filter "due_date", :type => :date
  add_available_filter "estimated_hours", :type => :float

  if User.current.allowed_to?(:view_time_entries, project, :global => true)
    add_available_filter "spent_time", :type => :float, :label => :label_spent_time
  end

  add_available_filter "done_ratio", :type => :integer

  if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
    User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
    add_available_filter(
      "is_private",
      :type => :list,
      :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
    )
  end
  add_available_filter(
    "attachment",
    :type => :text, :name => l(:label_attachment)
  )
  add_available_filter(
    "attachment_description",
    :type => :text, :name => l(:label_attachment_description)
  )
  if User.current.logged?
    add_available_filter(
      "watcher_id",
      :type => :list, :values => lambda {watcher_values}
    )
  end
  add_available_filter(
    "updated_by",
    :type => :list, :values => lambda {author_values}
  )
  add_available_filter(
    "last_updated_by",
    :type => :list, :values => lambda {author_values}
  )
  if project && !project.leaf?
    add_available_filter(
      "subproject_id",
      :type => :list_subprojects,
      :values => lambda {subproject_values}
    )
  end

  add_available_filter(
    "project.status",
    :type => :list,
    :name => l(:label_attribute_of_project, :name => l(:field_status)),
    :values => lambda {project_statuses_values}
  ) if project.nil? || !project.leaf?

  add_custom_fields_filters(issue_custom_fields)
  add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version

  IssueRelation::TYPES.each do |relation_type, options|
    add_available_filter(
      relation_type, :type => :relation, :label => options[:name],
      :values => lambda {all_projects_values}
    )
  end
  add_available_filter "parent_id", :type => :tree, :label => :field_parent_issue
  add_available_filter "child_id", :type => :tree, :label => :label_subtask_plural

  add_available_filter "issue_id", :type => :integer, :label => :label_issue

  add_available_filter "any_searchable", :type => :search

  Tracker.disabled_core_fields(trackers).each do |field|
    delete_available_filter field
  end
end

#issue_countObject

Returns the issue count



358
359
360
361
362
# File 'app/models/issue_query.rb', line 358

def issue_count
  base_scope.count
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#issue_ids(options = {}) ⇒ Object

Returns the issues ids



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'app/models/issue_query.rb', line 428

def issue_ids(options={})
  order_option = [group_by_sort_order, (options[:order] || sort_clause)].flatten.reject(&:blank?)
  # The default order of IssueQuery is issues.id DESC(by IssueQuery#default_sort_criteria)
  unless ["#{Issue.table_name}.id ASC", "#{Issue.table_name}.id DESC"].any?{|i| order_option.include?(i)}
    order_option << "#{Issue.table_name}.id DESC"
  end

  base_scope.
    includes(([:status, :project] + (options[:include] || [])).uniq).
    references(([:status, :project] + (options[:include] || [])).uniq).
    where(options[:conditions]).
    order(order_option).
    joins(joins_for_order_statement(order_option.join(','))).
    limit(options[:limit]).
    offset(options[:offset]).
    pluck(:id)
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#issues(options = {}) ⇒ Object

Returns the issues Valid options are :order, :offset, :limit, :include, :conditions



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'app/models/issue_query.rb', line 380

def issues(options={})
  order_option = [group_by_sort_order, (options[:order] || sort_clause)].flatten.reject(&:blank?)
  # The default order of IssueQuery is issues.id DESC(by IssueQuery#default_sort_criteria)
  unless ["#{Issue.table_name}.id ASC", "#{Issue.table_name}.id DESC"].any?{|i| order_option.include?(i)}
    order_option << "#{Issue.table_name}.id DESC"
  end

  scope = base_scope.
    preload(:priority).
    includes(([:status, :project] + (options[:include] || [])).uniq).
    where(options[:conditions]).
    order(order_option).
    joins(joins_for_order_statement(order_option.join(','))).
    limit(options[:limit]).
    offset(options[:offset])

  scope =
    scope.preload(
      [:tracker, :author, :assigned_to, :fixed_version,
       :category, :attachments] & columns.map(&:name)
    )
  if has_custom_field_column?
    scope = scope.preload(:custom_values)
  end

  issues = scope.to_a

  if has_column?(:spent_hours)
    Issue.load_visible_spent_hours(issues)
  end
  if has_column?(:total_spent_hours)
    Issue.load_visible_total_spent_hours(issues)
  end
  if has_column?(:last_updated_by)
    Issue.load_visible_last_updated_by(issues)
  end
  if has_column?(:relations)
    Issue.load_visible_relations(issues)
  end
  if has_column?(:last_notes)
    Issue.load_visible_last_notes(issues)
  end
  issues
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#joins_for_order_statement(order_options) ⇒ Object



836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'app/models/issue_query.rb', line 836

def joins_for_order_statement(order_options)
  joins = [super]

  if order_options
    if order_options.include?('authors')
      joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{queried_table_name}.author_id"
    end
    if order_options.include?('users')
      joins << "LEFT OUTER JOIN #{User.table_name} ON #{User.table_name}.id = #{queried_table_name}.assigned_to_id"
    end
    if order_options.include?('last_journal_user')
      joins <<
         "LEFT OUTER JOIN #{Journal.table_name}" \
           " ON #{Journal.table_name}.id = (SELECT MAX(#{Journal.table_name}.id)" \
           " FROM #{Journal.table_name}" \
           " WHERE #{Journal.table_name}.journalized_type = 'Issue'" \
           " AND #{Journal.table_name}.journalized_id = #{Issue.table_name}.id " \
           " AND #{Journal.visible_notes_condition(User.current, :skip_pre_condition => true)})" \
           " LEFT OUTER JOIN #{User.table_name} last_journal_user" \
           " ON last_journal_user.id = #{Journal.table_name}.user_id"
    end
    if order_options.include?('versions')
      joins <<
         "LEFT OUTER JOIN #{Version.table_name}" \
           " ON #{Version.table_name}.id = #{queried_table_name}.fixed_version_id"
    end
    if order_options.include?('issue_categories')
      joins <<
         "LEFT OUTER JOIN #{IssueCategory.table_name}" \
           " ON #{IssueCategory.table_name}.id = #{queried_table_name}.category_id"
    end
    if order_options.include?('trackers')
      joins <<
        "LEFT OUTER JOIN #{Tracker.table_name}" \
          " ON #{Tracker.table_name}.id = #{queried_table_name}.tracker_id"
    end
    if order_options.include?('enumerations')
      joins <<
        "LEFT OUTER JOIN #{IssuePriority.table_name}" \
          " ON #{IssuePriority.table_name}.id = #{queried_table_name}.priority_id"
    end
  end

  joins.any? ? joins.join(' ') : nil
end

#journals(options = {}) ⇒ Object

Returns the journals Valid options are :order, :offset, :limit



450
451
452
453
454
455
456
457
458
459
460
461
# File 'app/models/issue_query.rb', line 450

def journals(options={})
  Journal.visible.
    joins(:issue => [:project, :status]).
    where(statement).
    order(options[:order]).
    limit(options[:limit]).
    offset(options[:offset]).
    preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
    to_a
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#sql_for_any_searchable_field(field, operator, value) ⇒ Object



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# File 'app/models/issue_query.rb', line 783

def sql_for_any_searchable_field(field, operator, value)
  question = value.first

  # Fetch search results only from the selected and visible (sub-)projects
  project_scope = Project.allowed_to(:view_issues)
  if project
    projects = project_scope.where(project_statement)
  elsif has_filter?('project_id')
    case values_for('project_id').first
    when 'mine'
      project_ids = User.current.projects.ids
    when 'bookmarks'
      project_ids = User.current.bookmarked_project_ids
    else
      project_ids = values_for('project_id')
    end
    projects = project_scope.where(
      sql_for_field('project_id', operator_for('project_id'), project_ids, Project.table_name, 'id')
    )
  else
    projects = nil
  end

  is_all_words =
    case operator
    when '~'        then true
    when '*~', '!~' then false
    end

  is_open_issues = has_filter?('status_id') && operator_for('status_id') == 'o'

  fetcher = Redmine::Search::Fetcher.new(
    question, User.current, ['issue'], projects,
    all_words: is_all_words, open_issues: is_open_issues, attachments: '0'
  )
  ids = fetcher.result_ids.map(&:last)
  if ids.present?
    sw = operator == '!~' ? 'NOT' : ''
    "#{Issue.table_name}.id #{sw} IN (#{ids.join(',')})"
  else
    operator == '!~' ? '1=1' : '1=0'
  end
end

#sql_for_assigned_to_role_field(field, operator, value) ⇒ Object



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'app/models/issue_query.rb', line 564

def sql_for_assigned_to_role_field(field, operator, value)
  case operator
  when "*", "!*" # Member / Not member
    sw = operator == "!*" ? 'NOT' : ''
    nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
    "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
      " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
  when "=", "!"
    role_cond =
      if value.any?
        "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{self.class.connection.quote_string(val)}'"}.join(",") + ")"
      else
        "1=0"
      end
    sw = operator == "!" ? 'NOT' : ''
    nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
    "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
      " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
  end
end

#sql_for_attachment_description_field(field, operator, value) ⇒ Object



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'app/models/issue_query.rb', line 627

def sql_for_attachment_description_field(field, operator, value)
  cond_description = "a.description IS NOT NULL AND a.description <> ''"
  c =
    case operator
    when '*', '!*'
      (operator == '*' ? cond_description : "NOT (#{cond_description})")
    when '~', '!~', '*~'
      (operator == '~' ? '' : "#{cond_description} AND ") +
      sql_contains('a.description', value.first, :match => (operator != '!~'), :all_words => (operator != '*~'))
    when '^', '$'
      sql_contains('a.description', value.first, (operator == '^' ? :starts_with : :ends_with) => true)
    else
      '1=0'
    end
  "EXISTS (SELECT 1 FROM #{Attachment.table_name} a WHERE a.container_type = 'Issue' AND a.container_id = #{Issue.table_name}.id AND (#{c}))"
end

#sql_for_attachment_field(field, operator, value) ⇒ Object



612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'app/models/issue_query.rb', line 612

def sql_for_attachment_field(field, operator, value)
  case operator
  when "*", "!*"
    e = (operator == "*" ? "EXISTS" : "NOT EXISTS")
    "#{e} (SELECT 1 FROM #{Attachment.table_name} a WHERE a.container_type = 'Issue' AND a.container_id = #{Issue.table_name}.id)"
  when "~", "!~", "*~"
    c = sql_contains("a.filename", value.first, :all_words => (operator != "*~"))
    e = (operator == "!~" ? "NOT EXISTS" : "EXISTS")
    "#{e} (SELECT 1 FROM #{Attachment.table_name} a WHERE a.container_type = 'Issue' AND a.container_id = #{Issue.table_name}.id AND (#{c}))"
  when "^", "$"
    c = sql_contains("a.filename", value.first, (operator == "^" ? :starts_with : :ends_with) => true)
    "EXISTS (SELECT 1 FROM #{Attachment.table_name} a WHERE a.container_type = 'Issue' AND a.container_id = #{Issue.table_name}.id AND (#{c}))"
  end
end

#sql_for_child_id_field(field, operator, value) ⇒ Object



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'app/models/issue_query.rb', line 668

def sql_for_child_id_field(field, operator, value)
  case operator
  when "="
    # accepts a comma separated list of child ids
    child_ids = value.first.to_s.scan(/\d+/).map(&:to_i).uniq
    ids = Issue.where(:id => child_ids).pluck(:parent_id).compact.uniq
    if ids.present?
      "#{Issue.table_name}.id IN (#{ids.join(",")})"
    else
      "1=0"
    end
  when "~"
    root_id, lft, rgt = Issue.where(:id => value.first.to_i).pick(:root_id, :lft, :rgt)
    if root_id && lft && rgt
      "#{Issue.table_name}.root_id = #{root_id} AND #{Issue.table_name}.lft < #{lft} AND #{Issue.table_name}.rgt > #{rgt}"
    else
      "1=0"
    end
  when "!*"
    "#{Issue.table_name}.rgt - #{Issue.table_name}.lft = 1"
  when "*"
    "#{Issue.table_name}.rgt - #{Issue.table_name}.lft > 1"
  end
end

#sql_for_fixed_version_due_date_field(field, operator, value) ⇒ Object



594
595
596
597
598
599
600
601
# File 'app/models/issue_query.rb', line 594

def sql_for_fixed_version_due_date_field(field, operator, value)
  where = sql_for_field(field, operator, value, Version.table_name, "effective_date")
  version_id_scope = project ? project.shared_versions : Version.visible
  version_ids = version_id_scope.where(where).pluck(:id)

  nl = operator == "!*" ? "#{Issue.table_name}.fixed_version_id IS NULL OR" : ''
  "(#{nl} #{sql_for_field("fixed_version_id", "=", version_ids, Issue.table_name, "fixed_version_id")})"
end

#sql_for_fixed_version_status_field(field, operator, value) ⇒ Object



585
586
587
588
589
590
591
592
# File 'app/models/issue_query.rb', line 585

def sql_for_fixed_version_status_field(field, operator, value)
  where = sql_for_field(field, operator, value, Version.table_name, "status")
  version_id_scope = project ? project.shared_versions : Version.visible
  version_ids = version_id_scope.where(where).pluck(:id)

  nl = operator == "!" ? "#{Issue.table_name}.fixed_version_id IS NULL OR" : ''
  "(#{nl} #{sql_for_field("fixed_version_id", "=", version_ids, Issue.table_name, "fixed_version_id")})"
end

#sql_for_is_private_field(field, operator, value) ⇒ Object



603
604
605
606
607
608
609
610
# File 'app/models/issue_query.rb', line 603

def sql_for_is_private_field(field, operator, value)
  op = (operator == "=" ? 'IN' : 'NOT IN')
  va =
    value.map do |v|
      v == '0' ? self.class.connection.quoted_false : self.class.connection.quoted_true
    end.uniq.join(',')
  "#{Issue.table_name}.is_private #{op} (#{va})"
end

#sql_for_issue_id_field(field, operator, value) ⇒ Object



704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'app/models/issue_query.rb', line 704

def sql_for_issue_id_field(field, operator, value)
  if operator == "="
    # accepts a comma separated list of ids
    ids = value.first.to_s.scan(/\d+/).map(&:to_i)
    if ids.present?
      "#{Issue.table_name}.id IN (#{ids.join(",")})"
    else
      "1=0"
    end
  else
    sql_for_field("id", operator, value, Issue.table_name, "id")
  end
end

#sql_for_last_updated_by_field(field, operator, value) ⇒ Object



494
495
496
497
498
499
500
501
502
503
# File 'app/models/issue_query.rb', line 494

def sql_for_last_updated_by_field(field, operator, value)
  neg = (operator == '!' ? 'NOT' : '')
  subquery = "SELECT 1 FROM #{Journal.table_name} sj" +
    " WHERE sj.journalized_type='Issue' AND sj.journalized_id=#{Issue.table_name}.id AND (#{sql_for_field field, '=', value, 'sj', 'user_id'})" +
    " AND sj.id IN (SELECT MAX(#{Journal.table_name}.id) FROM #{Journal.table_name}" +
    "   WHERE #{Journal.table_name}.journalized_type='Issue' AND #{Journal.table_name}.journalized_id=#{Issue.table_name}.id" +
    "   AND (#{Journal.visible_notes_condition(User.current, :skip_pre_condition => true)}))"

  "#{neg} EXISTS (#{subquery})"
end

#sql_for_member_of_group_field(field, operator, value) ⇒ Object



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'app/models/issue_query.rb', line 545

def sql_for_member_of_group_field(field, operator, value)
  if operator == '*' # Any group
    groups = Group.givable
    operator = '=' # Override the operator since we want to find by assigned_to
  elsif operator == "!*"
    groups = Group.givable
    operator = '!' # Override the operator since we want to find by assigned_to
  else
    groups = Group.where(:id => value).to_a
  end
  groups ||= []

  members_of_groups = groups.inject([]) do |user_ids, group|
    user_ids + group.user_ids + [group.id]
  end.uniq.compact.sort.collect(&:to_s)

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

#sql_for_notes_field(field, operator, value) ⇒ Object



476
477
478
479
480
481
482
# File 'app/models/issue_query.rb', line 476

def sql_for_notes_field(field, operator, value)
  subquery = "SELECT 1 FROM #{Journal.table_name}" +
    " WHERE #{Journal.table_name}.journalized_type='Issue' AND #{Journal.table_name}.journalized_id=#{Issue.table_name}.id" +
    " AND (#{sql_for_field field, operator.sub(/^!/, ''), value, Journal.table_name, 'notes'})" +
    " AND (#{Journal.visible_notes_condition(User.current, :skip_pre_condition => true)})"
  "#{/^!/.match?(operator) ? "NOT EXISTS" : "EXISTS"} (#{subquery})"
end

#sql_for_parent_id_field(field, operator, value) ⇒ Object



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'app/models/issue_query.rb', line 644

def sql_for_parent_id_field(field, operator, value)
  case operator
  when "="
    # accepts a comma separated list of ids
    ids = value.first.to_s.scan(/\d+/).map(&:to_i).uniq
    if ids.present?
      "#{Issue.table_name}.parent_id IN (#{ids.join(",")})"
    else
      "1=0"
    end
  when "~"
    root_id, lft, rgt = Issue.where(:id => value.first.to_i).pick(:root_id, :lft, :rgt)
    if root_id && lft && rgt
      "#{Issue.table_name}.root_id = #{root_id} AND #{Issue.table_name}.lft > #{lft} AND #{Issue.table_name}.rgt < #{rgt}"
    else
      "1=0"
    end
  when "!*"
    "#{Issue.table_name}.parent_id IS NULL"
  when "*"
    "#{Issue.table_name}.parent_id IS NOT NULL"
  end
end

#sql_for_project_status_field(field, operator, value, options = {}) ⇒ Object



779
780
781
# File 'app/models/issue_query.rb', line 779

def sql_for_project_status_field(field, operator, value, options={})
  sql_for_field(field, operator, value, Project.table_name, "status")
end

#sql_for_relations(field, operator, value, options = {}) ⇒ Object



718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'app/models/issue_query.rb', line 718

def sql_for_relations(field, operator, value, options={})
  relation_options = IssueRelation::TYPES[field]
  return relation_options unless relation_options

  relation_type = field
  join_column, target_join_column = "issue_from_id", "issue_to_id"
  if relation_options[:reverse] || options[:reverse]
    relation_type = relation_options[:reverse] || relation_type
    join_column, target_join_column = target_join_column, join_column
  end
  sql =
    case operator
    when "*", "!*"
      op = (operator == "*" ? 'IN' : 'NOT IN')
      "#{Issue.table_name}.id #{op}" \
       " (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column}" \
         " FROM #{IssueRelation.table_name}" \
           " WHERE #{IssueRelation.table_name}.relation_type =" \
                " '#{self.class.connection.quote_string(relation_type)}')"
    when "=", "!"
      ids = value.first.to_s.scan(/\d+/).map(&:to_i).uniq
      if ids.present?
        op = (operator == "=" ? 'IN' : 'NOT IN')
        "#{Issue.table_name}.id #{op}" \
         " (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column}" \
           " FROM #{IssueRelation.table_name}" \
             " WHERE #{IssueRelation.table_name}.relation_type =" \
                  " '#{self.class.connection.quote_string(relation_type)}'" \
               " AND #{IssueRelation.table_name}.#{target_join_column} IN (#{ids.join(",")}))"
      else
        "1=0"
      end
    when "=p", "=!p", "!p"
      op = (operator == "!p" ? 'NOT IN' : 'IN')
      comp = (operator == "=!p" ? '<>' : '=')
      "#{Issue.table_name}.id #{op}" \
       " (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column}" \
         " FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues" \
           " WHERE #{IssueRelation.table_name}.relation_type =" \
                " '#{self.class.connection.quote_string(relation_type)}'" \
           " AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id" \
           " AND relissues.project_id #{comp} #{value.first.to_i})"
    when "*o", "!o"
      op = (operator == "!o" ? 'NOT IN' : 'IN')
      "#{Issue.table_name}.id #{op}" \
        " (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column}" \
         " FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues" \
           " WHERE #{IssueRelation.table_name}.relation_type =" \
                " '#{self.class.connection.quote_string(relation_type)}'" \
           " AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id" \
           " AND relissues.status_id IN" \
             " (SELECT id FROM #{IssueStatus.table_name}" \
             "  WHERE is_closed = #{self.class.connection.quoted_false}))"
    end
  if relation_options[:sym] == field && !options[:reverse]
    sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
    sql = sqls.join(["!", "!*", "!p", '!o'].include?(operator) ? " AND " : " OR ")
  end
  "(#{sql})"
end

#sql_for_spent_time_field(field, operator, value) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'app/models/issue_query.rb', line 505

def sql_for_spent_time_field(field, operator, value)
  first, second = value.first.to_f, value.second.to_f
  sql_op =
    case operator
    when "=", ">=", "<=" then  "#{operator} #{first}"
    when "><"            then  "BETWEEN #{first} AND #{second}"
    when "*"             then  "> 0"
    when "!*"            then  "= 0"
    else
      return nil
    end
  "COALESCE((" +
    "SELECT ROUND(CAST(SUM(hours) AS DECIMAL(30,3)), 2) " +
    "FROM #{TimeEntry.table_name} " +
    "WHERE issue_id = #{Issue.table_name}.id), 0) #{sql_op}"
end

#sql_for_updated_by_field(field, operator, value) ⇒ Object



484
485
486
487
488
489
490
491
492
# File 'app/models/issue_query.rb', line 484

def sql_for_updated_by_field(field, operator, value)
  neg = (operator == '!' ? 'NOT' : '')
  subquery = "SELECT 1 FROM #{Journal.table_name}" +
    " WHERE #{Journal.table_name}.journalized_type='Issue' AND #{Journal.table_name}.journalized_id=#{Issue.table_name}.id" +
    " AND (#{sql_for_field field, '=', value, Journal.table_name, 'user_id'})" +
    " AND (#{Journal.visible_notes_condition(User.current, :skip_pre_condition => true)})"

  "#{neg} EXISTS (#{subquery})"
end

#sql_for_updated_on_field(field, operator, value) ⇒ Object



693
694
695
696
697
698
699
700
701
702
# File 'app/models/issue_query.rb', line 693

def sql_for_updated_on_field(field, operator, value)
  case operator
  when "!*"
    "#{Issue.table_name}.updated_on = #{Issue.table_name}.created_on"
  when "*"
    "#{Issue.table_name}.updated_on > #{Issue.table_name}.created_on"
  else
    sql_for_field("updated_on", operator, value, Issue.table_name, "updated_on")
  end
end

#sql_for_watcher_id_field(field, operator, value) ⇒ Object



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
# File 'app/models/issue_query.rb', line 522

def sql_for_watcher_id_field(field, operator, value)
  db_table = Watcher.table_name
  me, others = value.partition {|id| ['0', User.current.id.to_s].include?(id)}
  sql =
    if others.any?
      "SELECT #{Issue.table_name}.id FROM #{Issue.table_name} " +
      "INNER JOIN #{db_table} ON #{Issue.table_name}.id = #{db_table}.watchable_id AND #{db_table}.watchable_type = 'Issue' " +
      "LEFT OUTER JOIN #{Project.table_name} ON #{Project.table_name}.id = #{Issue.table_name}.project_id " +
      "WHERE (" +
        sql_for_field(field, '=', me, db_table, 'user_id') +
      ') OR (' +
        Project.allowed_to_condition(User.current, :view_issue_watchers) +
        ' AND ' +
        sql_for_field(field, '=', others, db_table, 'user_id') +
      ')'
    else
      "SELECT #{db_table}.watchable_id FROM #{db_table} " +
      "WHERE #{db_table}.watchable_type='Issue' AND " +
      sql_for_field(field, '=', me, db_table, 'user_id')
    end
  "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (#{sql})"
end

#total_for_estimated_hours(scope) ⇒ Object

Returns sum of all the issue’s estimated_hours



365
366
367
# File 'app/models/issue_query.rb', line 365

def total_for_estimated_hours(scope)
  map_total(scope.sum(:estimated_hours)) {|t| t.to_f.round(2)}
end

#total_for_spent_hours(scope) ⇒ Object

Returns sum of all the issue’s time entries hours



370
371
372
373
374
375
376
# File 'app/models/issue_query.rb', line 370

def total_for_spent_hours(scope)
  total = scope.joins(:time_entries).
    where(TimeEntry.visible_condition(User.current)).
    sum("#{TimeEntry.table_name}.hours")

  map_total(total) {|t| t.to_f.round(2)}
end

#versions(options = {}) ⇒ Object

Returns the versions Valid options are :conditions



465
466
467
468
469
470
471
472
473
474
# File 'app/models/issue_query.rb', line 465

def versions(options={})
  Version.visible.
    where(project_statement).
    where(options[:conditions]).
    includes(:project).
    references(:project).
    to_a
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end