mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
adding maximum nodes
This commit is contained in:
parent
301dfa5a38
commit
7b122f9a33
6 changed files with 61 additions and 0 deletions
|
@ -16,6 +16,10 @@ module Arel
|
|||
def sum
|
||||
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
|
||||
end
|
||||
|
||||
def maximum
|
||||
Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
|
||||
end
|
||||
end
|
||||
|
||||
class String < Attribute; end
|
||||
|
|
|
@ -6,6 +6,7 @@ require 'arel/nodes/and'
|
|||
require 'arel/nodes/in'
|
||||
require 'arel/nodes/count'
|
||||
require 'arel/nodes/sum'
|
||||
require 'arel/nodes/max'
|
||||
require 'arel/nodes/sql_literal'
|
||||
require 'arel/nodes/select_core'
|
||||
require 'arel/nodes/select_statement'
|
||||
|
|
22
lib/arel/nodes/max.rb
Normal file
22
lib/arel/nodes/max.rb
Normal file
|
@ -0,0 +1,22 @@
|
|||
module Arel
|
||||
module Nodes
|
||||
class Max
|
||||
attr_accessor :expressions, :alias
|
||||
|
||||
def initialize expr, aliaz = nil
|
||||
@expressions = expr
|
||||
@alias = aliaz
|
||||
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
|
||||
end
|
|
@ -76,6 +76,11 @@ module Arel
|
|||
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
|
||||
end
|
||||
|
||||
def visit_Arel_Nodes_Max o
|
||||
"MAX(#{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
|
||||
|
|
|
@ -3,6 +3,23 @@ require 'spec_helper'
|
|||
module Arel
|
||||
module Attributes
|
||||
describe 'attribute' do
|
||||
describe '#maximum' do
|
||||
it 'should create a MAX node' do
|
||||
relation = Table.new(:users)
|
||||
relation[:id].maximum.should be_kind_of Nodes::Max
|
||||
end
|
||||
|
||||
# FIXME: backwards compat. Is this really necessary?
|
||||
it 'should set the alias to "max_id"' do
|
||||
relation = Table.new(:users)
|
||||
mgr = relation.project relation[:id].maximum
|
||||
mgr.to_sql.should be_like %{
|
||||
SELECT MAX("users"."id") AS max_id
|
||||
FROM "users"
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
describe '#sum' do
|
||||
it 'should create a SUM node' do
|
||||
relation = Table.new(:users)
|
||||
|
|
12
spec/arel/nodes/sum_spec.rb
Normal file
12
spec/arel/nodes/sum_spec.rb
Normal file
|
@ -0,0 +1,12 @@
|
|||
require 'spec_helper'
|
||||
|
||||
describe Arel::Nodes::Sum do
|
||||
describe "as" do
|
||||
it 'should alias the sum' do
|
||||
table = Arel::Table.new :users
|
||||
table[:id].sum.as('foo').to_sql.should be_like %{
|
||||
SUM("users"."id") AS foo
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue