diff --git a/bin/start_console_production b/bin/start_console_production index 08b5d5a9..7ba895a6 100755 --- a/bin/start_console_production +++ b/bin/start_console_production @@ -266,7 +266,8 @@ main() { # Check if READONLY mode is enabled if [ "$READONLY" = "true" ]; then echo "Starting Rails console in READONLY mode..." - exec ./bin/rails console -e 'ActiveRecord::Base.connection.execute("SET default_transaction_read_only = true")' + export RAILS_READONLY=true + exec ./bin/rails console else echo "Starting Rails console in normal mode..." exec ./bin/rails console diff --git a/bin/start_console_staging b/bin/start_console_staging index 3e9513fd..0991d160 100755 --- a/bin/start_console_staging +++ b/bin/start_console_staging @@ -266,7 +266,8 @@ main() { # Check if READONLY mode is enabled if [ "$READONLY" = "true" ]; then echo "Starting Rails console in READONLY mode..." - exec ./bin/rails console -e 'ActiveRecord::Base.connection.execute("SET default_transaction_read_only = true")' + export RAILS_READONLY=true + exec ./bin/rails console else echo "Starting Rails console in normal mode..." exec ./bin/rails console diff --git a/config/initializers/readonly_mode.rb b/config/initializers/readonly_mode.rb new file mode 100644 index 00000000..1ea1ab6e --- /dev/null +++ b/config/initializers/readonly_mode.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +# Set database to readonly mode when RAILS_READONLY environment variable is set +if ENV['RAILS_READONLY'] == 'true' + Rails.application.config.after_initialize do + if defined?(Rails::Console) + puts 'Setting database connection to read-only mode...' + + # Delay execution to ensure all connections are established + at_exit do + # Ensure we have an active connection + ActiveRecord::Base.establish_connection + + # Set readonly mode at the database level + ActiveRecord::Base.connection.execute('SET SESSION default_transaction_read_only = true') + puts '✓ Database session is now in read-only mode. Any write operations will fail.' + rescue StandardError => e + puts "⚠ Warning: Could not set read-only mode: #{e.message}" + end + + # Also set it immediately if connection is already available + begin + if ActiveRecord::Base.connection_pool.connected? + ActiveRecord::Base.connection.execute('SET SESSION default_transaction_read_only = true') + puts '✓ Database session is now in read-only mode. Any write operations will fail.' + end + rescue StandardError => e + puts "⚠ Note: Will set read-only mode when console starts: #{e.message}" + end + end + end +end