##// END OF EJS Templates
remove unneeded Relation#all from IssueQuery model...
Toshi MARUYAMA -
r12449:9c7568c1a1d4
parent child
Show More
@@ -1,483 +1,483
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class IssueQuery < Query
19 19
20 20 self.queried_class = Issue
21 21
22 22 self.available_columns = [
23 23 QueryColumn.new(:id, :sortable => "#{Issue.table_name}.id", :default_order => 'desc', :caption => '#', :frozen => true),
24 24 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
25 25 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
26 26 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
27 27 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
28 28 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
29 29 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
30 30 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
31 31 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
32 32 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
33 33 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
34 34 QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
35 35 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
36 36 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
37 37 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
38 38 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
39 39 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
40 40 QueryColumn.new(:closed_on, :sortable => "#{Issue.table_name}.closed_on", :default_order => 'desc'),
41 41 QueryColumn.new(:relations, :caption => :label_related_issues),
42 42 QueryColumn.new(:description, :inline => false)
43 43 ]
44 44
45 45 scope :visible, lambda {|*args|
46 46 user = args.shift || User.current
47 47 base = Project.allowed_to_condition(user, :view_issues, *args)
48 48 scope = includes(:project).where("#{table_name}.project_id IS NULL OR (#{base})")
49 49
50 50 if user.admin?
51 51 scope.where("#{table_name}.visibility <> ? OR #{table_name}.user_id = ?", VISIBILITY_PRIVATE, user.id)
52 52 elsif user.memberships.any?
53 53 scope.where("#{table_name}.visibility = ?" +
54 54 " OR (#{table_name}.visibility = ? AND #{table_name}.id IN (" +
55 55 "SELECT DISTINCT q.id FROM #{table_name} q" +
56 56 " INNER JOIN #{table_name_prefix}queries_roles#{table_name_suffix} qr on qr.query_id = q.id" +
57 57 " INNER JOIN #{MemberRole.table_name} mr ON mr.role_id = qr.role_id" +
58 58 " INNER JOIN #{Member.table_name} m ON m.id = mr.member_id AND m.user_id = ?" +
59 59 " WHERE q.project_id IS NULL OR q.project_id = m.project_id))" +
60 60 " OR #{table_name}.user_id = ?",
61 61 VISIBILITY_PUBLIC, VISIBILITY_ROLES, user.id, user.id)
62 62 elsif user.logged?
63 63 scope.where("#{table_name}.visibility = ? OR #{table_name}.user_id = ?", VISIBILITY_PUBLIC, user.id)
64 64 else
65 65 scope.where("#{table_name}.visibility = ?", VISIBILITY_PUBLIC)
66 66 end
67 67 }
68 68
69 69 def initialize(attributes=nil, *args)
70 70 super attributes
71 71 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
72 72 end
73 73
74 74 # Returns true if the query is visible to +user+ or the current user.
75 75 def visible?(user=User.current)
76 76 return true if user.admin?
77 77 return false unless project.nil? || user.allowed_to?(:view_issues, project)
78 78 case visibility
79 79 when VISIBILITY_PUBLIC
80 80 true
81 81 when VISIBILITY_ROLES
82 82 if project
83 83 (user.roles_for_project(project) & roles).any?
84 84 else
85 85 Member.where(:user_id => user.id).joins(:roles).where(:member_roles => {:role_id => roles.map(&:id)}).any?
86 86 end
87 87 else
88 88 user == self.user
89 89 end
90 90 end
91 91
92 92 def is_private?
93 93 visibility == VISIBILITY_PRIVATE
94 94 end
95 95
96 96 def is_public?
97 97 !is_private?
98 98 end
99 99
100 100 def draw_relations
101 101 r = options[:draw_relations]
102 102 r.nil? || r == '1'
103 103 end
104 104
105 105 def draw_relations=(arg)
106 106 options[:draw_relations] = (arg == '0' ? '0' : nil)
107 107 end
108 108
109 109 def draw_progress_line
110 110 r = options[:draw_progress_line]
111 111 r == '1'
112 112 end
113 113
114 114 def draw_progress_line=(arg)
115 115 options[:draw_progress_line] = (arg == '1' ? '1' : nil)
116 116 end
117 117
118 118 def build_from_params(params)
119 119 super
120 120 self.draw_relations = params[:draw_relations] || (params[:query] && params[:query][:draw_relations])
121 121 self.draw_progress_line = params[:draw_progress_line] || (params[:query] && params[:query][:draw_progress_line])
122 122 self
123 123 end
124 124
125 125 def initialize_available_filters
126 126 principals = []
127 127 subprojects = []
128 128 versions = []
129 129 categories = []
130 130 issue_custom_fields = []
131 131
132 132 if project
133 133 principals += project.principals.sort
134 134 unless project.leaf?
135 135 subprojects = project.descendants.visible.all
136 136 principals += Principal.member_of(subprojects)
137 137 end
138 138 versions = project.shared_versions.all
139 139 categories = project.issue_categories.all
140 140 issue_custom_fields = project.all_issue_custom_fields
141 141 else
142 142 if all_projects.any?
143 143 principals += Principal.member_of(all_projects)
144 144 end
145 145 versions = Version.visible.where(:sharing => 'system').all
146 146 issue_custom_fields = IssueCustomField.where(:is_for_all => true)
147 147 end
148 148 principals.uniq!
149 149 principals.sort!
150 150 users = principals.select {|p| p.is_a?(User)}
151 151
152 152 add_available_filter "status_id",
153 :type => :list_status, :values => IssueStatus.sorted.all.collect{|s| [s.name, s.id.to_s] }
153 :type => :list_status, :values => IssueStatus.sorted.collect{|s| [s.name, s.id.to_s] }
154 154
155 155 if project.nil?
156 156 project_values = []
157 157 if User.current.logged? && User.current.memberships.any?
158 158 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
159 159 end
160 160 project_values += all_projects_values
161 161 add_available_filter("project_id",
162 162 :type => :list, :values => project_values
163 163 ) unless project_values.empty?
164 164 end
165 165
166 166 add_available_filter "tracker_id",
167 167 :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] }
168 168 add_available_filter "priority_id",
169 169 :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
170 170
171 171 author_values = []
172 172 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
173 173 author_values += users.collect{|s| [s.name, s.id.to_s] }
174 174 add_available_filter("author_id",
175 175 :type => :list, :values => author_values
176 176 ) unless author_values.empty?
177 177
178 178 assigned_to_values = []
179 179 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
180 180 assigned_to_values += (Setting.issue_group_assignment? ?
181 181 principals : users).collect{|s| [s.name, s.id.to_s] }
182 182 add_available_filter("assigned_to_id",
183 183 :type => :list_optional, :values => assigned_to_values
184 184 ) unless assigned_to_values.empty?
185 185
186 186 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
187 187 add_available_filter("member_of_group",
188 188 :type => :list_optional, :values => group_values
189 189 ) unless group_values.empty?
190 190
191 191 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
192 192 add_available_filter("assigned_to_role",
193 193 :type => :list_optional, :values => role_values
194 194 ) unless role_values.empty?
195 195
196 196 if versions.any?
197 197 add_available_filter "fixed_version_id",
198 198 :type => :list_optional,
199 199 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
200 200 end
201 201
202 202 if categories.any?
203 203 add_available_filter "category_id",
204 204 :type => :list_optional,
205 205 :values => categories.collect{|s| [s.name, s.id.to_s] }
206 206 end
207 207
208 208 add_available_filter "subject", :type => :text
209 209 add_available_filter "created_on", :type => :date_past
210 210 add_available_filter "updated_on", :type => :date_past
211 211 add_available_filter "closed_on", :type => :date_past
212 212 add_available_filter "start_date", :type => :date
213 213 add_available_filter "due_date", :type => :date
214 214 add_available_filter "estimated_hours", :type => :float
215 215 add_available_filter "done_ratio", :type => :integer
216 216
217 217 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
218 218 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
219 219 add_available_filter "is_private",
220 220 :type => :list,
221 221 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
222 222 end
223 223
224 224 if User.current.logged?
225 225 add_available_filter "watcher_id",
226 226 :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]]
227 227 end
228 228
229 229 if subprojects.any?
230 230 add_available_filter "subproject_id",
231 231 :type => :list_subprojects,
232 232 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
233 233 end
234 234
235 235 add_custom_fields_filters(issue_custom_fields)
236 236
237 237 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
238 238
239 239 IssueRelation::TYPES.each do |relation_type, options|
240 240 add_available_filter relation_type, :type => :relation, :label => options[:name]
241 241 end
242 242
243 243 Tracker.disabled_core_fields(trackers).each {|field|
244 244 delete_available_filter field
245 245 }
246 246 end
247 247
248 248 def available_columns
249 249 return @available_columns if @available_columns
250 250 @available_columns = self.class.available_columns.dup
251 251 @available_columns += (project ?
252 252 project.all_issue_custom_fields :
253 253 IssueCustomField
254 254 ).visible.collect {|cf| QueryCustomFieldColumn.new(cf) }
255 255
256 256 if User.current.allowed_to?(:view_time_entries, project, :global => true)
257 257 index = nil
258 258 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
259 259 index = (index ? index + 1 : -1)
260 260 # insert the column after estimated_hours or at the end
261 261 @available_columns.insert index, QueryColumn.new(:spent_hours,
262 262 :sortable => "COALESCE((SELECT SUM(hours) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)",
263 263 :default_order => 'desc',
264 264 :caption => :label_spent_time
265 265 )
266 266 end
267 267
268 268 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
269 269 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
270 270 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
271 271 end
272 272
273 273 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
274 274 @available_columns.reject! {|column|
275 275 disabled_fields.include?(column.name.to_s)
276 276 }
277 277
278 278 @available_columns
279 279 end
280 280
281 281 def default_columns_names
282 282 @default_columns_names ||= begin
283 283 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
284 284
285 285 project.present? ? default_columns : [:project] | default_columns
286 286 end
287 287 end
288 288
289 289 # Returns the issue count
290 290 def issue_count
291 291 Issue.visible.joins(:status, :project).where(statement).count
292 292 rescue ::ActiveRecord::StatementInvalid => e
293 293 raise StatementInvalid.new(e.message)
294 294 end
295 295
296 296 # Returns the issue count by group or nil if query is not grouped
297 297 def issue_count_by_group
298 298 r = nil
299 299 if grouped?
300 300 begin
301 301 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
302 302 r = Issue.visible.
303 303 joins(:status, :project).
304 304 where(statement).
305 305 joins(joins_for_order_statement(group_by_statement)).
306 306 group(group_by_statement).
307 307 count
308 308 rescue ActiveRecord::RecordNotFound
309 309 r = {nil => issue_count}
310 310 end
311 311 c = group_by_column
312 312 if c.is_a?(QueryCustomFieldColumn)
313 313 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
314 314 end
315 315 end
316 316 r
317 317 rescue ::ActiveRecord::StatementInvalid => e
318 318 raise StatementInvalid.new(e.message)
319 319 end
320 320
321 321 # Returns the issues
322 322 # Valid options are :order, :offset, :limit, :include, :conditions
323 323 def issues(options={})
324 324 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
325 325
326 326 scope = Issue.visible.
327 327 joins(:status, :project).
328 328 where(statement).
329 329 includes(([:status, :project] + (options[:include] || [])).uniq).
330 330 where(options[:conditions]).
331 331 order(order_option).
332 332 joins(joins_for_order_statement(order_option.join(','))).
333 333 limit(options[:limit]).
334 334 offset(options[:offset])
335 335
336 336 if has_custom_field_column?
337 337 scope = scope.preload(:custom_values)
338 338 end
339 339
340 340 issues = scope.all
341 341
342 342 if has_column?(:spent_hours)
343 343 Issue.load_visible_spent_hours(issues)
344 344 end
345 345 if has_column?(:relations)
346 346 Issue.load_visible_relations(issues)
347 347 end
348 348 issues
349 349 rescue ::ActiveRecord::StatementInvalid => e
350 350 raise StatementInvalid.new(e.message)
351 351 end
352 352
353 353 # Returns the issues ids
354 354 def issue_ids(options={})
355 355 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
356 356
357 357 Issue.visible.
358 358 joins(:status, :project).
359 359 where(statement).
360 360 includes(([:status, :project] + (options[:include] || [])).uniq).
361 361 where(options[:conditions]).
362 362 order(order_option).
363 363 joins(joins_for_order_statement(order_option.join(','))).
364 364 limit(options[:limit]).
365 365 offset(options[:offset]).
366 366 find_ids
367 367 rescue ::ActiveRecord::StatementInvalid => e
368 368 raise StatementInvalid.new(e.message)
369 369 end
370 370
371 371 # Returns the journals
372 372 # Valid options are :order, :offset, :limit
373 373 def journals(options={})
374 374 Journal.visible.
375 375 joins(:issue => [:project, :status]).
376 376 where(statement).
377 377 order(options[:order]).
378 378 limit(options[:limit]).
379 379 offset(options[:offset]).
380 380 preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
381 381 all
382 382 rescue ::ActiveRecord::StatementInvalid => e
383 383 raise StatementInvalid.new(e.message)
384 384 end
385 385
386 386 # Returns the versions
387 387 # Valid options are :conditions
388 388 def versions(options={})
389 389 Version.visible.
390 390 where(project_statement).
391 391 where(options[:conditions]).
392 392 includes(:project).
393 393 all
394 394 rescue ::ActiveRecord::StatementInvalid => e
395 395 raise StatementInvalid.new(e.message)
396 396 end
397 397
398 398 def sql_for_watcher_id_field(field, operator, value)
399 399 db_table = Watcher.table_name
400 400 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
401 401 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
402 402 end
403 403
404 404 def sql_for_member_of_group_field(field, operator, value)
405 405 if operator == '*' # Any group
406 406 groups = Group.all
407 407 operator = '=' # Override the operator since we want to find by assigned_to
408 408 elsif operator == "!*"
409 409 groups = Group.all
410 410 operator = '!' # Override the operator since we want to find by assigned_to
411 411 else
412 412 groups = Group.where(:id => value).all
413 413 end
414 414 groups ||= []
415 415
416 416 members_of_groups = groups.inject([]) {|user_ids, group|
417 417 user_ids + group.user_ids + [group.id]
418 418 }.uniq.compact.sort.collect(&:to_s)
419 419
420 420 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
421 421 end
422 422
423 423 def sql_for_assigned_to_role_field(field, operator, value)
424 424 case operator
425 425 when "*", "!*" # Member / Not member
426 426 sw = operator == "!*" ? 'NOT' : ''
427 427 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
428 428 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
429 429 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
430 430 when "=", "!"
431 431 role_cond = value.any? ?
432 432 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{ActiveRecord::Base.connection.quote_string(val)}'"}.join(",") + ")" :
433 433 "1=0"
434 434
435 435 sw = operator == "!" ? 'NOT' : ''
436 436 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
437 437 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
438 438 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
439 439 end
440 440 end
441 441
442 442 def sql_for_is_private_field(field, operator, value)
443 443 op = (operator == "=" ? 'IN' : 'NOT IN')
444 444 va = value.map {|v| v == '0' ? connection.quoted_false : ActiveRecord::Base.connection.quoted_true}.uniq.join(',')
445 445
446 446 "#{Issue.table_name}.is_private #{op} (#{va})"
447 447 end
448 448
449 449 def sql_for_relations(field, operator, value, options={})
450 450 relation_options = IssueRelation::TYPES[field]
451 451 return relation_options unless relation_options
452 452
453 453 relation_type = field
454 454 join_column, target_join_column = "issue_from_id", "issue_to_id"
455 455 if relation_options[:reverse] || options[:reverse]
456 456 relation_type = relation_options[:reverse] || relation_type
457 457 join_column, target_join_column = target_join_column, join_column
458 458 end
459 459
460 460 sql = case operator
461 461 when "*", "!*"
462 462 op = (operator == "*" ? 'IN' : 'NOT IN')
463 463 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{ActiveRecord::Base.connection.quote_string(relation_type)}')"
464 464 when "=", "!"
465 465 op = (operator == "=" ? 'IN' : 'NOT IN')
466 466 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{ActiveRecord::Base.connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})"
467 467 when "=p", "=!p", "!p"
468 468 op = (operator == "!p" ? 'NOT IN' : 'IN')
469 469 comp = (operator == "=!p" ? '<>' : '=')
470 470 "#{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 = '#{ActiveRecord::Base.connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
471 471 end
472 472
473 473 if relation_options[:sym] == field && !options[:reverse]
474 474 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
475 475 sql = sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
476 476 end
477 477 "(#{sql})"
478 478 end
479 479
480 480 IssueRelation::TYPES.keys.each do |relation_type|
481 481 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
482 482 end
483 483 end
General Comments 0
You need to be logged in to leave comments. Login now