Skip to content

Commit

Permalink
Rails 6: add database_exists? (#796)
Browse files Browse the repository at this point in the history
* add database_exists?
rails/rails#36471

* fix translate error to ActiveRecord::NoDatabaseError in connection creating
add "test bad connection" like other adapters
  • Loading branch information
YehudaGold committed Apr 30, 2020
1 parent 9b71375 commit fe348fa
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/active_record/connection_adapters/sqlserver_adapter.rb
Expand Up @@ -81,6 +81,12 @@ def schema_creation
SQLServer::SchemaCreation.new self
end

def self.database_exists?(config)
!!ActiveRecord::Base.sqlserver_connection(config)
rescue ActiveRecord::NoDatabaseError
false
end

def supports_ddl_transactions?
true
end
Expand Down
6 changes: 6 additions & 0 deletions lib/active_record/sqlserver_base.rb
Expand Up @@ -11,6 +11,12 @@ def sqlserver_connection(config) #:nodoc:
raise ArgumentError, "Unknown connection mode in #{config.inspect}."
end
ConnectionAdapters::SQLServerAdapter.new(nil, nil, config.merge(mode: mode))
rescue TinyTds::Error => e
if e.message.match(/database .* does not exist/i)
raise ActiveRecord::NoDatabaseError
else
raise
end
end
end
end
19 changes: 19 additions & 0 deletions test/cases/adapter_test_sqlserver.rb
Expand Up @@ -65,6 +65,25 @@ class AdapterTestSQLServer < ActiveRecord::TestCase
assert_equal 'customers', connection.send(:get_table_name, basic_select_sql)
end

it 'test bad connection' do
assert_raise ActiveRecord::NoDatabaseError do
config = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest')
ActiveRecord::Base.sqlserver_connection config
end
end

it 'test database exists returns false if database does not exist' do
config = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest')
assert_not ActiveRecord::ConnectionAdapters::SQLServerAdapter.database_exists?(config),
'expected database to not exist'
end

it 'test database exists returns true when the database exists' do
config = ActiveRecord::Base.configurations['arunit']
assert ActiveRecord::ConnectionAdapters::SQLServerAdapter.database_exists?(config),
"expected database #{config[:database]} to exist"
end

describe 'with different language' do

before do
Expand Down

0 comments on commit fe348fa

Please sign in to comment.