|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "cases/helper_sqlserver" |
| 4 | + |
| 5 | +class TemporaryTableSQLServer < ActiveRecord::TestCase |
| 6 | + # setup do |
| 7 | + # @connection = ActiveRecord::Base.lease_connection |
| 8 | + # @connection.create_table(:barcodes, primary_key: "code", id: :uuid, force: true) |
| 9 | + # end |
| 10 | + # |
| 11 | + # # teardown do |
| 12 | + # # @connection.drop_table(:barcodes, if_exists: true) |
| 13 | + # # end |
| 14 | + # |
| 15 | + def test_insert_into_temporary_table |
| 16 | + ActiveSupport::Notifications.subscribe('sql.active_record') do |_name, _start, _finish, _id, payload| |
| 17 | + puts payload[:sql] |
| 18 | + end |
| 19 | + |
| 20 | + |
| 21 | + ActiveRecord::Base.with_connection do |conn| |
| 22 | + temp_table = "#temp_users" |
| 23 | + # connection.exec_query("IF OBJECT_ID('tempdb..#{temp_table}') IS NOT NULL DROP TABLE #{temp_table}") |
| 24 | + |
| 25 | + puts "Creating table" |
| 26 | + conn.exec_query("CREATE TABLE #{temp_table} (id INT IDENTITY(1,1), name NVARCHAR(100))") |
| 27 | + |
| 28 | + puts "Selecting table" |
| 29 | + result = conn.exec_query("SELECT * FROM #{temp_table}") |
| 30 | + puts "Result: #{result.to_a}" |
| 31 | + |
| 32 | + puts "Inserting into table" |
| 33 | + |
| 34 | + # ❌ This raises "Table doesn’t exist" error |
| 35 | + conn.exec_query("INSERT INTO #{temp_table} (name) VALUES ('John')") |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + # ✅ Workaround: Only runs if the table still exists in this session |
| 40 | + # conn.exec_query("IF OBJECT_ID('tempdb..#{temp_table}') IS NOT NULL INSERT INTO #{temp_table} (name) VALUES ('John')") |
| 41 | + |
| 42 | + # ✅ Workaround: raw_connection works without issue |
| 43 | + # conn.raw_connection.execute("IF OBJECT_ID('tempdb..#{temp_table}') IS NOT NULL INSERT INTO #{temp_table} (name) VALUES ('John')") |
| 44 | + |
| 45 | + puts "Selecting table again" |
| 46 | + result = conn.exec_query("SELECT * FROM #{temp_table}") |
| 47 | + puts "Result: #{result.to_a}" |
| 48 | + end |
| 49 | + end |
| 50 | +end |
0 commit comments