Sha256: 6db0dab47415d6334cc6749b4345e1b35cfe93d1554c2e1cc26f7169327f0817

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

require "query_helper/invalid_query_error"

class QueryHelper
  class SqlFilter

    attr_accessor :filter_values, :column_maps, :options, :qualify_filters

    def initialize(filter_values: [], column_maps: [], qualify_filters: [], options: {})
      @column_maps = column_maps
      @filter_values = filter_values
      @options = options
      @qualify_filters = qualify_filters
    end

    def create_filters
      @filters = []

      @filter_values.each do |comparate_alias, criteria|
        # Find the sql mapping if it exists
        map = @column_maps.find { |m| m.alias_name.downcase == comparate_alias.downcase }
        raise InvalidQueryError.new("cannot filter by #{comparate_alias}") unless map

        # create the filter
        @filters << QueryHelper::Filter.new(
          operator_code: criteria.keys.first,
          criterion: criteria.values.first,
          comparate: map.sql_expression,
          aggregate: map.aggregate,
          qualify_clause: aggregated_attribute?(comparate: map.sql_expression)
        )
      end
    end

    def aggregated_attribute?(comparate:)
      @options['qualify_clause'] && qualify_filters.include?(comparate)
    end

    def qualify_clauses
      @filters.select{ |f| aggregated_attribute?(comparate: f.comparate) }.map(&:sql_string)
    end

    def where_clauses
      @filters.select{ |f| f.aggregate == false && !f.qualify_clause }.map(&:sql_string)
    end

    def having_clauses
      @filters.select{ |f| f.aggregate == true }.map(&:sql_string)
    end

    def bind_variables
      Hash[@filters.collect { |f| [f.bind_variable, f.criterion] }]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
query_helper-0.3.8 lib/query_helper/sql_filter.rb