Chris@0: # Redmine - project management software Chris@1115: # Copyright (C) 2006-2012 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@441: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@441: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@441: class QueryColumn Chris@0: attr_accessor :name, :sortable, :groupable, :default_order Chris@0: include Redmine::I18n Chris@441: Chris@0: def initialize(name, options={}) Chris@0: self.name = name Chris@0: self.sortable = options[:sortable] Chris@0: self.groupable = options[:groupable] || false Chris@0: if groupable == true Chris@0: self.groupable = name.to_s Chris@0: end Chris@0: self.default_order = options[:default_order] Chris@1115: @inline = options.key?(:inline) ? options[:inline] : true Chris@0: @caption_key = options[:caption] || "field_#{name}" Chris@0: end Chris@441: Chris@0: def caption Chris@0: l(@caption_key) Chris@0: end Chris@441: Chris@0: # Returns true if the column is sortable, otherwise false Chris@0: def sortable? Chris@909: !@sortable.nil? Chris@909: end Chris@1115: Chris@909: def sortable Chris@909: @sortable.is_a?(Proc) ? @sortable.call : @sortable Chris@0: end Chris@441: Chris@1115: def inline? Chris@1115: @inline Chris@1115: end Chris@1115: Chris@0: def value(issue) Chris@0: issue.send name Chris@0: end Chris@441: Chris@441: def css_classes Chris@441: name Chris@441: end Chris@0: end Chris@0: Chris@0: class QueryCustomFieldColumn < QueryColumn Chris@0: Chris@0: def initialize(custom_field) Chris@0: self.name = "cf_#{custom_field.id}".to_sym Chris@0: self.sortable = custom_field.order_statement || false Chris@1115: self.groupable = custom_field.group_statement || false Chris@1115: @inline = true Chris@0: @cf = custom_field Chris@0: end Chris@441: Chris@0: def caption Chris@0: @cf.name Chris@0: end Chris@441: Chris@0: def custom_field Chris@0: @cf Chris@0: end Chris@441: Chris@0: def value(issue) Chris@1115: cv = issue.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)} Chris@1115: cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first Chris@0: end Chris@441: Chris@441: def css_classes Chris@441: @css_classes ||= "#{name} #{@cf.field_format}" Chris@441: end Chris@0: end Chris@0: Chris@0: class Query < ActiveRecord::Base Chris@0: class StatementInvalid < ::ActiveRecord::StatementInvalid Chris@0: end Chris@441: Chris@0: belongs_to :project Chris@0: belongs_to :user Chris@0: serialize :filters Chris@0: serialize :column_names Chris@0: serialize :sort_criteria, Array Chris@441: Chris@0: attr_protected :project_id, :user_id Chris@441: Chris@1115: validates_presence_of :name Chris@0: validates_length_of :name, :maximum => 255 Chris@909: validate :validate_query_filters Chris@441: Chris@441: @@operators = { "=" => :label_equals, Chris@0: "!" => :label_not_equals, Chris@0: "o" => :label_open_issues, Chris@0: "c" => :label_closed_issues, Chris@0: "!*" => :label_none, Chris@1115: "*" => :label_any, Chris@0: ">=" => :label_greater_or_equal, Chris@0: "<=" => :label_less_or_equal, Chris@909: "><" => :label_between, Chris@0: " :label_in_less_than, Chris@0: ">t+" => :label_in_more_than, Chris@1115: "> :label_in_the_next_days, Chris@0: "t+" => :label_in, Chris@0: "t" => :label_today, Chris@0: "w" => :label_this_week, Chris@0: ">t-" => :label_less_than_ago, Chris@0: " :label_more_than_ago, Chris@1115: "> :label_in_the_past_days, Chris@0: "t-" => :label_ago, Chris@0: "~" => :label_contains, Chris@1115: "!~" => :label_not_contains, Chris@1115: "=p" => :label_any_issues_in_project, Chris@1115: "=!p" => :label_any_issues_not_in_project, Chris@1115: "!p" => :label_no_issues_in_project} Chris@0: Chris@0: cattr_reader :operators Chris@441: Chris@0: @@operators_by_filter_type = { :list => [ "=", "!" ], Chris@0: :list_status => [ "o", "=", "!", "c", "*" ], Chris@0: :list_optional => [ "=", "!", "!*", "*" ], Chris@0: :list_subprojects => [ "*", "!*", "=" ], Chris@1115: :date => [ "=", ">=", "<=", "><", "t+", ">t-", " [ "=", ">=", "<=", "><", ">t-", " [ "=", "~", "!", "!~", "!*", "*" ], Chris@1115: :text => [ "~", "!~", "!*", "*" ], Chris@909: :integer => [ "=", ">=", "<=", "><", "!*", "*" ], Chris@1115: :float => [ "=", ">=", "<=", "><", "!*", "*" ], Chris@1115: :relation => ["=", "=p", "=!p", "!p", "!*", "*"]} Chris@0: Chris@0: cattr_reader :operators_by_filter_type Chris@0: Chris@0: @@available_columns = [ Chris@0: QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true), Chris@0: QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true), Chris@0: QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue), Chris@0: QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true), Chris@0: QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true), Chris@0: QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"), Chris@909: QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true), Chris@909: QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true), Chris@0: QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'), Chris@0: QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true), Chris@1115: QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true), Chris@0: QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"), Chris@0: QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"), Chris@0: QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"), Chris@0: QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true), Chris@0: QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'), Chris@1115: QueryColumn.new(:relations, :caption => :label_related_issues), Chris@1115: QueryColumn.new(:description, :inline => false) Chris@0: ] Chris@0: cattr_reader :available_columns Chris@441: Chris@1115: scope :visible, lambda {|*args| Chris@909: user = args.shift || User.current Chris@909: base = Project.allowed_to_condition(user, :view_issues, *args) Chris@909: user_id = user.logged? ? user.id : 0 Chris@909: { Chris@909: :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id], Chris@909: :include => :project Chris@909: } Chris@909: } Chris@909: Chris@1115: def initialize(attributes=nil, *args) Chris@0: super attributes Chris@0: self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} } Chris@0: @is_for_all = project.nil? Chris@0: end Chris@441: Chris@909: def validate_query_filters Chris@0: filters.each_key do |field| Chris@909: if values_for(field) Chris@909: case type_for(field) Chris@909: when :integer Chris@1115: add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) } Chris@909: when :float Chris@1115: add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) } Chris@909: when :date, :date_past Chris@909: case operator_for(field) Chris@909: when "=", ">=", "<=", "><" Chris@1115: add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) } Chris@1115: when ">t-", "t+", " 'activerecord.errors.messages') Chris@1115: errors.add(:base, m) Chris@1115: end Chris@1115: Chris@507: # Returns true if the query is visible to +user+ or the current user. Chris@507: def visible?(user=User.current) Chris@909: (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id) Chris@507: end Chris@441: Chris@0: def editable_by?(user) Chris@0: return false unless user Chris@0: # Admin can edit them all and regular users can edit their private queries Chris@0: return true if user.admin? || (!is_public && self.user_id == user.id) Chris@0: # Members can not edit public queries that are for all project (only admin is allowed to) Chris@0: is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project) Chris@0: end Chris@441: Chris@1115: def trackers Chris@1115: @trackers ||= project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers Chris@1115: end Chris@1115: Chris@1115: # Returns a hash of localized labels for all filter operators Chris@1115: def self.operators_labels Chris@1115: operators.inject({}) {|h, operator| h[operator.first] = l(operator.last); h} Chris@1115: end Chris@1115: Chris@0: def available_filters Chris@0: return @available_filters if @available_filters Chris@1115: @available_filters = { Chris@1115: "status_id" => { Chris@1115: :type => :list_status, :order => 0, Chris@1115: :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } Chris@1115: }, Chris@1115: "tracker_id" => { Chris@1115: :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } Chris@1115: }, Chris@1115: "priority_id" => { Chris@1115: :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } Chris@1115: }, Chris@1115: "subject" => { :type => :text, :order => 8 }, Chris@1115: "created_on" => { :type => :date_past, :order => 9 }, Chris@1115: "updated_on" => { :type => :date_past, :order => 10 }, Chris@1115: "start_date" => { :type => :date, :order => 11 }, Chris@1115: "due_date" => { :type => :date, :order => 12 }, Chris@1115: "estimated_hours" => { :type => :float, :order => 13 }, Chris@1115: "done_ratio" => { :type => :integer, :order => 14 } Chris@1115: } Chris@1115: IssueRelation::TYPES.each do |relation_type, options| Chris@1115: @available_filters[relation_type] = { Chris@1115: :type => :relation, :order => @available_filters.size + 100, Chris@1115: :label => options[:name] Chris@1115: } Chris@1115: end Chris@909: principals = [] Chris@0: if project Chris@909: principals += project.principals.sort Chris@1115: unless project.leaf? Chris@1115: subprojects = project.descendants.visible.all Chris@1115: if subprojects.any? Chris@1115: @available_filters["subproject_id"] = { Chris@1115: :type => :list_subprojects, :order => 13, Chris@1115: :values => subprojects.collect{|s| [s.name, s.id.to_s] } Chris@1115: } Chris@1115: principals += Principal.member_of(subprojects) Chris@1115: end Chris@1115: end Chris@0: else Chris@119: if all_projects.any? Chris@119: # members of visible projects Chris@1115: principals += Principal.member_of(all_projects) Chris@119: # project filter Chris@119: project_values = [] Chris@1115: if User.current.logged? && User.current.memberships.any? Chris@1115: project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"] Chris@119: end Chris@1115: project_values += all_projects_values Chris@1115: @available_filters["project_id"] = { Chris@1115: :type => :list, :order => 1, :values => project_values Chris@1115: } unless project_values.empty? Chris@0: end Chris@0: end Chris@1115: principals.uniq! Chris@1115: principals.sort! Chris@909: users = principals.select {|p| p.is_a?(User)} Chris@909: Chris@909: assigned_to_values = [] Chris@909: assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged? Chris@1115: assigned_to_values += (Setting.issue_group_assignment? ? Chris@1115: principals : users).collect{|s| [s.name, s.id.to_s] } Chris@1115: @available_filters["assigned_to_id"] = { Chris@1115: :type => :list_optional, :order => 4, :values => assigned_to_values Chris@1115: } unless assigned_to_values.empty? Chris@909: Chris@909: author_values = [] Chris@909: author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged? Chris@909: author_values += users.collect{|s| [s.name, s.id.to_s] } Chris@1115: @available_filters["author_id"] = { Chris@1115: :type => :list, :order => 5, :values => author_values Chris@1115: } unless author_values.empty? chris@22: chris@37: group_values = Group.all.collect {|g| [g.name, g.id.to_s] } Chris@1115: @available_filters["member_of_group"] = { Chris@1115: :type => :list_optional, :order => 6, :values => group_values Chris@1115: } unless group_values.empty? chris@22: chris@37: role_values = Role.givable.collect {|r| [r.name, r.id.to_s] } Chris@1115: @available_filters["assigned_to_role"] = { Chris@1115: :type => :list_optional, :order => 7, :values => role_values Chris@1115: } unless role_values.empty? Chris@441: Chris@0: if User.current.logged? Chris@1115: @available_filters["watcher_id"] = { Chris@1115: :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] Chris@1115: } Chris@0: end Chris@441: Chris@0: if project Chris@0: # project specific filters Chris@909: categories = project.issue_categories.all Chris@441: unless categories.empty? Chris@1115: @available_filters["category_id"] = { Chris@1115: :type => :list_optional, :order => 6, Chris@1115: :values => categories.collect{|s| [s.name, s.id.to_s] } Chris@1115: } Chris@0: end Chris@909: versions = project.shared_versions.all Chris@441: unless versions.empty? Chris@1115: @available_filters["fixed_version_id"] = { Chris@1115: :type => :list_optional, :order => 7, Chris@1115: :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } Chris@1115: } Chris@0: end Chris@909: add_custom_fields_filters(project.all_issue_custom_fields) Chris@0: else Chris@0: # global filters for cross project issue list Chris@0: system_shared_versions = Version.visible.find_all_by_sharing('system') Chris@0: unless system_shared_versions.empty? Chris@1115: @available_filters["fixed_version_id"] = { Chris@1115: :type => :list_optional, :order => 7, Chris@1115: :values => system_shared_versions.sort.collect{|s| Chris@1115: ["#{s.project.name} - #{s.name}", s.id.to_s] Chris@1115: } Chris@1115: } Chris@0: end Chris@1115: add_custom_fields_filters( Chris@1115: IssueCustomField.find(:all, Chris@1115: :conditions => { Chris@1115: :is_filter => true, Chris@1115: :is_for_all => true Chris@1115: })) Chris@1115: end Chris@1115: add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version Chris@1115: if User.current.allowed_to?(:set_issues_private, nil, :global => true) || Chris@1115: User.current.allowed_to?(:set_own_issues_private, nil, :global => true) Chris@1115: @available_filters["is_private"] = { Chris@1115: :type => :list, :order => 16, Chris@1115: :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]] Chris@1115: } Chris@1115: end Chris@1115: Tracker.disabled_core_fields(trackers).each {|field| Chris@1115: @available_filters.delete field Chris@1115: } Chris@1115: @available_filters.each do |field, options| Chris@1115: options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, '')) Chris@0: end Chris@0: @available_filters Chris@0: end Chris@441: Chris@1115: # Returns a representation of the available filters for JSON serialization Chris@1115: def available_filters_as_json Chris@1115: json = {} Chris@1115: available_filters.each do |field, options| Chris@1115: json[field] = options.slice(:type, :name, :values).stringify_keys Chris@1115: end Chris@1115: json Chris@1115: end Chris@1115: Chris@1115: def all_projects Chris@1115: @all_projects ||= Project.visible.all Chris@1115: end Chris@1115: Chris@1115: def all_projects_values Chris@1115: return @all_projects_values if @all_projects_values Chris@1115: Chris@1115: values = [] Chris@1115: Project.project_tree(all_projects) do |p, level| Chris@1115: prefix = (level > 0 ? ('--' * level + ' ') : '') Chris@1115: values << ["#{prefix}#{p.name}", p.id.to_s] Chris@1115: end Chris@1115: @all_projects_values = values Chris@1115: end Chris@1115: Chris@0: def add_filter(field, operator, values) Chris@0: # values must be an array Chris@909: return unless values.nil? || values.is_a?(Array) Chris@0: # check if field is defined as an available filter Chris@0: if available_filters.has_key? field Chris@0: filter_options = available_filters[field] Chris@0: # check if operator is allowed for that filter Chris@0: #if @@operators_by_filter_type[filter_options[:type]].include? operator Chris@0: # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]}) Chris@0: # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator Chris@0: #end Chris@909: filters[field] = {:operator => operator, :values => (values || [''])} Chris@0: end Chris@0: end Chris@441: Chris@0: def add_short_filter(field, expression) Chris@909: return unless expression && available_filters.has_key?(field) Chris@909: field_type = available_filters[field][:type] Chris@909: @@operators_by_filter_type[field_type].sort.reverse.detect do |operator| Chris@909: next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/ Chris@909: add_filter field, operator, $1.present? ? $1.split('|') : [''] Chris@909: end || add_filter(field, '=', expression.split('|')) Chris@0: end Chris@0: Chris@0: # Add multiple filters using +add_filter+ Chris@0: def add_filters(fields, operators, values) Chris@909: if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash)) chris@37: fields.each do |field| Chris@909: add_filter(field, operators[field], values && values[field]) chris@37: end Chris@0: end Chris@0: end Chris@441: Chris@0: def has_filter?(field) Chris@0: filters and filters[field] Chris@0: end Chris@441: Chris@909: def type_for(field) Chris@909: available_filters[field][:type] if available_filters.has_key?(field) Chris@909: end Chris@909: Chris@0: def operator_for(field) Chris@0: has_filter?(field) ? filters[field][:operator] : nil Chris@0: end Chris@441: Chris@0: def values_for(field) Chris@0: has_filter?(field) ? filters[field][:values] : nil Chris@0: end Chris@441: Chris@909: def value_for(field, index=0) Chris@909: (values_for(field) || [])[index] Chris@909: end Chris@909: Chris@0: def label_for(field) Chris@0: label = available_filters[field][:name] if available_filters.has_key?(field) Chris@1115: label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field) Chris@0: end Chris@0: Chris@0: def available_columns Chris@0: return @available_columns if @available_columns Chris@1115: @available_columns = ::Query.available_columns.dup Chris@909: @available_columns += (project ? Chris@0: project.all_issue_custom_fields : Chris@0: IssueCustomField.find(:all) Chris@441: ).collect {|cf| QueryCustomFieldColumn.new(cf) } Chris@1115: Chris@1115: if User.current.allowed_to?(:view_time_entries, project, :global => true) Chris@1115: index = nil Chris@1115: @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours} Chris@1115: index = (index ? index + 1 : -1) Chris@1115: # insert the column after estimated_hours or at the end Chris@1115: @available_columns.insert index, QueryColumn.new(:spent_hours, Chris@1115: :sortable => "(SELECT COALESCE(SUM(hours), 0) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id)", Chris@1115: :default_order => 'desc', Chris@1115: :caption => :label_spent_time Chris@1115: ) Chris@1115: end Chris@1115: Chris@1115: if User.current.allowed_to?(:set_issues_private, nil, :global => true) || Chris@1115: User.current.allowed_to?(:set_own_issues_private, nil, :global => true) Chris@1115: @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private") Chris@1115: end Chris@1115: Chris@1115: disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')} Chris@1115: @available_columns.reject! {|column| Chris@1115: disabled_fields.include?(column.name.to_s) Chris@1115: } Chris@1115: Chris@1115: @available_columns Chris@0: end Chris@0: Chris@0: def self.available_columns=(v) Chris@0: self.available_columns = (v) Chris@0: end Chris@441: Chris@0: def self.add_available_column(column) Chris@0: self.available_columns << (column) if column.is_a?(QueryColumn) Chris@0: end Chris@441: Chris@0: # Returns an array of columns that can be used to group the results Chris@0: def groupable_columns Chris@0: available_columns.select {|c| c.groupable} Chris@0: end Chris@0: Chris@0: # Returns a Hash of columns and the key for sorting Chris@0: def sortable_columns Chris@0: {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column| Chris@0: h[column.name.to_s] = column.sortable Chris@0: h Chris@0: }) Chris@0: end Chris@441: Chris@0: def columns Chris@909: # preserve the column_names order Chris@909: (has_default_columns? ? default_columns_names : column_names).collect do |name| Chris@909: available_columns.find { |col| col.name == name } Chris@909: end.compact Chris@909: end Chris@909: Chris@1115: def inline_columns Chris@1115: columns.select(&:inline?) Chris@1115: end Chris@1115: Chris@1115: def block_columns Chris@1115: columns.reject(&:inline?) Chris@1115: end Chris@1115: Chris@1115: def available_inline_columns Chris@1115: available_columns.select(&:inline?) Chris@1115: end Chris@1115: Chris@1115: def available_block_columns Chris@1115: available_columns.reject(&:inline?) Chris@1115: end Chris@1115: Chris@909: def default_columns_names Chris@909: @default_columns_names ||= begin Chris@909: default_columns = Setting.issue_list_default_columns.map(&:to_sym) Chris@909: Chris@909: project.present? ? default_columns : [:project] | default_columns Chris@0: end Chris@0: end Chris@441: Chris@0: def column_names=(names) Chris@0: if names Chris@0: names = names.select {|n| n.is_a?(Symbol) || !n.blank? } Chris@0: names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym } Chris@0: # Set column_names to nil if default columns Chris@909: if names == default_columns_names Chris@0: names = nil Chris@0: end Chris@0: end Chris@0: write_attribute(:column_names, names) Chris@0: end Chris@441: Chris@0: def has_column?(column) Chris@1115: column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column) Chris@0: end Chris@441: Chris@0: def has_default_columns? Chris@0: column_names.nil? || column_names.empty? Chris@0: end Chris@441: Chris@0: def sort_criteria=(arg) Chris@0: c = [] Chris@0: if arg.is_a?(Hash) Chris@0: arg = arg.keys.sort.collect {|k| arg[k]} Chris@0: end Chris@1115: 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: write_attribute(:sort_criteria, c) Chris@0: end Chris@441: Chris@0: def sort_criteria Chris@0: read_attribute(:sort_criteria) || [] Chris@0: end Chris@441: Chris@0: def sort_criteria_key(arg) Chris@0: sort_criteria && sort_criteria[arg] && sort_criteria[arg].first Chris@0: end Chris@441: Chris@0: def sort_criteria_order(arg) Chris@0: sort_criteria && sort_criteria[arg] && sort_criteria[arg].last Chris@0: end Chris@441: Chris@1115: def sort_criteria_order_for(key) Chris@1115: sort_criteria.detect {|k, order| key.to_s == k}.try(:last) Chris@1115: end Chris@1115: Chris@0: # Returns the SQL sort order that should be prepended for grouping Chris@0: def group_by_sort_order Chris@0: if grouped? && (column = group_by_column) Chris@1115: order = sort_criteria_order_for(column.name) || column.default_order Chris@0: column.sortable.is_a?(Array) ? Chris@1115: column.sortable.collect {|s| "#{s} #{order}"}.join(',') : Chris@1115: "#{column.sortable} #{order}" Chris@0: end Chris@0: end Chris@441: Chris@0: # Returns true if the query is a grouped query Chris@0: def grouped? Chris@119: !group_by_column.nil? Chris@0: end Chris@441: Chris@0: def group_by_column Chris@119: groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by} Chris@0: end Chris@441: Chris@0: def group_by_statement Chris@119: group_by_column.try(:groupable) Chris@0: end Chris@441: Chris@0: def project_statement Chris@0: project_clauses = [] Chris@909: if project && !project.descendants.active.empty? Chris@0: ids = [project.id] Chris@0: if has_filter?("subproject_id") Chris@0: case operator_for("subproject_id") Chris@0: when '=' Chris@0: # include the selected subprojects Chris@0: ids += values_for("subproject_id").each(&:to_i) Chris@0: when '!*' Chris@0: # main project only Chris@0: else Chris@0: # all subprojects Chris@0: ids += project.descendants.collect(&:id) Chris@0: end Chris@0: elsif Setting.display_subprojects_issues? Chris@0: ids += project.descendants.collect(&:id) Chris@0: end Chris@0: project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',') Chris@0: elsif project Chris@0: project_clauses << "#{Project.table_name}.id = %d" % project.id Chris@0: end Chris@441: project_clauses.any? ? project_clauses.join(' AND ') : nil Chris@0: end Chris@0: Chris@0: def statement Chris@0: # filters clauses Chris@0: filters_clauses = [] Chris@0: filters.each_key do |field| Chris@0: next if field == "subproject_id" Chris@0: v = values_for(field).clone Chris@0: next unless v and !v.empty? Chris@0: operator = operator_for(field) Chris@441: Chris@0: # "me" value subsitution Chris@0: if %w(assigned_to_id author_id watcher_id).include?(field) Chris@909: if v.delete("me") Chris@909: if User.current.logged? Chris@909: v.push(User.current.id.to_s) Chris@909: v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id' Chris@909: else Chris@909: v.push("0") Chris@909: end Chris@909: end Chris@0: end Chris@441: Chris@1115: if field == 'project_id' Chris@1115: if v.delete('mine') Chris@1115: v += User.current.memberships.map(&:project_id).map(&:to_s) Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: if field =~ /cf_(\d+)$/ Chris@0: # custom field Chris@909: filters_clauses << sql_for_custom_field(field, operator, v, $1) Chris@909: elsif respond_to?("sql_for_#{field}_field") Chris@909: # specific statement Chris@909: filters_clauses << send("sql_for_#{field}_field", field, operator, v) Chris@0: else Chris@0: # regular field Chris@909: filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')' Chris@0: end Chris@0: end if filters and valid? Chris@441: Chris@441: filters_clauses << project_statement Chris@441: filters_clauses.reject!(&:blank?) Chris@441: Chris@441: filters_clauses.any? ? filters_clauses.join(' AND ') : nil Chris@0: end Chris@441: Chris@0: # Returns the issue count Chris@0: def issue_count Chris@909: Issue.visible.count(:include => [:status, :project], :conditions => statement) Chris@0: rescue ::ActiveRecord::StatementInvalid => e Chris@0: raise StatementInvalid.new(e.message) Chris@0: end Chris@441: Chris@0: # Returns the issue count by group or nil if query is not grouped Chris@0: def issue_count_by_group Chris@0: r = nil Chris@0: if grouped? Chris@0: begin Chris@1115: # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value Chris@441: r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement) Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: r = {nil => issue_count} Chris@0: end Chris@0: c = group_by_column Chris@0: if c.is_a?(QueryCustomFieldColumn) Chris@0: r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h} Chris@0: end Chris@0: end Chris@0: r Chris@0: rescue ::ActiveRecord::StatementInvalid => e Chris@0: raise StatementInvalid.new(e.message) Chris@0: end Chris@441: Chris@0: # Returns the issues Chris@0: # Valid options are :order, :offset, :limit, :include, :conditions Chris@0: def issues(options={}) Chris@0: order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',') Chris@0: order_option = nil if order_option.blank? Chris@441: Chris@1115: issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq, Chris@909: :conditions => statement, Chris@0: :order => order_option, Chris@1115: :joins => joins_for_order_statement(order_option), Chris@0: :limit => options[:limit], Chris@0: :offset => options[:offset] Chris@1115: Chris@1115: if has_column?(:spent_hours) Chris@1115: Issue.load_visible_spent_hours(issues) Chris@1115: end Chris@1115: if has_column?(:relations) Chris@1115: Issue.load_visible_relations(issues) Chris@1115: end Chris@1115: issues Chris@1115: rescue ::ActiveRecord::StatementInvalid => e Chris@1115: raise StatementInvalid.new(e.message) Chris@1115: end Chris@1115: Chris@1115: # Returns the issues ids Chris@1115: def issue_ids(options={}) Chris@1115: order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',') Chris@1115: order_option = nil if order_option.blank? Chris@1115: Chris@1115: Issue.visible.scoped(:conditions => options[:conditions]).scoped(:include => ([:status, :project] + (options[:include] || [])).uniq, Chris@1115: :conditions => statement, Chris@1115: :order => order_option, Chris@1115: :joins => joins_for_order_statement(order_option), Chris@1115: :limit => options[:limit], Chris@1115: :offset => options[:offset]).find_ids Chris@0: rescue ::ActiveRecord::StatementInvalid => e Chris@0: raise StatementInvalid.new(e.message) Chris@0: end Chris@0: Chris@0: # Returns the journals Chris@0: # Valid options are :order, :offset, :limit Chris@0: def journals(options={}) Chris@441: Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}], Chris@0: :conditions => statement, Chris@0: :order => options[:order], Chris@0: :limit => options[:limit], Chris@0: :offset => options[:offset] Chris@0: rescue ::ActiveRecord::StatementInvalid => e Chris@0: raise StatementInvalid.new(e.message) Chris@0: end Chris@441: Chris@0: # Returns the versions Chris@0: # Valid options are :conditions Chris@0: def versions(options={}) Chris@909: Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement Chris@0: rescue ::ActiveRecord::StatementInvalid => e Chris@0: raise StatementInvalid.new(e.message) Chris@0: end Chris@441: Chris@909: def sql_for_watcher_id_field(field, operator, value) Chris@909: db_table = Watcher.table_name Chris@909: "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " + Chris@909: sql_for_field(field, '=', value, db_table, 'user_id') + ')' Chris@909: end Chris@909: Chris@909: def sql_for_member_of_group_field(field, operator, value) Chris@909: if operator == '*' # Any group Chris@909: groups = Group.all Chris@909: operator = '=' # Override the operator since we want to find by assigned_to Chris@909: elsif operator == "!*" Chris@909: groups = Group.all Chris@909: operator = '!' # Override the operator since we want to find by assigned_to Chris@909: else Chris@909: groups = Group.find_all_by_id(value) Chris@909: end Chris@909: groups ||= [] Chris@909: Chris@909: members_of_groups = groups.inject([]) {|user_ids, group| Chris@909: if group && group.user_ids.present? Chris@909: user_ids << group.user_ids Chris@909: end Chris@909: user_ids.flatten.uniq.compact Chris@909: }.sort.collect(&:to_s) Chris@909: Chris@909: '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')' Chris@909: end Chris@909: Chris@909: def sql_for_assigned_to_role_field(field, operator, value) Chris@909: case operator Chris@909: when "*", "!*" # Member / Not member Chris@909: sw = operator == "!*" ? 'NOT' : '' Chris@909: nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : '' Chris@909: "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" + Chris@909: " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))" Chris@909: when "=", "!" Chris@1115: role_cond = value.any? ? Chris@909: "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" : Chris@909: "1=0" Chris@1115: Chris@909: sw = operator == "!" ? 'NOT' : '' Chris@909: nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : '' Chris@909: "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" + Chris@909: " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))" Chris@909: end Chris@909: end Chris@909: Chris@1115: def sql_for_is_private_field(field, operator, value) Chris@1115: op = (operator == "=" ? 'IN' : 'NOT IN') Chris@1115: va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',') Chris@1115: Chris@1115: "#{Issue.table_name}.is_private #{op} (#{va})" Chris@1115: end Chris@1115: Chris@1115: def sql_for_relations(field, operator, value, options={}) Chris@1115: relation_options = IssueRelation::TYPES[field] Chris@1115: return relation_options unless relation_options Chris@1115: Chris@1115: relation_type = field Chris@1115: join_column, target_join_column = "issue_from_id", "issue_to_id" Chris@1115: if relation_options[:reverse] || options[:reverse] Chris@1115: relation_type = relation_options[:reverse] || relation_type Chris@1115: join_column, target_join_column = target_join_column, join_column Chris@1115: end Chris@1115: Chris@1115: sql = case operator Chris@1115: when "*", "!*" Chris@1115: op = (operator == "*" ? 'IN' : 'NOT IN') Chris@1115: "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}')" Chris@1115: when "=", "!" Chris@1115: op = (operator == "=" ? 'IN' : 'NOT IN') Chris@1115: "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})" Chris@1115: when "=p", "=!p", "!p" Chris@1115: op = (operator == "!p" ? 'NOT IN' : 'IN') Chris@1115: comp = (operator == "=!p" ? '<>' : '=') Chris@1115: "#{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 = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})" Chris@1115: end Chris@1115: Chris@1115: if relation_options[:sym] == field && !options[:reverse] Chris@1115: sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)] Chris@1115: sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ") Chris@1115: else Chris@1115: sql Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: IssueRelation::TYPES.keys.each do |relation_type| Chris@1115: alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations Chris@1115: end Chris@1115: Chris@0: private Chris@441: Chris@909: def sql_for_custom_field(field, operator, value, custom_field_id) Chris@909: db_table = CustomValue.table_name Chris@909: db_field = 'value' Chris@1115: filter = @available_filters[field] Chris@1115: return nil unless filter Chris@1115: if filter[:format] == 'user' Chris@1115: if value.delete('me') Chris@1115: value.push User.current.id.to_s Chris@1115: end Chris@1115: end Chris@1115: not_in = nil Chris@1115: if operator == '!' Chris@1115: # Makes ! operator work for custom fields with multiple values Chris@1115: operator = '=' Chris@1115: not_in = 'NOT' Chris@1115: end Chris@1115: customized_key = "id" Chris@1115: customized_class = Issue Chris@1115: if field =~ /^(.+)\.cf_/ Chris@1115: assoc = $1 Chris@1115: customized_key = "#{assoc}_id" Chris@1115: customized_class = Issue.reflect_on_association(assoc.to_sym).klass.base_class rescue nil Chris@1115: raise "Unknown Issue association #{assoc}" unless customized_class Chris@1115: end Chris@1115: "#{Issue.table_name}.#{customized_key} #{not_in} IN (SELECT #{customized_class.table_name}.id FROM #{customized_class.table_name} 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} WHERE " + Chris@909: sql_for_field(field, operator, value, db_table, db_field, true) + ')' Chris@909: end Chris@909: Chris@0: # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+ Chris@0: def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false) Chris@0: sql = '' Chris@0: case operator Chris@0: when "=" Chris@245: if value.any? Chris@909: case type_for(field) Chris@909: when :date, :date_past Chris@909: sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil)) Chris@909: when :integer Chris@1115: if is_custom_filter Chris@1115: sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) = #{value.first.to_i})" Chris@1115: else Chris@1115: sql = "#{db_table}.#{db_field} = #{value.first.to_i}" Chris@1115: end Chris@909: when :float Chris@1115: if is_custom_filter Chris@1115: sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5})" Chris@1115: else Chris@1115: sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}" Chris@1115: end Chris@909: else Chris@909: sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" Chris@909: end Chris@245: else Chris@245: # IN an empty set Chris@245: sql = "1=0" Chris@245: end Chris@0: when "!" Chris@245: if value.any? Chris@245: sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))" Chris@245: else Chris@245: # NOT IN an empty set Chris@245: sql = "1=1" Chris@245: end Chris@0: when "!*" Chris@0: sql = "#{db_table}.#{db_field} IS NULL" Chris@0: sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter Chris@0: when "*" Chris@0: sql = "#{db_table}.#{db_field} IS NOT NULL" Chris@0: sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter Chris@0: when ">=" Chris@909: if [:date, :date_past].include?(type_for(field)) Chris@909: sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil) Chris@909: else Chris@909: if is_custom_filter Chris@1115: sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f})" Chris@909: else Chris@909: sql = "#{db_table}.#{db_field} >= #{value.first.to_f}" Chris@909: end Chris@909: end Chris@0: when "<=" Chris@909: if [:date, :date_past].include?(type_for(field)) Chris@909: sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil)) Chris@909: else Chris@909: if is_custom_filter Chris@1115: sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f})" Chris@909: else Chris@909: sql = "#{db_table}.#{db_field} <= #{value.first.to_f}" Chris@909: end Chris@909: end Chris@909: when "><" Chris@909: if [:date, :date_past].include?(type_for(field)) Chris@909: sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil)) Chris@909: else Chris@909: if is_custom_filter Chris@1115: sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f})" Chris@909: else Chris@909: sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}" Chris@909: end Chris@909: end Chris@0: when "o" Chris@1115: sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id" Chris@0: when "c" Chris@1115: sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id" Chris@1115: when ">t-" Chris@1115: # >= today - n days Chris@1115: sql = relative_date_clause(db_table, db_field, - value.first.to_i, nil) Chris@0: when "t+" Chris@1115: # >= today + n days Chris@909: sql = relative_date_clause(db_table, db_field, value.first.to_i, nil) Chris@0: when "= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week) Chris@909: sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6) Chris@0: when "~" Chris@0: sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'" Chris@0: when "!~" Chris@0: sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'" Chris@909: else Chris@909: raise "Unknown query operator #{operator}" Chris@0: end Chris@441: Chris@0: return sql Chris@0: end Chris@441: Chris@1115: def add_custom_fields_filters(custom_fields, assoc=nil) Chris@1115: return unless custom_fields.present? Chris@0: @available_filters ||= {} Chris@441: Chris@0: custom_fields.select(&:is_filter?).each do |field| Chris@0: case field.field_format Chris@0: when "text" Chris@0: options = { :type => :text, :order => 20 } Chris@0: when "list" Chris@0: options = { :type => :list_optional, :values => field.possible_values, :order => 20} Chris@0: when "date" Chris@0: options = { :type => :date, :order => 20 } Chris@0: when "bool" Chris@0: options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 } Chris@909: when "int" Chris@909: options = { :type => :integer, :order => 20 } Chris@909: when "float" Chris@909: options = { :type => :float, :order => 20 } Chris@441: when "user", "version" Chris@441: next unless project Chris@1115: values = field.possible_values_options(project) Chris@1115: if User.current.logged? && field.field_format == 'user' Chris@1115: values.unshift ["<< #{l(:label_me)} >>", "me"] Chris@1115: end Chris@1115: options = { :type => :list_optional, :values => values, :order => 20} Chris@0: else Chris@0: options = { :type => :string, :order => 20 } Chris@0: end Chris@1115: filter_id = "cf_#{field.id}" Chris@1115: filter_name = field.name Chris@1115: if assoc.present? Chris@1115: filter_id = "#{assoc}.#{filter_id}" Chris@1115: filter_name = l("label_attribute_of_#{assoc}", :name => filter_name) Chris@1115: end Chris@1115: @available_filters[filter_id] = options.merge({ Chris@1115: :name => filter_name, Chris@1115: :format => field.field_format, Chris@1115: :field => field Chris@1115: }) Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: def add_associations_custom_fields_filters(*associations) Chris@1115: fields_by_class = CustomField.where(:is_filter => true).group_by(&:class) Chris@1115: associations.each do |assoc| Chris@1115: association_klass = Issue.reflect_on_association(assoc).klass Chris@1115: fields_by_class.each do |field_class, fields| Chris@1115: if field_class.customized_class <= association_klass Chris@1115: add_custom_fields_filters(fields, assoc) Chris@1115: end Chris@1115: end Chris@0: end Chris@0: end Chris@441: Chris@0: # Returns a SQL clause for a date or datetime field. Chris@909: def date_clause(table, field, from, to) Chris@0: s = [] Chris@0: if from Chris@909: from_yesterday = from - 1 Chris@1115: from_yesterday_time = Time.local(from_yesterday.year, from_yesterday.month, from_yesterday.day) Chris@1115: if self.class.default_timezone == :utc Chris@1115: from_yesterday_time = from_yesterday_time.utc Chris@1115: end Chris@1115: s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_time.end_of_day)]) Chris@0: end Chris@0: if to Chris@1115: to_time = Time.local(to.year, to.month, to.day) Chris@1115: if self.class.default_timezone == :utc Chris@1115: to_time = to_time.utc Chris@1115: end Chris@1115: s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_time.end_of_day)]) Chris@0: end Chris@0: s.join(' AND ') Chris@0: end Chris@909: Chris@909: # Returns a SQL clause for a date or datetime field using relative dates. Chris@909: def relative_date_clause(table, field, days_from, days_to) Chris@909: date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil)) Chris@909: end Chris@1115: Chris@1115: # Additional joins required for the given sort options Chris@1115: def joins_for_order_statement(order_options) Chris@1115: joins = [] Chris@1115: Chris@1115: if order_options Chris@1115: if order_options.include?('authors') Chris@1115: joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{Issue.table_name}.author_id" Chris@1115: end Chris@1115: order_options.scan(/cf_\d+/).uniq.each do |name| Chris@1115: column = available_columns.detect {|c| c.name.to_s == name} Chris@1115: join = column && column.custom_field.join_for_order_statement Chris@1115: if join Chris@1115: joins << join Chris@1115: end Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: joins.any? ? joins.join(' ') : nil Chris@1115: end Chris@0: end