Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord_spanner_adapter/base.rb

Constant Summary collapse

VERSION_7_1 =
Gem::Version.create "7.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._buffer_record(values, method, returning) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/activerecord_spanner_adapter/base.rb', line 160

def self._buffer_record values, method, returning
  primary_key_value =
    if primary_key.is_a? Array
      _set_composite_primary_key_values primary_key, values
    else
      _set_single_primary_key_value primary_key, values
    end

   = TableMetadata.new self, arel_table
  columns, grpc_values = _create_grpc_values_for_insert , values

  write = Google::Cloud::Spanner::V1::Mutation::Write.new(
    table: arel_table.name,
    columns: columns,
    values: [grpc_values.list_value]
  )
  mutation = Google::Cloud::Spanner::V1::Mutation.new(
    "#{method}": write
  )
  connection.current_spanner_transaction.buffer mutation

  _convert_primary_key primary_key_value, returning
end

._convert_primary_key(primary_key_value, returning) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/activerecord_spanner_adapter/base.rb', line 89

def self._convert_primary_key primary_key_value, returning
  # Rails 7.1 and higher supports composite primary keys, and therefore require the provider to return an array
  # instead of a single value in all cases. The order of the values should be equal to the order of the returning
  # columns (or the primary key if no returning columns were specified).
  return primary_key_value if ActiveRecord.gem_version < VERSION_7_1
  return primary_key_value if primary_key_value.is_a?(Array) && primary_key_value.length == 1
  return [primary_key_value] unless primary_key_value.is_a? Array

  # Re-order the returned values according to the returning columns if it is not equal to the primary key of the
  # table.
  keys = returning || primary_key
  return primary_key_value if keys == primary_key

  primary_key_values_hash = Hash[primary_key.zip(primary_key_value)]
  values = []
  keys.each do |column|
    values.append primary_key_values_hash[column]
  end
  values
end

._insert_record(values, returning = []) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/activerecord_spanner_adapter/base.rb', line 51

def self._insert_record values, returning = []
  if !(buffered_mutations? || (primary_key && values.is_a?(Hash))) || !spanner_adapter?
    return super values if ActiveRecord.gem_version < VERSION_7_1
    return super
  end

  # Mutations cannot be used in combination with a sequence, as mutations do not support a THEN RETURN clause.
  if buffered_mutations? && sequence_name
    raise StatementInvalid, "Mutations cannot be used to create records that use a sequence " \
                                 "to generate the primary key. #{self} uses #{sequence_name}."
  end

  return _buffer_record values, :insert, returning if buffered_mutations?

  _insert_record_dml values, returning
end

._insert_record_dml(values, returning) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/activerecord_spanner_adapter/base.rb', line 68

def self._insert_record_dml values, returning
  primary_key_value = _set_primary_key_value values
  if ActiveRecord::VERSION::MAJOR >= 7
    im = Arel::InsertManager.new arel_table
    im.insert(values.transform_keys { |name| arel_table[name] })
  else
    im = arel_table.compile_insert _substitute_values(values)
  end
  result = connection.insert(im, "#{self} Create", primary_key || false, primary_key_value)

  _convert_primary_key result, returning
end

._set_composite_primary_key_value(primary_key, values) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/activerecord_spanner_adapter/base.rb', line 192

def self._set_composite_primary_key_value primary_key, values
  value = values[primary_key]
  type = ActiveModel::Type::BigInteger.new

  if value.is_a? ActiveModel::Attribute
    type = value.type
    value = value.value
  end

  return value unless prefetch_primary_key?

  if value.nil?
    value = next_sequence_value
  end

  values[primary_key] =
    if ActiveRecord::VERSION::MAJOR >= 7
      ActiveModel::Attribute.from_database primary_key, value, type
    else
      value
    end

  value
end

._set_composite_primary_key_values(primary_key, values) ⇒ Object



184
185
186
187
188
189
190
# File 'lib/activerecord_spanner_adapter/base.rb', line 184

def self._set_composite_primary_key_values primary_key, values
  primary_key_value = []
  primary_key.each do |col|
    primary_key_value.append _set_composite_primary_key_value col, values
  end
  primary_key_value
end

._set_primary_key_value(values) ⇒ Object



81
82
83
84
85
86
87
# File 'lib/activerecord_spanner_adapter/base.rb', line 81

def self._set_primary_key_value values
  if primary_key.is_a? Array
    _set_composite_primary_key_values primary_key, values
  else
    _set_single_primary_key_value primary_key, values
  end
end

._set_single_primary_key_value(primary_key, values) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/activerecord_spanner_adapter/base.rb', line 217

def self._set_single_primary_key_value primary_key, values
  primary_key_value = values[primary_key] || values[primary_key.to_sym]

  return primary_key_value if sequence_name
  return primary_key_value unless prefetch_primary_key?

  if primary_key_value.nil?
    primary_key_value = next_sequence_value
    if ActiveRecord::VERSION::MAJOR >= 7
      values[primary_key] = ActiveModel::Attribute.from_database primary_key, primary_key_value,
                                                                 ActiveModel::Type::BigInteger.new
    else
      values[primary_key] = primary_key_value
    end
  end

  primary_key_value
end

._upsert_record(values, returning) ⇒ Object



