rails-sqlserver / activerecord-sqlserver-adapter

SQL Server Adapter For Rails
MIT License
972 stars 558 forks source link

Rails 7 insert data in table in different schema fails #1043

Closed KDGundermann closed 1 year ago

KDGundermann commented 1 year ago

Issue

Inserting data in a table with different schema fails

  class SstSchemaIdentity < ApplicationRecord
    self.table_name = "test.sst_schema_identity"
  end

  class SstSchemaIdentityTest < ActiveSupport::TestCase
    def test_insert
      r = SstSchemaIdentity.new
      r.save!
    end
  end

fails with:

Minitest::UnexpectedError: ActiveRecord::StatementInvalid: Table 'sst_schema_identity' doesn't exist
    test/models/sst_schema_identity_test.rb:13:in `test_insert'
    test/models/sst_schema_identity_test.rb:13:in `test_insert'

Expected behavior

data should be inserted in table

Actual behavior

above error

How to reproduce

ActiveRecord Schema test

Details

KDGundermann commented 1 year ago

looking at database_statements.rb :

       def query_requires_identity_insert?(sql)
          if insert_sql?(sql)
            table_name = get_table_name(sql)
            id_column = identity_columns(table_name).first

get_table_name() will return the table name WITHOUT database/schema so schema_cache will look for the table in the default schema 'dbo' where this not exist

KDGundermann commented 1 year ago

Possible fix: In database_statements.rb:query_requires_identity_insert?

change

table_name = get_table_name(sql)

to

table_name = get_raw_table_name(sql)

but then a test is failing:

Failure:
AdapterTestSQLServer::identity inserts#test_0001_return quoted table_name to #query_requires_identity_insert? when INSERT sql contains id column [/home/klaus/Projekte/activerecord-sqlserver-adapter/test/cases/adapter_test_sqlserver.rb:202]:
Expected: "funny_jokes"
  Actual: "[funny_jokes]"

Strange: the test is named return_QUOTED_table_name but is testing for the unquoted name...

mirrorspock commented 1 year ago

I have run into the exact same issue, Inserts into a different database fail.

my current workaround is to create a table in the main database with the same name.

grantlees commented 1 year ago

I have also run into this issue using gem 'activerecord-sqlserver-adapter', '7.0.1.0' with ruby 3.2.1 and rails 7.0.4.2. Is there anyone looking into a permanent fix ? Thanks

zortech1 commented 1 year ago

I just ran into this on activerecord-sqlserver-adapter 7.0.1.0

grantlees commented 1 year ago

I patched as suggested by KDGundermann, Im quite surprised this has been sitting around for so long.

aidanharan commented 1 year ago

Issue has been fixed in release v7.0.2.0