Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force ActiveRecord to open database in read-only mode?

Is there a parameter to ActiveRecord::Base.configurations or establish_connection() that forcibly ensures NO write is possible to the database? (If it makes a difference it is a Heroku Postgres database)

An ancillary Sinatra app (using ActiveRecord 5.2) needs strictly read-only access to a Heroku Postgres database used by a primary app... eg, even if a code bug accidentally tries to write a change, we need it to fail.

The advice in several SO threads is to define a readonly? method as shown below.

It ALMOST works... with one important exception...

Although it does prevent a save or an update_attributes, it does NOT prevent an update_column from writing.

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

results:

> 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
like image 475
jpw Avatar asked Sep 12 '25 04:09

jpw


1 Answers

Unfortunately I only know the answer for Postgresql, but that appears to be what you're using.

The simple answer is (possibly in an initializer):

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

The way I use it is:

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

Here's an example use:

[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 - It will only call the SET SESSION CHARACTERISTICS.. when it connects.

like image 176
jjthrash Avatar answered Sep 14 '25 23:09

jjthrash