Skip to content

Commit ab8f5c9

Browse files
authored
Merge pull request rails#50079 from tttffff/mysql_null_first_last_consistency
Arel nulls first/last implementation Mysql
2 parents 5621c93 + 059caa2 commit ab8f5c9

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,8 @@
106106
107107
*Jason Meller*
108108
109+
* Add `nulls_last` and working `desc.nulls_first` for MySQL.
110+
111+
*Tristan Fellows*
112+
109113
Please check [7-1-stable](https://github.com/rails/rails/blob/7-1-stable/activerecord/CHANGELOG.md) for previous changes.

activerecord/lib/arel/visitors/mysql.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,14 @@ def visit_Arel_Nodes_NotRegexp(o, collector)
5959
infix_value o, collector, " NOT REGEXP "
6060
end
6161

62-
# no-op
6362
def visit_Arel_Nodes_NullsFirst(o, collector)
64-
visit o.expr, collector
63+
visit(o.expr.expr, collector) << " IS NOT NULL, "
64+
visit(o.expr, collector)
65+
end
66+
67+
def visit_Arel_Nodes_NullsLast(o, collector)
68+
visit(o.expr.expr, collector) << " IS NULL, "
69+
visit(o.expr, collector)
6570
end
6671

6772
def visit_Arel_Nodes_Cte(o, collector)

activerecord/test/cases/arel/visitors/mysql_test.rb

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,31 @@ def compile(node)
154154
end
155155

156156
describe "Nodes::Ordering" do
157-
it "should no-op ascending nulls first" do
157+
it "should handle nulls first" do
158158
test = Table.new(:users)[:first_name].asc.nulls_first
159159
_(compile(test)).must_be_like %{
160-
"users"."first_name" ASC
160+
"users"."first_name" IS NOT NULL, "users"."first_name" ASC
161+
}
162+
end
163+
164+
it "should handle nulls last" do
165+
test = Table.new(:users)[:first_name].asc.nulls_last
166+
_(compile(test)).must_be_like %{
167+
"users"."first_name" IS NULL, "users"."first_name" ASC
168+
}
169+
end
170+
171+
it "should handle nulls first reversed" do
172+
test = Table.new(:users)[:first_name].asc.nulls_first.reverse
173+
_(compile(test)).must_be_like %{
174+
"users"."first_name" IS NULL, "users"."first_name" DESC
175+
}
176+
end
177+
178+
it "should handle nulls last reversed" do
179+
test = Table.new(:users)[:first_name].asc.nulls_last.reverse
180+
_(compile(test)).must_be_like %{
181+
"users"."first_name" IS NOT NULL, "users"."first_name" DESC
161182
}
162183
end
163184
end

0 commit comments

Comments
 (0)