Sha256: 5060591b8398d2186403c7f855891b4af7ae44977c3b358b0aa6a22afc70bb71

Contents?: true

Size: 1.42 KB

Versions: 27

Compression:

Stored size: 1.42 KB

Contents

require "query_helper/invalid_query_error"

class QueryHelper
  class SqlSort

    attr_accessor :column_maps, :select_strings

    def initialize(sort_string: "", column_maps: [])
      @sort_string = sort_string
      @column_maps = column_maps
      @select_strings = []
    end

    def parse_sort_string
      sql_strings = []
      sorts = @sort_string.split(",")
      sorts.each_with_index do |sort, index|
        sort_alias = sort.split(":")[0]
        direction = sort.split(":")[1]
        modifier = sort.split(":")[2]

        begin
          sql_expression = @column_maps.find{ |m| m.alias_name == sort_alias }.sql_expression
        rescue NoMethodError => e
          raise InvalidQueryError.new("Sorting not allowed on column '#{sort_alias}'")
        end

        if direction == "desc"
          case ActiveRecord::Base.connection.adapter_name
          when "SQLite" # SQLite is used in the test suite
            direction = "desc"
          else
            direction = "desc nulls last"
          end
        else
          direction = "asc"
        end

        case modifier
        when "lowercase"
          sql_expression = "lower(#{sql_expression})"
          # When select distincts are used, the order by clause must be included in the select clause
          @select_strings << sql_expression
        end

        sql_strings << "#{sql_expression} #{direction}"
      end

      return sql_strings
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
query_helper-0.2.19 lib/query_helper/sql_sort.rb
query_helper-0.2.18 lib/query_helper/sql_sort.rb
query_helper-0.2.17 lib/query_helper/sql_sort.rb
query_helper-0.2.16 lib/query_helper/sql_sort.rb
query_helper-0.2.15 lib/query_helper/sql_sort.rb
query_helper-0.2.14 lib/query_helper/sql_sort.rb
query_helper-0.2.13 lib/query_helper/sql_sort.rb
query_helper-0.2.12 lib/query_helper/sql_sort.rb
query_helper-0.2.11 lib/query_helper/sql_sort.rb
query_helper-0.2.10 lib/query_helper/sql_sort.rb
query_helper-0.2.9 lib/query_helper/sql_sort.rb
query_helper-0.2.8 lib/query_helper/sql_sort.rb
query_helper-0.2.7 lib/query_helper/sql_sort.rb
query_helper-0.2.6 lib/query_helper/sql_sort.rb
query_helper-0.2.5 lib/query_helper/sql_sort.rb
query_helper-0.2.4 lib/query_helper/sql_sort.rb
query_helper-0.2.3 lib/query_helper/sql_sort.rb
query_helper-0.2.2 lib/query_helper/sql_sort.rb
query_helper-0.2.1 lib/query_helper/sql_sort.rb
query_helper-0.2.0 lib/query_helper/sql_sort.rb