mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
adding "as" and to_sql to count nodes
This commit is contained in:
parent
cea486ac81
commit
5ab502a755
5 changed files with 40 additions and 2 deletions
|
@ -8,6 +8,10 @@ module Arel
|
|||
def in other
|
||||
Nodes::In.new self, other
|
||||
end
|
||||
|
||||
def count
|
||||
Nodes::Count.new [self]
|
||||
end
|
||||
end
|
||||
|
||||
class String < Attribute; end
|
||||
|
@ -17,4 +21,6 @@ module Arel
|
|||
class Float < Attribute; end
|
||||
class Integer < Attribute; end
|
||||
end
|
||||
|
||||
Attribute = Attributes::Attribute
|
||||
end
|
||||
|
|
|
@ -1,11 +1,22 @@
|
|||
module Arel
|
||||
module Nodes
|
||||
class Count
|
||||
attr_accessor :expressions, :distinct
|
||||
attr_accessor :expressions, :distinct, :alias
|
||||
|
||||
def initialize expr, distinct = false
|
||||
@expressions = expr
|
||||
@distinct = distinct
|
||||
@alias = nil
|
||||
end
|
||||
|
||||
def as aliaz
|
||||
self.alias = SqlLiteral.new(aliaz)
|
||||
self
|
||||
end
|
||||
|
||||
def to_sql
|
||||
viz = Visitors::ToSql.new Table.engine
|
||||
viz.accept self
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -64,7 +64,9 @@ module Arel
|
|||
end
|
||||
|
||||
def visit_Arel_Nodes_Count o
|
||||
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x| visit x }.join(', ')})"
|
||||
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
|
||||
visit x
|
||||
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
|
||||
end
|
||||
|
||||
def visit_Arel_Nodes_TableAlias o
|
||||
|
|
|
@ -3,6 +3,13 @@ require 'spec_helper'
|
|||
module Arel
|
||||
module Attributes
|
||||
describe 'attribute' do
|
||||
describe '#count' do
|
||||
it 'should return a count node' do
|
||||
relation = Table.new(:users)
|
||||
relation[:id].count.should be_kind_of Nodes::Count
|
||||
end
|
||||
end
|
||||
|
||||
describe '#eq' do
|
||||
it 'should return an equality node' do
|
||||
attribute = Attribute.new nil, nil, nil
|
||||
|
|
12
spec/arel/nodes/count_spec.rb
Normal file
12
spec/arel/nodes/count_spec.rb
Normal file
|
@ -0,0 +1,12 @@
|
|||
require 'spec_helper'
|
||||
|
||||
describe Arel::Nodes::Count do
|
||||
describe "as" do
|
||||
it 'should alias the count' do
|
||||
table = Arel::Table.new :users
|
||||
table[:id].count.as('foo').to_sql.should be_like %{
|
||||
COUNT("users"."id") AS foo
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue