mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
arel more nicely supports EXISTS queries
This commit is contained in:
parent
22a38c6a86
commit
dbd0140974
5 changed files with 33 additions and 14 deletions
|
@ -1,11 +1,7 @@
|
|||
module Arel
|
||||
module Nodes
|
||||
class Exists
|
||||
attr_reader :select_stmt
|
||||
|
||||
def initialize select_stmt
|
||||
@select_stmt = select_stmt
|
||||
end
|
||||
class Exists < Arel::Nodes::Function
|
||||
alias :select_stmt :expressions
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -22,6 +22,12 @@ module Arel
|
|||
self
|
||||
end
|
||||
|
||||
###
|
||||
# Produces an Arel::Nodes::Exists node
|
||||
def exists
|
||||
Arel::Nodes::Exists.new @ast
|
||||
end
|
||||
|
||||
def where_clauses
|
||||
#warn "where_clauses is deprecated" if $VERBOSE
|
||||
to_sql = Visitors::ToSql.new @engine
|
||||
|
|
|
@ -4,7 +4,7 @@ module Arel
|
|||
include Arel::Relation
|
||||
|
||||
attr_accessor :visitor
|
||||
attr_reader :ast
|
||||
attr_reader :ast, :engine
|
||||
|
||||
def initialize engine
|
||||
@engine = engine
|
||||
|
|
|
@ -62,7 +62,8 @@ module Arel
|
|||
end
|
||||
|
||||
def visit_Arel_Nodes_Exists o
|
||||
"EXISTS (#{visit o.select_stmt})"
|
||||
"EXISTS (#{visit o.select_stmt})#{
|
||||
o.alias ? " AS #{visit o.alias}" : ''}"
|
||||
end
|
||||
|
||||
def visit_Arel_Nodes_Values o
|
||||
|
|
|
@ -56,9 +56,7 @@ module Arel
|
|||
manager.project SqlLiteral.new '*'
|
||||
manager.from table
|
||||
manager.order :foo
|
||||
manager.to_sql.must_be_like %{
|
||||
SELECT * FROM "users" ORDER BY foo
|
||||
}
|
||||
manager.to_sql.must_be_like %{ SELECT * FROM "users" ORDER BY foo }
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -68,9 +66,7 @@ module Arel
|
|||
manager = Arel::SelectManager.new Table.engine
|
||||
manager.from table
|
||||
manager.group :foo
|
||||
manager.to_sql.must_be_like %{
|
||||
SELECT FROM "users" GROUP BY foo
|
||||
}
|
||||
manager.to_sql.must_be_like %{ SELECT FROM "users" GROUP BY foo }
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -130,6 +126,26 @@ module Arel
|
|||
end
|
||||
end
|
||||
|
||||
describe 'exists' do
|
||||
it 'should create an exists clause' do
|
||||
table = Table.new(:users)
|
||||
manager = Arel::SelectManager.new Table.engine, table
|
||||
manager.project SqlLiteral.new '*'
|
||||
m2 = Arel::SelectManager.new(manager.engine)
|
||||
m2.project manager.exists
|
||||
m2.to_sql.must_be_like %{ SELECT EXISTS (#{manager.to_sql}) }
|
||||
end
|
||||
|
||||
it 'can be aliased' do
|
||||
table = Table.new(:users)
|
||||
manager = Arel::SelectManager.new Table.engine, table
|
||||
manager.project SqlLiteral.new '*'
|
||||
m2 = Arel::SelectManager.new(manager.engine)
|
||||
m2.project manager.exists.as('foo')
|
||||
m2.to_sql.must_be_like %{ SELECT EXISTS (#{manager.to_sql}) AS foo }
|
||||
end
|
||||
end
|
||||
|
||||
describe 'ast' do
|
||||
it 'should return the ast' do
|
||||
table = Table.new :users
|
||||
|
|
Loading…
Reference in a new issue