aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--lib/arel/insert_manager.rb4
-rw-r--r--lib/arel/nodes/insert_statement.rb7
-rw-r--r--lib/arel/visitors/to_sql.rb8
-rw-r--r--test/test_insert_manager.rb23
4 files changed, 39 insertions, 3 deletions
diff --git a/lib/arel/insert_manager.rb b/lib/arel/insert_manager.rb
index b5d2aeb3a4..8839dd8181 100644
--- a/lib/arel/insert_manager.rb
+++ b/lib/arel/insert_manager.rb
@@ -13,6 +13,10 @@ module Arel
def columns; @ast.columns end
def values= val; @ast.values = val; end
+ def select select
+ @ast.select = select
+ end
+
def insert fields
return if fields.empty?
diff --git a/lib/arel/nodes/insert_statement.rb b/lib/arel/nodes/insert_statement.rb
index ec8870a1c2..ada4fcc562 100644
--- a/lib/arel/nodes/insert_statement.rb
+++ b/lib/arel/nodes/insert_statement.rb
@@ -1,29 +1,32 @@
module Arel
module Nodes
class InsertStatement < Arel::Nodes::Node
- attr_accessor :relation, :columns, :values
+ attr_accessor :relation, :columns, :values, :select
def initialize
super()
@relation = nil
@columns = []
@values = nil
+ @select = nil
end
def initialize_copy other
super
@columns = @columns.clone
@values = @values.clone if @values
+ @select = @select.clone if @select
end
def hash
- [@relation, @columns, @values].hash
+ [@relation, @columns, @values, @select].hash
end
def eql? other
self.class == other.class &&
self.relation == other.relation &&
self.columns == other.columns &&
+ self.select == other.select &&
self.values == other.values
end
alias :== :eql?
diff --git a/lib/arel/visitors/to_sql.rb b/lib/arel/visitors/to_sql.rb
index e1b46eb6e6..22f7943ab9 100644
--- a/lib/arel/visitors/to_sql.rb
+++ b/lib/arel/visitors/to_sql.rb
@@ -127,7 +127,13 @@ module Arel
}.join ', '})"
end
- maybe_visit o.values, collector
+ if o.values
+ maybe_visit o.values, collector
+ elsif o.select
+ maybe_visit o.select, collector
+ else
+ collector
+ end
end
def visit_Arel_Nodes_Exists o, collector
diff --git a/test/test_insert_manager.rb b/test/test_insert_manager.rb
index 9e4cc9d05e..4e82ca34c0 100644
--- a/test/test_insert_manager.rb
+++ b/test/test_insert_manager.rb
@@ -139,5 +139,28 @@ module Arel
}
end
end
+
+ describe "select" do
+
+ it "accepts a select query in place of a VALUES clause" do
+ table = Table.new :users
+
+ manager = Arel::InsertManager.new Table.engine
+ manager.into table
+
+ select = Arel::SelectManager.new Table.engine
+ select.project Arel.sql('1')
+ select.project Arel.sql('"aaron"')
+
+ manager.select select
+ manager.columns << table[:id]
+ manager.columns << table[:name]
+ manager.to_sql.must_be_like %{
+ INSERT INTO "users" ("id", "name") (SELECT 1, "aaron")
+ }
+ end
+
+ end
+
end
end