From 5ab502a755d0031d229278b6f14123c45623dd04 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 7 Sep 2010 16:37:11 -0700 Subject: adding "as" and to_sql to count nodes --- lib/arel/attributes/attribute.rb | 6 ++++++ lib/arel/nodes/count.rb | 13 ++++++++++++- lib/arel/visitors/to_sql.rb | 4 +++- 3 files changed, 21 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/arel/attributes/attribute.rb b/lib/arel/attributes/attribute.rb index ff17d6136c..6087dc8e52 100644 --- a/lib/arel/attributes/attribute.rb +++ b/lib/arel/attributes/attribute.rb @@ -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 diff --git a/lib/arel/nodes/count.rb b/lib/arel/nodes/count.rb index b7c4b60948..1222a791bb 100644 --- a/lib/arel/nodes/count.rb +++ b/lib/arel/nodes/count.rb @@ -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 diff --git a/lib/arel/visitors/to_sql.rb b/lib/arel/visitors/to_sql.rb index 55b3259e81..38cb81717d 100644 --- a/lib/arel/visitors/to_sql.rb +++ b/lib/arel/visitors/to_sql.rb @@ -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 -- cgit v1.2.3