##// END OF EJS Templates
Round totals (#1561)....
Jean-Philippe Lang -
r14262:e35d036bdae5
parent child
Show More
@@ -1,575 +1,575
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2015 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", :totalable => true),
38 38 QueryColumn.new(:total_estimated_hours,
39 39 :sortable => "COALESCE((SELECT SUM(estimated_hours) FROM #{Issue.table_name} subtasks" +
40 40 " WHERE subtasks.root_id = #{Issue.table_name}.root_id AND subtasks.lft >= #{Issue.table_name}.lft AND subtasks.rgt <= #{Issue.table_name}.rgt), 0)",
41 41 :default_order => 'desc'),
42 42 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
43 43 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
44 44 QueryColumn.new(:closed_on, :sortable => "#{Issue.table_name}.closed_on", :default_order => 'desc'),
45 45 QueryColumn.new(:relations, :caption => :label_related_issues),
46 46 QueryColumn.new(:description, :inline => false)
47 47 ]
48 48
49 49 scope :visible, lambda {|*args|
50 50 user = args.shift || User.current
51 51 base = Project.allowed_to_condition(user, :view_issues, *args)
52 52 scope = joins("LEFT OUTER JOIN #{Project.table_name} ON #{table_name}.project_id = #{Project.table_name}.id").
53 53 where("#{table_name}.project_id IS NULL OR (#{base})")
54 54
55 55 if user.admin?
56 56 scope.where("#{table_name}.visibility <> ? OR #{table_name}.user_id = ?", VISIBILITY_PRIVATE, user.id)
57 57 elsif user.memberships.any?
58 58 scope.where("#{table_name}.visibility = ?" +
59 59 " OR (#{table_name}.visibility = ? AND #{table_name}.id IN (" +
60 60 "SELECT DISTINCT q.id FROM #{table_name} q" +
61 61 " INNER JOIN #{table_name_prefix}queries_roles#{table_name_suffix} qr on qr.query_id = q.id" +
62 62 " INNER JOIN #{MemberRole.table_name} mr ON mr.role_id = qr.role_id" +
63 63 " INNER JOIN #{Member.table_name} m ON m.id = mr.member_id AND m.user_id = ?" +
64 64 " WHERE q.project_id IS NULL OR q.project_id = m.project_id))" +
65 65 " OR #{table_name}.user_id = ?",
66 66 VISIBILITY_PUBLIC, VISIBILITY_ROLES, user.id, user.id)
67 67 elsif user.logged?
68 68 scope.where("#{table_name}.visibility = ? OR #{table_name}.user_id = ?", VISIBILITY_PUBLIC, user.id)
69 69 else
70 70 scope.where("#{table_name}.visibility = ?", VISIBILITY_PUBLIC)
71 71 end
72 72 }
73 73
74 74 def initialize(attributes=nil, *args)
75 75 super attributes
76 76 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
77 77 end
78 78
79 79 # Returns true if the query is visible to +user+ or the current user.
80 80 def visible?(user=User.current)
81 81 return true if user.admin?
82 82 return false unless project.nil? || user.allowed_to?(:view_issues, project)
83 83 case visibility
84 84 when VISIBILITY_PUBLIC
85 85 true
86 86 when VISIBILITY_ROLES
87 87 if project
88 88 (user.roles_for_project(project) & roles).any?
89 89 else
90 90 Member.where(:user_id => user.id).joins(:roles).where(:member_roles => {:role_id => roles.map(&:id)}).any?
91 91 end
92 92 else
93 93 user == self.user
94 94 end
95 95 end
96 96
97 97 def is_private?
98 98 visibility == VISIBILITY_PRIVATE
99 99 end
100 100
101 101 def is_public?
102 102 !is_private?
103 103 end
104 104
105 105 def draw_relations
106 106 r = options[:draw_relations]
107 107 r.nil? || r == '1'
108 108 end
109 109
110 110 def draw_relations=(arg)
111 111 options[:draw_relations] = (arg == '0' ? '0' : nil)
112 112 end
113 113
114 114 def draw_progress_line
115 115 r = options[:draw_progress_line]
116 116 r == '1'
117 117 end
118 118
119 119 def draw_progress_line=(arg)
120 120 options[:draw_progress_line] = (arg == '1' ? '1' : nil)
121 121 end
122 122
123 123 def build_from_params(params)
124 124 super
125 125 self.draw_relations = params[:draw_relations] || (params[:query] && params[:query][:draw_relations])
126 126 self.draw_progress_line = params[:draw_progress_line] || (params[:query] && params[:query][:draw_progress_line])
127 127 self
128 128 end
129 129
130 130 def initialize_available_filters
131 131 principals = []
132 132 subprojects = []
133 133 versions = []
134 134 categories = []
135 135 issue_custom_fields = []
136 136
137 137 if project
138 138 principals += project.principals.visible
139 139 unless project.leaf?
140 140 subprojects = project.descendants.visible.to_a
141 141 principals += Principal.member_of(subprojects).visible
142 142 end
143 143 versions = project.shared_versions.to_a
144 144 categories = project.issue_categories.to_a
145 145 issue_custom_fields = project.all_issue_custom_fields
146 146 else
147 147 if all_projects.any?
148 148 principals += Principal.member_of(all_projects).visible
149 149 end
150 150 versions = Version.visible.where(:sharing => 'system').to_a
151 151 issue_custom_fields = IssueCustomField.where(:is_for_all => true)
152 152 end
153 153 principals.uniq!
154 154 principals.sort!
155 155 principals.reject! {|p| p.is_a?(GroupBuiltin)}
156 156 users = principals.select {|p| p.is_a?(User)}
157 157
158 158 add_available_filter "status_id",
159 159 :type => :list_status, :values => IssueStatus.sorted.collect{|s| [s.name, s.id.to_s] }
160 160
161 161 if project.nil?
162 162 project_values = []
163 163 if User.current.logged? && User.current.memberships.any?
164 164 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
165 165 end
166 166 project_values += all_projects_values
167 167 add_available_filter("project_id",
168 168 :type => :list, :values => project_values
169 169 ) unless project_values.empty?
170 170 end
171 171
172 172 add_available_filter "tracker_id",
173 173 :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] }
174 174 add_available_filter "priority_id",
175 175 :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
176 176
177 177 author_values = []
178 178 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
179 179 author_values += users.collect{|s| [s.name, s.id.to_s] }
180 180 add_available_filter("author_id",
181 181 :type => :list, :values => author_values
182 182 ) unless author_values.empty?
183 183
184 184 assigned_to_values = []
185 185 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
186 186 assigned_to_values += (Setting.issue_group_assignment? ?
187 187 principals : users).collect{|s| [s.name, s.id.to_s] }
188 188 add_available_filter("assigned_to_id",
189 189 :type => :list_optional, :values => assigned_to_values
190 190 ) unless assigned_to_values.empty?
191 191
192 192 group_values = Group.givable.visible.collect {|g| [g.name, g.id.to_s] }
193 193 add_available_filter("member_of_group",
194 194 :type => :list_optional, :values => group_values
195 195 ) unless group_values.empty?
196 196
197 197 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
198 198 add_available_filter("assigned_to_role",
199 199 :type => :list_optional, :values => role_values
200 200 ) unless role_values.empty?
201 201
202 202 if versions.any?
203 203 add_available_filter "fixed_version_id",
204 204 :type => :list_optional,
205 205 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
206 206 end
207 207
208 208 if categories.any?
209 209 add_available_filter "category_id",
210 210 :type => :list_optional,
211 211 :values => categories.collect{|s| [s.name, s.id.to_s] }
212 212 end
213 213
214 214 add_available_filter "subject", :type => :text
215 215 add_available_filter "created_on", :type => :date_past
216 216 add_available_filter "updated_on", :type => :date_past
217 217 add_available_filter "closed_on", :type => :date_past
218 218 add_available_filter "start_date", :type => :date
219 219 add_available_filter "due_date", :type => :date
220 220 add_available_filter "estimated_hours", :type => :float
221 221 add_available_filter "done_ratio", :type => :integer
222 222
223 223 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
224 224 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
225 225 add_available_filter "is_private",
226 226 :type => :list,
227 227 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
228 228 end
229 229
230 230 if User.current.logged?
231 231 add_available_filter "watcher_id",
232 232 :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]]
233 233 end
234 234
235 235 if subprojects.any?
236 236 add_available_filter "subproject_id",
237 237 :type => :list_subprojects,
238 238 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
239 239 end
240 240
241 241 add_custom_fields_filters(issue_custom_fields)
242 242
243 243 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
244 244
245 245 IssueRelation::TYPES.each do |relation_type, options|
246 246 add_available_filter relation_type, :type => :relation, :label => options[:name]
247 247 end
248 248 add_available_filter "parent_id", :type => :tree, :label => :field_parent_issue
249 249 add_available_filter "child_id", :type => :tree, :label => :label_subtask_plural
250 250
251 251 Tracker.disabled_core_fields(trackers).each {|field|
252 252 delete_available_filter field
253 253 }
254 254 end
255 255
256 256 def available_columns
257 257 return @available_columns if @available_columns
258 258 @available_columns = self.class.available_columns.dup
259 259 @available_columns += (project ?
260 260 project.all_issue_custom_fields :
261 261 IssueCustomField
262 262 ).visible.collect {|cf| QueryCustomFieldColumn.new(cf) }
263 263
264 264 if User.current.allowed_to?(:view_time_entries, project, :global => true)
265 265 index = @available_columns.find_index {|column| column.name == :total_estimated_hours}
266 266 index = (index ? index + 1 : -1)
267 267 # insert the column after total_estimated_hours or at the end
268 268 @available_columns.insert index, QueryColumn.new(:spent_hours,
269 269 :sortable => "COALESCE((SELECT SUM(hours) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)",
270 270 :default_order => 'desc',
271 271 :caption => :label_spent_time,
272 272 :totalable => true
273 273 )
274 274 @available_columns.insert index+1, QueryColumn.new(:total_spent_hours,
275 275 :sortable => "COALESCE((SELECT SUM(hours) FROM #{TimeEntry.table_name} JOIN #{Issue.table_name} subtasks ON subtasks.id = #{TimeEntry.table_name}.issue_id" +
276 276 " WHERE subtasks.root_id = #{Issue.table_name}.root_id AND subtasks.lft >= #{Issue.table_name}.lft AND subtasks.rgt <= #{Issue.table_name}.rgt), 0)",
277 277 :default_order => 'desc',
278 278 :caption => :label_total_spent_time
279 279 )
280 280 end
281 281
282 282 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
283 283 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
284 284 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
285 285 end
286 286
287 287 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
288 288 @available_columns.reject! {|column|
289 289 disabled_fields.include?(column.name.to_s)
290 290 }
291 291
292 292 @available_columns
293 293 end
294 294
295 295 def default_columns_names
296 296 @default_columns_names ||= begin
297 297 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
298 298
299 299 project.present? ? default_columns : [:project] | default_columns
300 300 end
301 301 end
302 302
303 303 def base_scope
304 304 Issue.visible.joins(:status, :project).where(statement)
305 305 end
306 306 private :base_scope
307 307
308 308 # Returns the issue count
309 309 def issue_count
310 310 base_scope.count
311 311 rescue ::ActiveRecord::StatementInvalid => e
312 312 raise StatementInvalid.new(e.message)
313 313 end
314 314
315 315 # Returns sum of all the issue's estimated_hours
316 316 def total_for_estimated_hours
317 base_scope.sum(:estimated_hours)
317 base_scope.sum(:estimated_hours).to_f.round(2)
318 318 end
319 319
320 320 # Returns sum of all the issue's time entries hours
321 321 def total_for_spent_hours
322 base_scope.joins(:time_entries).sum("#{TimeEntry.table_name}.hours")
322 base_scope.joins(:time_entries).sum("#{TimeEntry.table_name}.hours").to_f.round(2)
323 323 end
324 324
325 325 def total_for_custom_field(custom_field)
326 326 base_scope.joins(:custom_values).
327 327 where(:custom_values => {:custom_field_id => custom_field.id}).
328 328 where.not(:custom_values => {:value => ''}).
329 329 sum("CAST(#{CustomValue.table_name}.value AS decimal(30,3))")
330 330 end
331 331 private :total_for_custom_field
332 332
333 333 def total_for_float_custom_field(custom_field)
334 334 total_for_custom_field(custom_field).to_f
335 335 end
336 336
337 337 def total_for_int_custom_field(custom_field)
338 338 total_for_custom_field(custom_field).to_i
339 339 end
340 340
341 341 # Returns the issue count by group or nil if query is not grouped
342 342 def issue_count_by_group
343 343 r = nil
344 344 if grouped?
345 345 begin
346 346 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
347 347 r = Issue.visible.
348 348 joins(:status, :project).
349 349 where(statement).
350 350 joins(joins_for_order_statement(group_by_statement)).
351 351 group(group_by_statement).
352 352 count
353 353 rescue ActiveRecord::RecordNotFound
354 354 r = {nil => issue_count}
355 355 end
356 356 c = group_by_column
357 357 if c.is_a?(QueryCustomFieldColumn)
358 358 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
359 359 end
360 360 end
361 361 r
362 362 rescue ::ActiveRecord::StatementInvalid => e
363 363 raise StatementInvalid.new(e.message)
364 364 end
365 365
366 366 # Returns the issues
367 367 # Valid options are :order, :offset, :limit, :include, :conditions
368 368 def issues(options={})
369 369 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
370 370
371 371 scope = Issue.visible.
372 372 joins(:status, :project).
373 373 where(statement).
374 374 includes(([:status, :project] + (options[:include] || [])).uniq).
375 375 where(options[:conditions]).
376 376 order(order_option).
377 377 joins(joins_for_order_statement(order_option.join(','))).
378 378 limit(options[:limit]).
379 379 offset(options[:offset])
380 380
381 381 scope = scope.preload(:custom_values)
382 382 if has_column?(:author)
383 383 scope = scope.preload(:author)
384 384 end
385 385
386 386 issues = scope.to_a
387 387
388 388 if has_column?(:spent_hours)
389 389 Issue.load_visible_spent_hours(issues)
390 390 end
391 391 if has_column?(:total_spent_hours)
392 392 Issue.load_visible_total_spent_hours(issues)
393 393 end
394 394 if has_column?(:relations)
395 395 Issue.load_visible_relations(issues)
396 396 end
397 397 issues
398 398 rescue ::ActiveRecord::StatementInvalid => e
399 399 raise StatementInvalid.new(e.message)
400 400 end
401 401
402 402 # Returns the issues ids
403 403 def issue_ids(options={})
404 404 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
405 405
406 406 Issue.visible.
407 407 joins(:status, :project).
408 408 where(statement).
409 409 includes(([:status, :project] + (options[:include] || [])).uniq).
410 410 references(([:status, :project] + (options[:include] || [])).uniq).
411 411 where(options[:conditions]).
412 412 order(order_option).
413 413 joins(joins_for_order_statement(order_option.join(','))).
414 414 limit(options[:limit]).
415 415 offset(options[:offset]).
416 416 pluck(:id)
417 417 rescue ::ActiveRecord::StatementInvalid => e
418 418 raise StatementInvalid.new(e.message)
419 419 end
420 420
421 421 # Returns the journals
422 422 # Valid options are :order, :offset, :limit
423 423 def journals(options={})
424 424 Journal.visible.
425 425 joins(:issue => [:project, :status]).
426 426 where(statement).
427 427 order(options[:order]).
428 428 limit(options[:limit]).
429 429 offset(options[:offset]).
430 430 preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
431 431 to_a
432 432 rescue ::ActiveRecord::StatementInvalid => e
433 433 raise StatementInvalid.new(e.message)
434 434 end
435 435
436 436 # Returns the versions
437 437 # Valid options are :conditions
438 438 def versions(options={})
439 439 Version.visible.
440 440 where(project_statement).
441 441 where(options[:conditions]).
442 442 includes(:project).
443 443 references(:project).
444 444 to_a
445 445 rescue ::ActiveRecord::StatementInvalid => e
446 446 raise StatementInvalid.new(e.message)
447 447 end
448 448
449 449 def sql_for_watcher_id_field(field, operator, value)
450 450 db_table = Watcher.table_name
451 451 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
452 452 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
453 453 end
454 454
455 455 def sql_for_member_of_group_field(field, operator, value)
456 456 if operator == '*' # Any group
457 457 groups = Group.givable
458 458 operator = '=' # Override the operator since we want to find by assigned_to
459 459 elsif operator == "!*"
460 460 groups = Group.givable
461 461 operator = '!' # Override the operator since we want to find by assigned_to
462 462 else
463 463 groups = Group.where(:id => value).to_a
464 464 end
465 465 groups ||= []
466 466
467 467 members_of_groups = groups.inject([]) {|user_ids, group|
468 468 user_ids + group.user_ids + [group.id]
469 469 }.uniq.compact.sort.collect(&:to_s)
470 470
471 471 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
472 472 end
473 473
474 474 def sql_for_assigned_to_role_field(field, operator, value)
475 475 case operator
476 476 when "*", "!*" # Member / Not member
477 477 sw = operator == "!*" ? 'NOT' : ''
478 478 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
479 479 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
480 480 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
481 481 when "=", "!"
482 482 role_cond = value.any? ?
483 483 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{self.class.connection.quote_string(val)}'"}.join(",") + ")" :
484 484 "1=0"
485 485
486 486 sw = operator == "!" ? 'NOT' : ''
487 487 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
488 488 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
489 489 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
490 490 end
491 491 end
492 492
493 493 def sql_for_is_private_field(field, operator, value)
494 494 op = (operator == "=" ? 'IN' : 'NOT IN')
495 495 va = value.map {|v| v == '0' ? self.class.connection.quoted_false : self.class.connection.quoted_true}.uniq.join(',')
496 496
497 497 "#{Issue.table_name}.is_private #{op} (#{va})"
498 498 end
499 499
500 500 def sql_for_parent_id_field(field, operator, value)
501 501 case operator
502 502 when "="
503 503 "#{Issue.table_name}.parent_id = #{value.first.to_i}"
504 504 when "~"
505 505 root_id, lft, rgt = Issue.where(:id => value.first.to_i).pluck(:root_id, :lft, :rgt).first
506 506 if root_id && lft && rgt
507 507 "#{Issue.table_name}.root_id = #{root_id} AND #{Issue.table_name}.lft > #{lft} AND #{Issue.table_name}.rgt < #{rgt}"
508 508 else
509 509 "1=0"
510 510 end
511 511 when "!*"
512 512 "#{Issue.table_name}.parent_id IS NULL"
513 513 when "*"
514 514 "#{Issue.table_name}.parent_id IS NOT NULL"
515 515 end
516 516 end
517 517
518 518 def sql_for_child_id_field(field, operator, value)
519 519 case operator
520 520 when "="
521 521 parent_id = Issue.where(:id => value.first.to_i).pluck(:parent_id).first
522 522 if parent_id
523 523 "#{Issue.table_name}.id = #{parent_id}"
524 524 else
525 525 "1=0"
526 526 end
527 527 when "~"
528 528 root_id, lft, rgt = Issue.where(:id => value.first.to_i).pluck(:root_id, :lft, :rgt).first
529 529 if root_id && lft && rgt
530 530 "#{Issue.table_name}.root_id = #{root_id} AND #{Issue.table_name}.lft < #{lft} AND #{Issue.table_name}.rgt > #{rgt}"
531 531 else
532 532 "1=0"
533 533 end
534 534 when "!*"
535 535 "#{Issue.table_name}.rgt - #{Issue.table_name}.lft = 1"
536 536 when "*"
537 537 "#{Issue.table_name}.rgt - #{Issue.table_name}.lft > 1"
538 538 end
539 539 end
540 540
541 541 def sql_for_relations(field, operator, value, options={})
542 542 relation_options = IssueRelation::TYPES[field]
543 543 return relation_options unless relation_options
544 544
545 545 relation_type = field
546 546 join_column, target_join_column = "issue_from_id", "issue_to_id"
547 547 if relation_options[:reverse] || options[:reverse]
548 548 relation_type = relation_options[:reverse] || relation_type
549 549 join_column, target_join_column = target_join_column, join_column
550 550 end
551 551
552 552 sql = case operator
553 553 when "*", "!*"
554 554 op = (operator == "*" ? 'IN' : 'NOT IN')
555 555 "#{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)}')"
556 556 when "=", "!"
557 557 op = (operator == "=" ? 'IN' : 'NOT IN')
558 558 "#{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} = #{value.first.to_i})"
559 559 when "=p", "=!p", "!p"
560 560 op = (operator == "!p" ? 'NOT IN' : 'IN')
561 561 comp = (operator == "=!p" ? '<>' : '=')
562 562 "#{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})"
563 563 end
564 564
565 565 if relation_options[:sym] == field && !options[:reverse]
566 566 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
567 567 sql = sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
568 568 end
569 569 "(#{sql})"
570 570 end
571 571
572 572 IssueRelation::TYPES.keys.each do |relation_type|
573 573 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
574 574 end
575 575 end
General Comments 0
You need to be logged in to leave comments. Login now