试用Rails 6上添加的一项小功能115(检查PostgreSQL数据库是否存在)

首先

尝试试用Rails 6新添的第115个功能。这次是关于检查PostgreSQL数据库是否存在的部分。
在Rails 6中,检查PostgreSQL数据库是否存在的方法有些变化。
当数据库不存在时,在执行bin/rails db:migrate时,不论PostgreSQL的区域设置是否为英语,都会出现ActiveRecord::NoDatabaseError错误。

我已在Ruby 2.6.5,Rails 6.0.2.1,Rails 5.2.4.1和PostgreSQL 12.1上进行了确认。(在Rails 6.0.0中已含有此修复)。

$ rails --version
Rails 6.0.2.1

这次,我会在Docker环境中使用日本语区域设置(ja_JP.UTF8)启动PostgreSQL,并使用bin/rails db:migrate命令来确认Rails 6.0.2.1和Rails 5.2.4.1之间的差异。

请参阅如何在 Docker 环境中使用日本语地域设置创建 PostgreSQL。

在PostgreSQL中直接确认数据库不存在。

通过 psql 命令确认数据库不存在。

$ psql app_development -U postgres
psql: エラー: サーバに接続できませんでした: FATAL:  データベース"app_development"は存在しません

执行 db:migrate

如果在不进行 db:create 操作的情况下执行 db:migrate 来检查错误,会引发 ActiveRecord::NoDatabaseError。

$ bin/rails db:migrate
rails aborted!
ActiveRecord::NoDatabaseError: FATAL:  データベース"app_development"は存在しません
/usr/local/bundle/gems/activerecord-6.0.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:50:in `rescue in postgresql_connection'

顺便提一句,如果 PostgreSQL 的区域设置为英语(en_US.UTF-8),也会出现 ActiveRecord::NoDatabaseError 错误。

$ bin/rails db:migrate
rails aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "app_development" does not exist
/usr/local/bundle/gems/activerecord-6.0.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:50:in `rescue in postgresql_connection'

只需要一个选项。
在Rails 5中:

当PostgreSQL使用ja_JP.UTF-8时,会引发PG::ConnectionBad错误。如果使用en_US.UTF-8,则会出现ActiveRecord::NoDatabaseError错误。

如果使用 ja_JP.UTF-8 :

$ bin/rails db:migrate
rails aborted!
PG::ConnectionBad: FATAL:  データベース"app_development"は存在しません
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `initialize'

如果使用en_US.UTF-8编码的话。

$ bin/rails db:migrate
rails aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "app_development" does not exist
/usr/local/bundle/gems/activerecord-5.2.4.1/lib/active_record/connection_adapters/postgresql_adapter.rb:696:in `rescue in connect'`

有什么变化?

在Rails 5中,当发生PG::ConnectionBad错误时,如果错误消息中包含”does not exist”,则会引发ActiveRecord::NoDatabaseError错误。
在Rails 6中,当发生PG::ConnectionBad错误时,如果错误消息中包含数据库名(本例中为app_development),则会引发ActiveRecord::NoDatabaseError错误。

尽管这不是准确的判断,但根据数据库名称进行判断似乎可以减少误判。

嘗試過的醬料

在中国人的母语中,以下是“参考情报”的另一种表达方式:“参考资料”。

    Make “bin/setup” works when using PostgreSQL with locales other than en locale