Skip to content

Commit 0a180ae

Browse files
authored
Added support for Nulls first and last (#1385)
1 parent 6208f71 commit 0a180ae

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
#### Added
44

5+
- [#1385](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1385) Added support for Nulls first and last.
6+
57
#### Changed
68

79
- [#1381](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1381) Fix `change_column` to preserve old column attributes.

lib/arel/visitors/sqlserver.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,25 @@ def visit_Arel_Nodes_WithRecursive(o, collector)
271271
collect_ctes(o.children, collector)
272272
end
273273

274+
def visit_Arel_Nodes_NullsFirst(o, collector)
275+
collector << sql_to_order_nulls_position(o, is_first: true)
276+
collector << ", "
277+
visit o.expr, collector
278+
end
279+
280+
def visit_Arel_Nodes_NullsLast(o, collector)
281+
collector << sql_to_order_nulls_position(o, is_first: false)
282+
collector << ", "
283+
visit o.expr, collector
284+
end
285+
286+
def sql_to_order_nulls_position(o, is_first:)
287+
order_column = "".dup
288+
visit o.expr.expr, order_column
289+
290+
"(CASE WHEN #{order_column} IS NULL THEN #{is_first ? 0 : 1} ELSE #{is_first ? 1 : 0} END)"
291+
end
292+
274293
# SQLServer ToSql/Visitor (Additions)
275294

276295
def visit_Arel_Nodes_SelectStatement_SQLServer_Lock(collector, options = {})

test/cases/order_test_sqlserver.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
require "cases/helper_sqlserver"
44
require "models/post"
5+
require "models/book"
56

67
class OrderTestSQLServer < ActiveRecord::TestCase
78
fixtures :posts
@@ -150,4 +151,24 @@ class OrderTestSQLServer < ActiveRecord::TestCase
150151
sql = Post.order(:id).order("posts.id ASC").to_sql
151152
assert_equal "SELECT [posts].* FROM [posts] ORDER BY [posts].[id] ASC, posts.id ASC", sql
152153
end
154+
155+
it "support nulls first" do
156+
Book.delete_all
157+
Book.create!(title: "Hyperion")
158+
Book.create!(title: nil)
159+
Book.create!(title: "Dune")
160+
161+
books = Book.order(Book.arel_table[:title].desc.nulls_first)
162+
assert_equal([nil, "Hyperion", "Dune"], books.map(&:title))
163+
end
164+
165+
it "support nulls last" do
166+
Book.delete_all
167+
Book.create!(title: "Hyperion")
168+
Book.create!(title: nil)
169+
Book.create!(title: "Dune")
170+
171+
books = Book.order(Book.arel_table[:title].desc.nulls_last)
172+
assert_equal(["Hyperion", "Dune", nil], books.map(&:title))
173+
end
153174
end

0 commit comments

Comments
 (0)