你能在 Rails 中获取数据库用户名、密码、数据库名称吗?

发布于 2024-07-11 17:42:43 字数 258 浏览 6 评论 0原文

我正在编写一个 rake 任务,它在 Rails/ActiveRecord 之外执行一些数据库工作。

有没有办法获取database.yml中定义的当前环境的数据库连接信息(主机、用户名、密码、数据库名称)?

我想得到它,这样我就可以用它来像这样连接......

con = Mysql.real_connect("host", "user", "pw", "current_db")

I'm writing a rake task that does some DB work outside of Rails/ActiveRecord.

Is there a way to get the DB connection info (host, username, password, DB name) for the current environment as defined in database.yml?

I'd like to get it so I can use it to connect like this...

con = Mysql.real_connect("host", "user", "pw", "current_db")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

灵芸 2024-07-18 17:42:43

在 Rails 中,您可以创建一个配置对象并从中获取必要的信息:

config   = Rails.configuration.database_configuration
host     = config[Rails.env]["host"]
database = config[Rails.env]["database"]
username = config[Rails.env]["username"]
password = config[Rails.env]["password"]

请参阅文档< /a> 用于 Rails::Configuration 了解详细信息。

这只是使用 YAML::load 从数据库配置加载配置文件 (database.yml),您可以自己使用该文件从 Rails 环境外部获取信息:

require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...

From within rails you can create a configuration object and obtain the necessary information from it:

config   = Rails.configuration.database_configuration
host     = config[Rails.env]["host"]
database = config[Rails.env]["database"]
username = config[Rails.env]["username"]
password = config[Rails.env]["password"]

See the documentation for Rails::Configuration for details.

This just uses YAML::load to load the configuration from the database configuration file (database.yml) which you can use yourself to get the information from outside the rails environment:

require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...
柳絮泡泡 2024-07-18 17:42:43

布莱恩在上面评论中的回答值得更多的曝光:

>> Rails.configuration.database_configuration[Rails.env]
=> {"encoding"=>"unicode", "username"=>"postgres", "adapter"=>"postgresql", "port"=>5432, "host"=>"localhost", "password"=>"postgres", "database"=>"mydb", "pool"=>5}

Bryan's answer in the comment above deserves a little more exposure:

>> Rails.configuration.database_configuration[Rails.env]
=> {"encoding"=>"unicode", "username"=>"postgres", "adapter"=>"postgresql", "port"=>5432, "host"=>"localhost", "password"=>"postgres", "database"=>"mydb", "pool"=>5}
输什么也不输骨气 2024-07-18 17:42:43
ActiveRecord::Base.connection_config

以散列形式返回连接配置:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, 
    :database=>DB, :pool=>POOL, :username=>USERNAME, 
    :password=>PASSWORD} 

正如 tpett 在他们的评论中所说:此解决方案考虑了合并来自 database.yml 和环境变量 DATABASE_URL< 的配置/代码>。

ActiveRecord::Base.connection_config

returns the connection configuration in a hash:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, 
    :database=>DB, :pool=>POOL, :username=>USERNAME, 
    :password=>PASSWORD} 

As tpett remarked in their comment: this solution accounts for merging the configuration from database.yml and from the environment variable DATABASE_URL.

南七夏 2024-07-18 17:42:43

从 Rails 6.1 开始,ActiveRecord::Base.connection_config 已被弃用。 较新的访问器是 ActiveRecord::Base.connection_db_config

[1] pry(main)> ActiveRecord::Base.connection_db_config
=> #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fe04ae72e58
 @configuration_hash=
  {:adapter=>"postgresql",
   :encoding=>"utf8",
   :min_messages=>"WARNING",
   :host=>"localhost",
   :username=>"postgres",
   :password=>"P@ssw0rd",
   :port=>5432,
   :database=>"myapp_development"},
 @env_name="development",
 @name="primary">

As of Rails 6.1, ActiveRecord::Base.connection_config is deprecated. The newer accessor is ActiveRecord::Base.connection_db_config

[1] pry(main)> ActiveRecord::Base.connection_db_config
=> #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fe04ae72e58
 @configuration_hash=
  {:adapter=>"postgresql",
   :encoding=>"utf8",
   :min_messages=>"WARNING",
   :host=>"localhost",
   :username=>"postgres",
   :password=>"P@ssw0rd",
   :port=>5432,
   :database=>"myapp_development"},
 @env_name="development",
 @name="primary">
金橙橙 2024-07-18 17:42:43

我认为这是最简单的解决方案。 经过一些测试(至少在 Rails 5.2 中),这将正确解析 DATABASE_URL。

 ActiveRecord::Base.configurations[Rails.env]

I think this is the simplest solution. After some testing (in Rails 5.2 at least) this will resolve DATABASE_URL correctly.

 ActiveRecord::Base.configurations[Rails.env]
宛菡 2024-07-18 17:42:43

在 Rails 6.1+ 中,您可以使用:

ActiveRecord::Base.connection_db_config.configuration_hash

这将返回包含当前环境的连接信息的哈希值:

