Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions acceptance/cases/models/preventing_writes_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Copyright 2026 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
#
# frozen_string_literal: true

require "test_helper"
require "models/author"

module ActiveRecord
module Model
class PreventingWritesTest < SpannerAdapter::TestCase
include SpannerAdapter::Associations::TestHelper

def setup
super
@author = Author.create! name: "Original"
end

def teardown
super
Author.destroy_all
end

def test_reads_succeed_while_preventing_writes
ActiveRecord::Base.while_preventing_writes do
found = Author.find @author.id
assert_equal "Original", found.name

hinted = Author.optimizer_hints("statement_hint: @{USE_ADDITIONAL_PARALLELISM=true}").find @author.id
assert_equal "Original", hinted.name

ActiveRecord::Base.transaction isolation: :read_only do
assert_equal "Original", Author.find(@author.id).name
end
end
end

def test_mutations_and_dml_and_ddl_raise_read_only_error_without_modifying_data
ActiveRecord::Base.while_preventing_writes do
assert_raises ActiveRecord::ReadOnlyError do
Author.create! name: "Created"
end

assert_raises ActiveRecord::ReadOnlyError do
@author.update! name: "Updated"
end

assert_raises ActiveRecord::ReadOnlyError do
@author.destroy!
end

assert_raises ActiveRecord::ReadOnlyError do
Author.delete_all
end

assert_raises ActiveRecord::ReadOnlyError do
Author.where(id: @author.id).update_all name: "DmlUpdated"
end

assert_raises ActiveRecord::ReadOnlyError do
Author
.optimizer_hints("statement_hint: @{USE_ADDITIONAL_PARALLELISM=true}")
.where(id: @author.id)
.update_all name: "HintedUpdated"
end

assert_raises ActiveRecord::ReadOnlyError do
ActiveRecord::Base.connection.truncate "authors"
end

assert_raises ActiveRecord::ReadOnlyError do
ActiveRecord::Base.connection.execute_ddl "CREATE TABLE `blocked_table` (`id` INT64) PRIMARY KEY (`id`)"
end

assert_raises ActiveRecord::ReadOnlyError do
ActiveRecord::Base.transaction isolation: :pdml do
Author.where(id: @author.id).update_all name: "PdmlUpdated"
end
end
end

assert_equal [@author.id], Author.where(id: @author.id).pluck(:id)
assert_equal "Original", Author.find(@author.id).name
refute ActiveRecord::Base.connection.table_exists?("blocked_table")
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,13 @@ def internal_exec_query sql, name = "SQL", binds = [], prepare: false, async: fa

def internal_execute sql, name = "SQL", binds = [],
prepare: false, async: false, allow_retry: false # rubocop:disable Lint/UnusedMethodArgument
statement_type = sql_statement_type sql
# Call `transform` to invoke any query transformers that might have been registered.
sql = transform sql
append_request_tag_from_query_logs sql, binds

if preventing_writes? && [:dml, :ddl].include?(statement_type)
raise ActiveRecord::ReadOnlyError(
"Write query attempted while in readonly mode: #{sql}"
)
statement_type = sql_statement_type sql
if preventing_writes? && (statement_type != :dql || write_query?(sql))
ensure_writes_allowed sql
end
append_request_tag_from_query_logs sql, binds

if statement_type == :ddl
execute_ddl sql
Expand Down Expand Up @@ -162,6 +159,7 @@ def _has_pk_binding pk, binds
end

def exec_mutation mutation
ensure_writes_allowed "MUTATION (#{mutation.operation})"
@connection.current_transaction.buffer mutation
end

Expand Down Expand Up @@ -202,6 +200,7 @@ def exec_update sql, name = "SQL", binds = []
alias exec_delete exec_update

def truncate table_name, name = nil
ensure_writes_allowed "TRUNCATE #{Array(table_name).join(', ')}"
Array(table_name).each do |t|
log "TRUNCATE #{t}", name do
@connection.truncate t
Expand All @@ -210,10 +209,13 @@ def truncate table_name, name = nil
end

def write_query? sql
sql_statement_type(sql) == :dml
!READ_QUERY.match? sql
Comment thread
olavloite marked this conversation as resolved.
Dismissed
rescue ArgumentError
!READ_QUERY.match? sql.b
Comment thread
olavloite marked this conversation as resolved.
Dismissed
end

def execute_ddl statements
ensure_writes_allowed Array(statements).join("; ")
log "MIGRATION", "SCHEMA" do
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
@connection.execute_ddl statements
Expand Down Expand Up @@ -283,6 +285,8 @@ def transaction_isolation_levels
end

def begin_db_transaction
ensure_writes_allowed "BEGIN PDML" if @connection.isolation_level == :pdml

log "BEGIN" do
opts = @_spanner_begin_transaction_options || {}
@connection.begin_transaction nil, **opts
Expand Down Expand Up @@ -311,23 +315,17 @@ def begin_isolated_db_transaction isolation
opts = @_spanner_begin_transaction_options || {}
# If isolation level is specified in the options, use that instead of the default isolation level.
isolation_option = opts[:isolation] || isolation
if isolation_option.is_a? Hash
raise "Unsupported isolation level: #{isolation_option}" unless
isolation_option[:timestamp] || isolation_option[:staleness] || isolation_option[:strong]
raise "Only one option is supported. It must be one of `timestamp`, `staleness` or `strong`." \
if isolation_option.count != 1
else
raise "Unsupported isolation level: #{isolation_option}" unless
[:serializable, :repeatable_read, :read_only, :buffered_mutations, :pdml,
:fallback_to_pdml].include? isolation_option
end
validate_isolation_level! isolation_option
ensure_writes_allowed "BEGIN PDML" if isolation_option == :pdml

log "BEGIN #{isolation_option}" do
@connection.begin_transaction isolation_option, **opts.except(:isolation)
end
end

def commit_db_transaction
ensure_writes_allowed "COMMIT" if preventing_writes? && @connection.current_transaction&.mutations?

log "COMMIT" do
@connection.commit_transaction
end
Expand All @@ -339,8 +337,29 @@ def rollback_db_transaction
end
end

def ensure_writes_allowed sql # :nodoc:
return unless preventing_writes?

raise ActiveRecord::ReadOnlyError,
"Write query attempted while in readonly mode: #{sql}"
end

private

def validate_isolation_level! isolation_option
if isolation_option.is_a? Hash
unless isolation_option[:timestamp] || isolation_option[:staleness] || isolation_option[:strong]
raise "Unsupported isolation level: #{isolation_option}"
end
if isolation_option.count != 1
raise "Only one option is supported. It must be one of `timestamp`, `staleness` or `strong`."
end
elsif ![:serializable, :repeatable_read, :read_only, :buffered_mutations, :pdml,
:fallback_to_pdml].include?(isolation_option)
raise "Unsupported isolation level: #{isolation_option}"
end
end

# Translates binds to Spanner types and params.
def to_types_and_params binds # rubocop:disable Metrics/AbcSize
return [{}, {}] if binds.empty?
Expand Down Expand Up @@ -417,27 +436,45 @@ def create_delete_all_mutation arel
)
end

COMMENT_REGEX = %r{(?:--.*\n)*|/\*(?:[^*]|\*[^/])*\*/}m \
COMMENT_REGEX = %r{(?:--.*\n)|/\*(?>[^*]++|\*(?!/))*\*/} \
unless defined? ActiveRecord::ConnectionAdapters::AbstractAdapter::COMMENT_REGEX
COMMENT_REGEX = ActiveRecord::ConnectionAdapters::AbstractAdapter::COMMENT_REGEX \
if defined? ActiveRecord::ConnectionAdapters::AbstractAdapter::COMMENT_REGEX

HASH_COMMENT_REGEX = /#.*\n/
private_constant :HASH_COMMENT_REGEX

