annotate app/models/query.rb @ 1524:82fac3dcf466 redmine-2.5-integration

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