Skip to content

Commit 6ca59c1

Browse files
Jeskokares
authored andcommitted
SELECT DISTINCT clause with ORDER BY for MSSQL
SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause. Partially fixes #437
1 parent cbb5a32 commit 6ca59c1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

lib/arjdbc/mssql/adapter.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,32 @@ def rename_column(table_name, column_name, new_column_name)
360360
execute "EXEC sp_rename '#{table_name}.#{column_name}', '#{new_column_name}', 'COLUMN'"
361361
end
362362

363+
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
364+
# MSSQL requires the ORDER BY columns in the select list for distinct queries.
365+
def distinct(columns, order_by)
366+
"DISTINCT #{columns_for_distinct(columns, order_by)}"
367+
end
368+
369+
def columns_for_distinct(columns, orders)
370+
return columns if orders.blank?
371+
372+
# construct a clean list of column names from the ORDER BY clause,
373+
# removing any ASC/DESC modifiers
374+
order_columns = [ orders ]; order_columns.flatten! # AR 3.x vs 4.x
375+
order_columns.map! do |column|
376+
column = column.to_sql unless column.is_a?(String) # handle AREL node
377+
column.split(',').collect!{ |s| s.split.first }
378+
end.flatten!
379+
order_columns.reject!(&:blank?)
380+
order_columns = order_columns.zip(0...order_columns.size).to_a
381+
order_columns = order_columns.map{ |s, i| "#{s}" }
382+
383+
columns = [ columns ]; columns.flatten!
384+
columns.push( *order_columns ).join(', ')
385+
# return a DISTINCT clause that's distinct on the columns we want but
386+
# includes all the required columns for the ORDER BY to work properly
387+
end
388+
363389
# @override
364390
def change_column(table_name, column_name, type, options = {})
365391

0 commit comments

Comments
 (0)