Sha256: 6d4315e44b5aae39d234a3fb5fd953d4f33d5aced77de6302a2ad754cfb3677a

Contents?: true

Size: 1.58 KB

Versions: 7

Compression:

Stored size: 1.58 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 == comparate_alias }
        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

7 entries across 7 versions & 1 rubygems

Version Path
query_helper-0.4.0 lib/query_helper/sql_filter.rb
query_helper-0.3.6 lib/query_helper/sql_filter.rb
query_helper-0.3.5 lib/query_helper/sql_filter.rb
query_helper-0.3.4 lib/query_helper/sql_filter.rb
query_helper-0.2.29 lib/query_helper/sql_filter.rb
query_helper-0.2.30 lib/query_helper/sql_filter.rb
query_helper-0.2.28 lib/query_helper/sql_filter.rb