forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ar_order.rb
39 lines (38 loc) · 1.68 KB
/
ar_order.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# This monkey patches rails to support proper joins
# current PR: https://github.com/rails/rails/pull/36531
module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module SchemaStatements
def columns_for_distinct(columns, orders) # :nodoc:
order_columns = orders.reject(&:blank?).map do |s|
# Convert Arel node to string
unless s.kind_of?(String)
if s.kind_of?(Arel::Nodes::Ordering)
s = s.expr
keep_order = true
end
if s.respond_to?(:to_sql)
s = s.to_sql
else # for Arel::Nodes::Attribute
engine = Arel::Table.engine
collector = Arel::Collectors::SQLString.new
collector = engine.connection.visitor.accept(s, collector)
s = collector.value
end
end
# If we haven't already removed the order clause,
# Remove any ASC/DESC modifiers
if keep_order
s
else
s.gsub(/\s+(?:ASC|DESC)\b/i, "")
.gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "")
end
end.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }
(order_columns << super).join(", ")
end
end
end
end
end