Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add #extract, which produces ANSI SQL function EXTRACT(<field> from <…

…expr>).
  • Loading branch information...
commit 2db4ec6a28a59a3f74a4979ae5bc117e5c7573c4 1 parent a1a6fbc
Alexander Staubo authored
View
4 lib/arel/expressions.rb
@@ -19,5 +19,9 @@ def minimum
def average
Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
end
+
+ def extract field
+ Nodes::Extract.new [self], field
+ end
end
end
View
1  lib/arel/nodes.rb
@@ -36,6 +36,7 @@
# We should make Function a Unary node and deprecate the use of "aliaz"
require 'arel/nodes/function'
require 'arel/nodes/count'
+require 'arel/nodes/extract'
require 'arel/nodes/values'
require 'arel/nodes/named_function'
View
23 lib/arel/nodes/extract.rb
@@ -0,0 +1,23 @@
+module Arel
+ module Nodes
+
+ class Extract < Arel::Nodes::Unary
+ include Arel::Expression
+ include Arel::Predications
+
+ attr_accessor :field
+ attr_accessor :alias
+
+ def initialize expr, field, aliaz = nil
+ super(expr)
+ @field = field
+ @alias = aliaz && SqlLiteral.new(aliaz)
+ end
+
+ def as aliaz
+ self.alias = SqlLiteral.new(aliaz)
+ self
+ end
+ end
+ end
+end
View
6 lib/arel/visitors/dot.rb
@@ -103,6 +103,12 @@ def function o
alias :visit_Arel_Nodes_Avg :function
alias :visit_Arel_Nodes_Sum :function
+ def extract o
+ visit_edge o, "expressions"
+ visit_edge o, "alias"
+ end
+ alias :visit_Arel_Nodes_Extract :extract
+
def visit_Arel_Nodes_NamedFunction o
visit_edge o, "name"
visit_edge o, "expressions"
View
4 lib/arel/visitors/to_sql.rb
@@ -272,6 +272,10 @@ def visit_Arel_Nodes_NamedFunction o
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
end
+ def visit_Arel_Nodes_Extract o
+ "EXTRACT(#{o.field.to_s.upcase} FROM #{visit o.expr})#{o.alias ? " AS #{visit o.alias}" : ''}"
+ end
+
def visit_Arel_Nodes_Count o
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
visit x
View
19 test/nodes/test_extract.rb
@@ -0,0 +1,19 @@
+require 'helper'
+
+describe Arel::Nodes::Extract do
+ it "should extract field" do
+ table = Arel::Table.new :users
+ table[:timestamp].extract('date').to_sql.must_be_like %{
+ EXTRACT(DATE FROM "users"."timestamp")
+ }
+ end
+
+ describe "as" do
+ it 'should alias the extract' do
+ table = Arel::Table.new :users
+ table[:timestamp].extract('date').as('foo').to_sql.must_be_like %{
+ EXTRACT(DATE FROM "users"."timestamp") AS foo
+ }
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.