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

adding a sum node

This commit is contained in:
Aaron Patterson 2010-09-08 14:36:10 -07:00
parent ab55d3bfc1
commit 7b8944cb76
5 changed files with 39 additions and 0 deletions

View file

@ -12,6 +12,10 @@ module Arel
def count distinct = false
Nodes::Count.new [self], distinct
end
def sum
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
end
end
class String < Attribute; end

View file

@ -5,6 +5,7 @@ require 'arel/nodes/and'
require 'arel/nodes/in'
require 'arel/nodes/count'
require 'arel/nodes/sum'
require 'arel/nodes/sql_literal'
require 'arel/nodes/select_core'
require 'arel/nodes/select_statement'

12
lib/arel/nodes/sum.rb Normal file
View file

@ -0,0 +1,12 @@
module Arel
module Nodes
class Sum
attr_accessor :expressions, :alias
def initialize expr, aliaz = nil
@expressions = expr
@alias = aliaz
end
end
end
end

View file

@ -69,6 +69,11 @@ module Arel
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
end
def visit_Arel_Nodes_Sum o
"SUM(#{o.expressions.map { |x|
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
end
def visit_Arel_Nodes_TableAlias o
"#{visit o.relation} #{quote_table_name o.name}"
end

View file

@ -3,6 +3,23 @@ require 'spec_helper'
module Arel
module Attributes
describe 'attribute' do
describe '#sum' do
it 'should create a SUM node' do
relation = Table.new(:users)
relation[:id].sum.should be_kind_of Nodes::Sum
end
# FIXME: backwards compat. Is this really necessary?
it 'should set the alias to "sum_id"' do
relation = Table.new(:users)
mgr = relation.project relation[:id].sum
mgr.to_sql.should be_like %{
SELECT SUM("users"."id") AS sum_id
FROM "users"
}
end
end
describe '#count' do
it 'should return a count node' do
relation = Table.new(:users)