|
3 | 3 | require "cases/helper_sqlserver" |
4 | 4 |
|
5 | 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 | 6 | 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 | 7 | 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 | | - |
| 8 | + conn.exec_query("CREATE TABLE #temp_users (id INT IDENTITY(1,1), name NVARCHAR(100))") |
38 | 9 |
|
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')") |
| 10 | + result = conn.exec_query("SELECT * FROM #temp_users") |
| 11 | + assert_equal 0, result.count |
41 | 12 |
|
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')") |
| 13 | + conn.exec_query("INSERT INTO #temp_users (name) VALUES ('John'), ('Doe')") |
44 | 14 |
|
45 | | - puts "Selecting table again" |
46 | | - result = conn.exec_query("SELECT * FROM #{temp_table}") |
47 | | - puts "Result: #{result.to_a}" |
| 15 | + result = conn.exec_query("SELECT * FROM #temp_users") |
| 16 | + assert_equal 2, result.count |
48 | 17 | end |
49 | 18 | end |
50 | 19 | end |
0 commit comments