1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Allow #nulls_first and #nulls_last in PostgreSQL

When using PostgreSQL, it's useful to be able to specify NULLS FIRST and NULLS LAST on ordered columns. With this commit you can do that now, as in:

```ruby
User.arel_table[:first_name].desc.nulls_last
```
This commit is contained in:
Kevin Deisz 2019-12-31 15:59:59 -05:00
parent 3c28e79b61
commit 66b19b5dec
No known key found for this signature in database
GPG key ID: D78C2D8FB232C59C
5 changed files with 45 additions and 1 deletions

View file

@ -18,6 +18,7 @@ require "arel/nodes/false"
# unary
require "arel/nodes/unary"
require "arel/nodes/grouping"
require "arel/nodes/ordering"
require "arel/nodes/ascending"
require "arel/nodes/descending"
require "arel/nodes/unqualified_column"

View file

@ -0,0 +1,18 @@
# frozen_string_literal: true
module Arel # :nodoc: all
module Nodes
class Ordering < Unary
def nulls_first
NullsFirst.new(self)
end
def nulls_last
NullsLast.new(self)
end
end
class NullsFirst < Ordering; end
class NullsLast < Ordering; end
end
end

View file

@ -36,7 +36,6 @@ module Arel # :nodoc: all
Offset
On
OptimizerHints
Ordering
RollUp
}.each do |name|
const_set(name, Class.new(Unary))

View file

@ -82,6 +82,16 @@ module Arel # :nodoc: all
visit o.right, collector
end
def visit_Arel_Nodes_NullsFirst(o, collector)
visit o.expr, collector
collector << " NULLS FIRST"
end
def visit_Arel_Nodes_NullsLast(o, collector)
visit o.expr, collector
collector << " NULLS LAST"
end
# Used by Lateral visitor to enclose select queries in parentheses
def grouping_parentheses(o, collector)
if o.expr.is_a? Nodes::SelectStatement

View file

@ -315,6 +315,22 @@ module Arel
_(sql).must_be_like %{ "users"."name" IS DISTINCT FROM NULL }
end
end
describe "Nodes::Ordering" do
it "should handle nulls first" do
test = Table.new(:users)[:first_name].desc.nulls_first
_(compile(test)).must_be_like %{
"users"."first_name" DESC NULLS FIRST
}
end
it "should handle nulls last" do
test = Table.new(:users)[:first_name].desc.nulls_last
_(compile(test)).must_be_like %{
"users"."first_name" DESC NULLS LAST
}
end
end
end
end
end