Skip to content

Commit b53f458

Browse files
committed
Use ASCII-based sorting on text columns
1 parent d7b4579 commit b53f458

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

app/api/api_v2/helpers/shared_helpers.rb

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,32 @@
11
module ApiV2::Helpers::SharedHelpers
22
extend Grape::API::Helpers
33

4+
# Use case-insensitive ASCII-based sorting on text columns
45
def apply_sort(relation, secondary_col = nil, secondary_dir = :asc)
56
attribute, direction = params[:sort].split(":")
6-
relation = relation.order("#{relation.table_name}.#{attribute} #{direction}")
7+
table_name = relation.table_name
8+
9+
primary_column = relation.connection.schema_cache.columns(table_name).find { |col| col.name == attribute }
10+
primary_sort =
11+
if primary_column && %i[ string text ].include?(primary_column.type)
12+
"LOWER(#{table_name}.#{attribute}) COLLATE \"C\" #{direction}"
13+
else
14+
"#{table_name}.#{attribute} #{direction}"
15+
end
16+
relation = relation.order(Arel.sql(primary_sort))
17+
718
if secondary_col && attribute != secondary_col
8-
relation = relation.order("#{relation.table_name}.#{secondary_col} #{secondary_dir}")
19+
secondary_column = relation.connection.schema_cache.columns(table_name).find { |col| col.name == secondary_col }
20+
secondary_sort =
21+
if secondary_column && %i[ string text ].include?(secondary_column.type)
22+
"LOWER(#{table_name}.#{secondary_col}) COLLATE \"C\" #{secondary_dir}"
23+
else
24+
"#{table_name}.#{secondary_col} #{secondary_dir}"
25+
end
26+
27+
relation = relation.order(Arel.sql(secondary_sort))
928
end
29+
1030
relation
1131
end
1232

0 commit comments

Comments
 (0)