{
  :adapter=>"postgresql",
  :encoding=>"utf8",
  :min_messages=>"WARNING",
  :host=>"localhost",
  :username=>"postgres",
  :password=>"P@ssw0rd",
  :port=>5432,
  :database=>"my_app_development"
}

In Rails 6.1+, you can use:

ActiveRecord::Base.connection_db_config.configuration_hash

This returns a hash containing the current environment's connection information:

{
  :adapter=>"postgresql",
  :encoding=>"utf8",
  :min_messages=>"WARNING",
  :host=>"localhost",
  :username=>"postgres",
  :password=>"P@ssw0rd",
  :port=>5432,
  :database=>"my_app_development"
}
秋风の叶未落 2024-07-18 17:42:43

老问题,但这是我寻找如何做到这一点的第一站之一,所以我认为这可能对其他人有帮助。 我通常在主目录中有 .my.cnf 文件。 因此,在我的database.yml配置文件中使用“parseconfig”gem和一些ERB语法意味着我拥有动态文件,我可以很好地检查源代码控制并简化部署(在我的例子中)。 另请注意常见套接字列表,这使得我可以更轻松地将应用程序移动到可能具有不同 Unix 套接字路径的不同操作系统。

<% 
    require 'parseconfig'
    c=ParseConfig.new('../../.my.cnf') %>

mysqlevn: &mysql
  adapter: mysql 
  username: <%= c.params['client']['user'] %>
  password: <%= c.params['client']['password'] %>
  host: localhost 
  socket: <%= [ 
  '/var/run/mysqld/mysqld.sock',
  '/var/lib/mysql/mysql.sock',
  '/tmp/mysqld.sock',
  '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %>

production:
  database: app_production
  <<: *mysql


development:
  database: app_development 
  <<: *mysql

# Do not set this db to the same as development or production.
test:
  database: app_test
  <<: *mysql

参考: http://effectif.com/articles/database-yml-should -签入

Old question but this was one of my first stops in looking up how to do this so I figure this may help someone else. I normally have .my.cnf files in the home directory. So using the 'parseconfig' gem and some ERB syntax in my database.yml config file means I've got dynamic file that I can feel good about checking into source control and also simplify deployments (in my case). Also note the list of common sockets, this makes it easier to move my app to different operating systems that might have a different Unix socket path.

<% 
    require 'parseconfig'
    c=ParseConfig.new('../../.my.cnf') %>

mysqlevn: &mysql
  adapter: mysql 
  username: <%= c.params['client']['user'] %>
  password: <%= c.params['client']['password'] %>
  host: localhost 
  socket: <%= [ 
  '/var/run/mysqld/mysqld.sock',
  '/var/lib/mysql/mysql.sock',
  '/tmp/mysqld.sock',
  '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %>

production:
  database: app_production
  <<: *mysql


development:
  database: app_development 
  <<: *mysql

# Do not set this db to the same as development or production.
test:
  database: app_test
  <<: *mysql

ref: http://effectif.com/articles/database-yml-should-be-checked-in

茶色山野 2024-07-18 17:42:43

我试图获取用户名和密码以便连接到 pgAdmin。 我尝试了上面的每种方法,但找不到在 Rails 7 中开发的数据库的 usernamepassword 值。

事实证明 pgAdmin 实际上并不需要用户名以及各个应用程序数据库的密码; 相反,它将向 postgres 服务器进行身份验证,因此可以访问服务器上的所有数据库。

对于出于与我类似的原因需要用户名密码的人来说,这可能会解决问题。


但这并不能解释为什么我无法获取特定(rails 7)应用程序的用户名密码。 我能想到的最好的猜测是,这是因为 Rails 7 默认使用默认凭据连接到本地数据库。

就我而言(PostgreSQL)默认使用用户名“postgres”,没有密码或密码为空。

因此,如果您签入 config/database.yml 并且开发环境引用的是 default,并且这些默认值不会列出 username 的任何内容和密码明确,它可能使用数据库的默认信用。 不过,我找不到任何方法来确认这一点,这只是我根据我在 Rails 7 的 database.yml 中看到的内容进行的怀疑,事实上 ENV 没有提供与db,并且上述所有方法都没有给出结果。

I was trying to get the username and password in order to connect to pgAdmin. I tried every method above and couldn't find the values for username and password for my database in development in rails 7.

It turns out pgAdmin didn't actually need the username and password for the individual app's database; instead, it will authenticate to the postgres server and hence have access to all databases on the server.

This may solve the problem for people needing the username and password for similar reasons to me.


But this doesn't explain why I was unable to get the username and password for my specific (rails 7) app. The best I can guess is it's because Rails 7 defaults to using default credentials to connect to the local database.

In my case (PostgreSQL) uses the username "postgres" by default with no password or a blank password.

So if you check in config/database.yml and the dev environment is referring to default, and those defaults don't list anything for username and password explicitly, it might be using your database's default creds. I couldn't find any way to confirm this though, it's merely my suspicion based on what I see in rails 7's database.yml, the fact ENV gives nothing related to the db, and that all the above methods gave no results.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文