はじめに
Rails 6 に追加された新機能を試す第114段。 今回は、database_exists?
編です。
Rails 6 では、データベースが存在するかどうかを確認する database_exists? メソッドが追加されました。
Ruby 2.6.5, Rails 6.0.2.1 で確認しました。 (Rails 6.0.0 でこの修正が入っています。)
$ rails --version
Rails 6.0.2.1
今回は、データベースが存在するかどうかを確認するスクリプトを作って確認してみます。
Rails プロジェクトを作成する
$ rails new rails_sandbox
$ cd rails_sandbox
スクリプトを作成する
database.yml
から development:
の設定を読み取ります。
database.yml
の adapter:
の情報から対応するデータベースの Adapter を決定し、 database_exists?
メソッドを呼び出します。
Hash
を使わずに動的に adapter の情報を取得する方法がわかりませんを手抜きで調べませんでした。
ADAPTERS = {
'postgresql' => :PostgreSQLAdapter,
'mysql2' => :Mysql2Adapter,
'sqlite3' => :SQLite3Adapter
}
config = ActiveRecord::Base.configurations[:development]
adapter = ADAPTERS[config['adapter']]
puts ActiveRecord::ConnectionAdapters.const_get(adapter).database_exists?(config)
データベースが存在しない状態にする
念のため、データベースを削除しておきます。
$ bin/rails db:drop
スクリプトを実行する
スクリプトを実行すると、 false
と表示されます。
$ bin/rails runner scripts/database_exists.rb
Running via Spring preloader in process 936
false
データベースを作成してからスクリプトを実行する
データベースを作成してから、スクリプトを実行してみると、最後に true
と表示されます。
データベースを作成します。
$ bin/rails db:create
Created database 'app_development'
Created database 'app_test'
スクリプトを実行します。
$ bin/rails runner scripts/database_exists.rb
Running via Spring preloader in process 974
true
その他
database_exists?
メソッドは、 SQLite3 と他のデータベースとで、 bin/rails db:prepare
の挙動などが異ならないようにするために追加されたメソッドです。