Skip to content

Insert into different schema using raw SQL #1357

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: 7-2-stable
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@ def column_definitions(table_name)
end

def column_definitions_sql(database, identifier)
database = "TEMPDB" if identifier.temporary_table?
schema_name = "schema_name()"

if prepared_statements
Expand All @@ -581,12 +582,8 @@ def column_definitions_sql(database, identifier)
schema_name = quote(identifier.schema) if identifier.schema.present?
end

object_id_arg = identifier.schema.present? ? "CONCAT(#{schema_name},'.',#{object_name})" : object_name

if identifier.temporary_table?
database = "TEMPDB"
object_id_arg = "CONCAT('#{database}','..',#{object_name})"
end
object_id_arg = identifier.schema.present? ? "CONCAT('.',#{schema_name},'.',#{object_name})" : "CONCAT('..',#{object_name})"
object_id_arg = "CONCAT('#{database}',#{object_id_arg})"

%{
SELECT
Expand Down
39 changes: 39 additions & 0 deletions test/cases/temp_test_sqlserver.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# frozen_string_literal: true

require "cases/helper_sqlserver"
require "models/dog"
require "models/other_dog"

class TempTestSQLServer < ActiveRecord::TestCase
# it "assert true" do
# assert true
# end

it "insert from one schema to another using raw SQL" do
arunit_connection = Dog.lease_connection
arunit2_connection = OtherDog.lease_connection

arunit_database = arunit_connection.pool.db_config.database
arunit2_database = arunit2_connection.pool.db_config.database

sql = <<~SQL
INSERT INTO #{arunit2_database}.dbo.dogs(id) SELECT id FROM #{arunit_database}.dbo.dogs
SQL

OtherDog.destroy_all

assert Dog.count, 1
assert OtherDog.count, 0

Dog.transaction do
OtherDog.transaction do
assert_nothing_raised do
arunit_connection.execute(sql)
end
end
end

assert Dog.count, 1
assert OtherDog.count, 1
end
end
Loading