- 
                Notifications
    You must be signed in to change notification settings 
- Fork 565
Closed
Description
We're hitting a bug when upgrading to Rails 7.1 and activerecord-sqlserver-adapter 7.1.11. If we call ActiveRecord::Base.connection.use_database('target_db') as the first call after establishing a connection, the call will fail with NoMethodError: undefined method 'execute' for nil:NilClass.
The root cause: The connection object exists but isn't fully established, causing sqlserver_azure? to fail when it tries to execute a query.
Reproduction
require 'bundler/inline'
gemfile do
  source 'https://rubygems.org'
  gem 'rails', '~> 7.1.0'
  gem 'activerecord-sqlserver-adapter', '~> 7.1.11'
  gem 'tiny_tds'
end
require 'active_record'
# Configure database connection
ActiveRecord::Base.establish_connection(
  adapter: 'sqlserver',
  host: 'localhost',  # Replace with your SQL Server host
  database: 'master', # Replace with your database
  username: 'sa',     # Replace with your username
  password: 'password' # Replace with your password
)
# This should trigger the bug
begin
  puts "Attempting to call use_database as first operation..."
  ActiveRecord::Base.connection.use_database('your_target_database')
  puts "Success: No error occurred"
rescue NoMethodError => e
  puts "BUG REPRODUCED: #{e.message}"
  puts "Error class: #{e.class}"
  puts "Backtrace:"
  puts e.backtrace.first(10)
end
# Workaround: Force connection establishment first
begin
  puts "\nTesting workaround - establishing connection first..."
  ActiveRecord::Base.connection.execute('SELECT 1') # calling something like ActiveRecord::Base.connection.raw_connection _also_ works
  ActiveRecord::Base.connection.use_database('your_target_database')
  puts "Workaround successful"
rescue => e
  puts "Workaround failed: #{e.message}"
endsmiller-vc