如何强制ActiveRecord以只读模式打开数据库?

时间:2019-01-28 04:50:59

标签: activerecord readonly

是否有ActiveRecord :: Base.configurations的参数或Establishment_connection()强制确保无法对数据库进行写操作? (如果有所作为,那就是Heroku Postgres数据库)

辅助Sinatra应用程序(使用ActiveRecord 5.2)需要严格对主应用程序使用的Heroku Postgres数据库进行只读访问...例如,即使代码错误意外地尝试编写变化,我们需要它失败。

几个SO线程中的建议是定义只读?方法如下所示。

ALMOST可以正常工作...一个重要的例外...

尽管它确实会阻止保存或update_attributes,但不会阻止update_column写入。

APP_DB_HASH = { 
  "appdb"=>
    { "adapter"=>"postgresql", 
      "encoding" => "unicode",
      "pool" => 5,
      "url"=> ENV["APP_DATABASE_URL"] },

ActiveRecord::Base.configurations["appdb"] = {
  :adapter  => APP_DB_HASH["appdb"]["adapter"],
  :encoding  => APP_DB_HASH["appdb"]["encoding"],
  :database => uri.path.gsub('/',''),
  :username => uri.user,
  :password => uri.password,
  :port => uri.port,
  :host => uri.host
}

class AppBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection configurations["appdb"]

  # THIS DOES NOT PREVENT update_column FROM WRITING TO DATABASE!
  def readonly?
    true
  end
end

class MyModel << AppBase
...
end

结果:

> rec = MyModel.first.foo
# false

> rec.update_attributes foo: true
# GOOD: exception thrown, prevents write

> rec.foo = true
> rec.save
# GOOD: exception thrown, prevents write

> rec.update_column :foo, true
# FAIL: THE 'READONLY" DATABASE GETS WRITTEN

2 个答案:

答案 0 :(得分:1)

不幸的是,我只知道Postgresql的答案,但这似乎就是您所使用的。

简单的答案是(可能在初始化程序中):

ActiveRecord::Base.connection.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")

我的使用方式是:

def with_read_only_connection(configuration)
  original_connection = ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection(configuration)
  ActiveRecord::Base.connection.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")
  yield
ensure
  ActiveRecord::Base.establish_connection(original_connection)
end

这是一个示例用法:

[5] pry(main)> with_read_only_connection(:development) do
[5] pry(main)*   User.count
[5] pry(main)* end
   (0.2ms)  SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
   (96.6ms)  SELECT COUNT(*) FROM "users"
=> 24566

[6] pry(main)> with_read_only_connection(:development) do
[6] pry(main)*   User.first.update_attribute(:first_name, "Bob")
[6] pry(main)* end
   (0.2ms)  SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
  User Load (1.9ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1
   (0.2ms)  BEGIN
  SQL (0.7ms)  UPDATE "users" SET "first_name" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["first_name", "Bob"], ["updated_at", "2019-04-06 13:14:12.270619"], ["id", 1]]
   (0.2ms)  ROLLBACK
ActiveRecord::StatementInvalid: PG::ReadOnlySqlTransaction: ERROR:  cannot execute UPDATE in a read-only transaction
: UPDATE "users" SET "first_name" = $1, "updated_at" = $2 WHERE "users"."id" = $3
from .../.bundle/ruby/2.2.0/gems/activerecord-4.2.11.1/lib/active_record/connection_adapters/postgresql_adapter.rb:602:in `exec_prepared'

NB-仅在连接时调用SET SESSION CHARACTERISTICS..

答案 1 :(得分:0)

当我尝试在只读环境中执行执行 (ActiveRecord) 操作时,我偶然发现了这个问题。过了一会儿,我意识到与其将整个连接设为只读及其会话特性(如上面方法 with_read_only_connection 中所建议的),我可以简单地将所有内容包装在一个事务中并在执行后回滚它:

ActiveRecord::Base.transaction do
  # do your thing!
  raise ActiveRecord::Rollback
end

我希望这会有所帮助。非常感谢@jjthrash,对于SET SESSION CHARACTERISTICS 的提示,我在制作时一直使用它。