如何在rails中设置postgresql命令超时

Cla*_*ark 16 postgresql ruby-on-rails heroku

我正在使用heroku和heroku postgresql.如何设置db命令超时,以便在sql命令超过10秒时出现异常?

小智 20

像这样配置你的database.yml,关键位是变量hash:

defaults: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  min_messages: warning
  variables:
    statement_timeout: 5000
Run Code Online (Sandbox Code Playgroud)


小智 6

添加

ActiveRecord::Base.connection.execute('set statement_timeout to 10000')
Run Code Online (Sandbox Code Playgroud)

到文件末尾environment.rb对我来说不起作用。

有效的是添加

ActiveRecord::Base.connection.execute("SET statement_timeout = '10s'")
Run Code Online (Sandbox Code Playgroud)

到初始化文件。


小智 5

我不知道Ruby,但是在PostgreSQL中,您可以简单地运行以下命令:

SET statement_timeout = '10s'
Run Code Online (Sandbox Code Playgroud)

然后,此连接(会话)中的所有查询将对运行时进行严格限制。

您也可以在postgresql.conf中将其更改为全局默认值,甚至可以将其更改为给定数据库或给定用户的默认值,例如:

ALTER DATABASE web SET statement_timeout = '10s';
ALTER USER bad_user SET statement_timeout = '10s';
Run Code Online (Sandbox Code Playgroud)


Cla*_*ark 5

我在这里找到了一个解决方案:Ruby on Rails:如何在应用程序配置中设置数据库超时?

ActiveRecord::Base.connection.execute('set statement_timeout to 10000')
Run Code Online (Sandbox Code Playgroud)

environment.rb文件的最后.

有没有人看到更好的方法?