110
111
112
# File 'lib/activerecord_spanner_adapter/base.rb', line 110

def self._upsert_record values, returning
  _buffer_record values, :insert_or_update, returning
end

.active_transaction?Boolean

Returns:

  • (Boolean)


247
248
249
250
# File 'lib/activerecord_spanner_adapter/base.rb', line 247

def self.active_transaction?
  current_transaction = connection.current_transaction
  !(current_transaction.nil? || current_transaction.is_a?(ConnectionAdapters::NullTransaction))
end

.buffered_mutations?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/activerecord_spanner_adapter/base.rb', line 47

def self.buffered_mutations?
  spanner_adapter? && connection&.current_spanner_transaction&.isolation == :buffered_mutations
end

.create(attributes = nil, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/activerecord_spanner_adapter/base.rb', line 32

def self.create attributes = nil, &block
  return super unless spanner_adapter?
  return super if active_transaction?

  # Only use mutations to create new records if the primary key is generated client-side.
  isolation = sequence_name ? nil : :buffered_mutations
  transaction isolation: isolation do
    return super
  end
end

.create!(attributes = nil, &block) ⇒ Object

Creates an object (or multiple objects) and saves it to the database. This method will use mutations instead of DML if there is no active transaction, or if the active transaction has been created with the option isolation: :buffered_mutations.



23
24
25
26
27
28
29
30
# File 'lib/activerecord_spanner_adapter/base.rb', line 23

def self.create! attributes = nil, &block
  return super unless spanner_adapter?
  return super if active_transaction?

  transaction isolation: :buffered_mutations do
    return super
  end
end

.delete_allObject

Deletes all records of this class. This method will use mutations instead of DML if there is no active transaction, or if the active transaction has been created with the option isolation: :buffered_mutations.



238
239
240
241
242
243
244
245
# File 'lib/activerecord_spanner_adapter/base.rb', line 238

def self.delete_all
  return super unless spanner_adapter?
  return super if active_transaction?

  transaction isolation: :buffered_mutations do
    return super
  end
end

.insert_all(_attributes, **_kwargs) ⇒ Object

Raises:

  • (NotImplementedError)


114
115
116
# File 'lib/activerecord_spanner_adapter/base.rb', line 114

def self.insert_all _attributes, **_kwargs
  raise NotImplementedError, "Cloud Spanner does not support skip_duplicates. Use insert! or upsert instead."
end

.insert_all!(attributes, returning: nil, **_kwargs) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/activerecord_spanner_adapter/base.rb', line 118

def self.insert_all! attributes, returning: nil, **_kwargs
  return super unless spanner_adapter?
  return super if active_transaction? && !buffered_mutations?

  # This might seem inefficient, but is actually not, as it is only buffering a mutation locally.
  # The mutations will be sent as one batch when the transaction is committed.
  if active_transaction?
    attributes.each do |record|
      _insert_record record
    end
  else
    transaction isolation: :buffered_mutations do
      attributes.each do |record|
        _insert_record record
      end
    end
  end
end

.spanner_adapter?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/activerecord_spanner_adapter/base.rb', line 43

def self.spanner_adapter?
  connection.adapter_name == "spanner"
end

.unwrap_attribute(attr_or_value) ⇒ Object



252
253
254
255
256
257
258
# File 'lib/activerecord_spanner_adapter/base.rb', line 252

def self.unwrap_attribute attr_or_value
  if attr_or_value.is_a? ActiveModel::Attribute
    attr_or_value.value
  else
    attr_or_value
  end
end

.upsert_all(attributes, returning: nil, unique_by: nil, **_kwargs) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/activerecord_spanner_adapter/base.rb', line 137

def self.upsert_all attributes, returning: nil, unique_by: nil, **_kwargs
  return super unless spanner_adapter?
  if active_transaction? && !buffered_mutations?
    raise NotImplementedError, "Cloud Spanner does not support upsert using DML. " \
                               "Use upsert outside a transaction block or in a transaction " \
                               "block with isolation: :buffered_mutations"
  end

  # This might seem inefficient, but is actually not, as it is only buffering a mutation locally.
  # The mutations will be sent as one batch when the transaction is committed.
  if active_transaction?
    attributes.each do |record|
      _upsert_record record, returning
    end
  else
    transaction isolation: :buffered_mutations do
      attributes.each do |record|
        _upsert_record record, returning
      end
    end
  end
end

Instance Method Details

#destroyObject

Deletes the object in the database. This method will use mutations instead of DML if there is no active transaction, or if the active transaction has been created with the option isolation: :buffered_mutations.



275
276
277
278
279
280
281
282
# File 'lib/activerecord_spanner_adapter/base.rb', line 275

def destroy
  return super unless self.class.spanner_adapter?
  return super if self.class.active_transaction?

  transaction isolation: :buffered_mutations do
    return super
  end
end

#update(attributes) ⇒ Object

Updates the given attributes of the object in the database. This method will use mutations instead of DML if there is no active transaction, or if the active transaction has been created with the option isolation: :buffered_mutations.



263
264
265
266
267
268
269
270
# File 'lib/activerecord_spanner_adapter/base.rb', line 263

def update attributes
  return super unless self.class.spanner_adapter?
  return super if self.class.active_transaction?

  transaction isolation: :buffered_mutations do
    return super
  end
end