STATEMENT_HINT_REGEX = %r(@\{(?>[^}'"]++|'(?>\\.|[^'\\])*'|"(?>\\.|[^"\\])*")*\})
private_constant :STATEMENT_HINT_REGEX

private_class_method def self.build_sql_statement_regexp *parts # :nodoc:
parts = parts.map { |part| /#{part}/i }
/\A(?:[(\s]|#{COMMENT_REGEX})*#{Regexp.union(*parts)}/
parts = parts.map { |part| /#{part}\b/i }
/\A(?>(?:[(\s]|#{COMMENT_REGEX}|#{HASH_COMMENT_REGEX}|#{STATEMENT_HINT_REGEX})*)#{Regexp.union(*parts)}/
end

DDL_REGX = build_sql_statement_regexp(:create, :alter, :drop).freeze
DDL_REGX = build_sql_statement_regexp(:create, :alter, :drop, :rename, :grant, :revoke, :analyze).freeze
private_constant :DDL_REGX

DML_REGX = build_sql_statement_regexp(:insert, :delete, :update).freeze
private_constant :DML_REGX

# Mirrors ActiveRecord's DEFAULT_READ_QUERY so read-only transactions (BEGIN/COMMIT/ROLLBACK/SAVEPOINT/RELEASE)
# and read queries (including Spanner FROM/GRAPH/SHOW syntax) are permitted in read-only mode.
READ_QUERY = build_sql_statement_regexp(
:begin, :commit, :explain, :from, :graph, :release, :rollback, :savepoint, :select, :show, :with
).freeze
private_constant :READ_QUERY

def sql_statement_type sql
case sql
when DDL_REGX
match_statement_type sql
rescue ArgumentError
match_statement_type sql.b
end

def match_statement_type sql
if DDL_REGX.match? sql
:ddl
when DML_REGX
elsif DML_REGX.match? sql
:dml
else
:dql
Expand Down
28 changes: 26 additions & 2 deletions lib/active_record/connection_adapters/spanner_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,34 @@ def spanner_schema_cache
end

# Spanner Connection API
delegate :dml_batch, :dml_batch?, :start_batch_dml,
:ddl_batch, :ddl_batch?, :start_batch_ddl, :abort_batch, :run_batch,
delegate :dml_batch?, :ddl_batch?, :abort_batch,
:isolation_level, :isolation_level=, to: :@connection

def dml_batch(&)
ensure_writes_allowed "DML BATCH"
@connection.dml_batch(&)
end

def start_batch_dml
ensure_writes_allowed "START BATCH DML"
@connection.start_batch_dml
end

def ddl_batch(&)
ensure_writes_allowed "DDL BATCH"
@connection.ddl_batch(&)
end

def start_batch_ddl
ensure_writes_allowed "START BATCH DDL"
@connection.start_batch_ddl
end

def run_batch
ensure_writes_allowed "RUN BATCH"
@connection.run_batch
end

def current_spanner_transaction
@connection.current_transaction
end
Expand Down
31 changes: 19 additions & 12 deletions lib/activerecord_spanner_adapter/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,18 @@ def self._insert_record *args
return super
end

# Mutations cannot be used in combination with an auto-generated primary key,
# as mutations do not support a THEN RETURN clause.
if buffered_mutations? \
&& has_auto_generated_primary_key? \
&& !_has_all_primary_key_values?(primary_key, values) \
&& !connection.use_client_side_id_for_mutations
raise StatementInvalid, "Mutations cannot be used to create records that use an auto-generated primary key."
end
if buffered_mutations?
connection.ensure_writes_allowed "MUTATION (insert)"
# Mutations cannot be used in combination with an auto-generated primary key,
# as mutations do not support a THEN RETURN clause.
if has_auto_generated_primary_key? \
&& !_has_all_primary_key_values?(primary_key, values) \
&& !connection.use_client_side_id_for_mutations
raise StatementInvalid, "Mutations cannot be used to create records that use an auto-generated primary key."
end

return _buffer_record values, :insert, returning if buffered_mutations?
return _buffer_record values, :insert, returning
end

_insert_record_dml values, returning
end
Expand Down Expand Up @@ -199,6 +201,8 @@ def self.upsert_all attributes, returning: nil, unique_by: nil, **kwargs
end

def self._buffer_record values, method, returning
connection.ensure_writes_allowed "MUTATION (#{method})"

primary_key_value =
if primary_key.is_a? Array
_set_composite_primary_key_values primary_key, values, true
Expand All @@ -217,7 +221,7 @@ def self._buffer_record values, method, returning
mutation = Google::Cloud::Spanner::V1::Mutation.new(
"#{method}": write
)
connection.current_spanner_transaction.buffer mutation
connection.exec_mutation mutation

_convert_primary_key primary_key_value, returning
end
Expand Down Expand Up @@ -350,6 +354,7 @@ def self._create_grpc_values_for_insert metadata, values
def _update_row attribute_names, attempted_action = "update"
return super unless self.class.buffered_mutations?

self.class.connection.ensure_writes_allowed "MUTATION (update)"
if locking_enabled?
_execute_version_check attempted_action
attribute_names << self.class.locking_column
Expand All @@ -367,7 +372,7 @@ def _update_row attribute_names, attempted_action = "update"
values: [grpc_values.list_value]
)
)
self.class.connection.current_spanner_transaction.buffer mutation
self.class.connection.exec_mutation mutation
1 # Affected rows
end

Expand Down Expand Up @@ -407,6 +412,8 @@ def destroy_row

def _delete_row
return super unless self.class.buffered_mutations?

self.class.connection.ensure_writes_allowed "MUTATION (delete)"
if locking_enabled?
_execute_version_check "destroy"
end
Expand All @@ -425,7 +432,7 @@ def _delete_row
key_set: { keys: [list_value] }
)
)
self.class.connection.current_spanner_transaction.buffer mutation
self.class.connection.exec_mutation mutation
1 # Affected rows
end

Expand Down
4 changes: 4 additions & 0 deletions lib/activerecord_spanner_adapter/transaction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ def buffer mutation
@mutations << mutation
end

def mutations?
!@mutations.empty?
end

# Begins the transaction.
#
# Read-only and PDML transactions are started by executing a BeginTransaction RPC.
Expand Down
Loading
Loading