Module: Card::Query::SqlStatement::Order

Included in:
Card::Query::SqlStatement
Defined in:
card/lib/card/query/sql_statement/order.rb

Overview

build ORDER BY clause

Instance Method Summary collapse

Instance Method Details

#orderObject



19
20
21
22
23
24
# File 'card/lib/card/query/sql_statement/order.rb', line 19

def order
  full_syntax do
    dirs = order_directives
    "ORDER BY #{dirs.join ', '}" if dirs.present?
  end
end

#order_asObject



51
52
53
54
55
56
# File 'card/lib/card/query/sql_statement/order.rb', line 51

def order_as
  field = yield
  return field unless (as = @mods[:sort_as])

  "CAST(#{field} AS #{cast_type(safe_sql(as))})"
end

#order_dir(order_key, index) ⇒ Object



58
59
60
61
62
63
64
65
# File 'card/lib/card/query/sql_statement/order.rb', line 58

def order_dir order_key, index
  dir = @mods[:sort_dir] || @mods[:dir] # dir is DEPRECATED
  if dir.blank?
    DEFAULT_ORDER_DIRS[order_key.to_sym] || "asc"
  else
    safe_sql Array.wrap(dir)[index]
  end
end

#order_directive(order_key, index) ⇒ Object



35
36
37
38
39
# File 'card/lib/card/query/sql_statement/order.rb', line 35

def order_directive order_key, index
  field = order_field order_key
  @fields += ", #{field}"
  "#{field} #{order_dir order_key, index}"
end

#order_directivesObject



26
27
28
29
30
31
32
33
# File 'card/lib/card/query/sql_statement/order.rb', line 26

def order_directives
  sort_mod = @mods[:sort_by] || @mods[:sort]
  return if sort_mod.blank?

  Array.wrap(sort_mod).map.with_index do |order_key, index|
    order_directive order_key, index
  end
end

#order_field(order_key) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'card/lib/card/query/sql_statement/order.rb', line 41

def order_field order_key
  order_as do
    if (field = ORDER_MAP[order_key])
      "#{@query.table_alias}.#{field}"
    else
      safe_sql order_key
    end
  end
end