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"
VERSION_7_2 =
Gem::Version.create "7.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._buffer_record(values, method, returning) ⇒ Object



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

def self._buffer_record values, method, returning
  primary_key_value =
    if primary_key.is_a? Array
      _set_composite_primary_key_values primary_key, values, true
    else
      _set_single_primary_key_value primary_key, values, true
    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



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/activerecord_spanner_adapter/base.rb', line 130

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 = primary_key.zip(primary_key_value).to_h
  keys.map do |column|
    primary_key_values_hash[column]
  end
end

._has_all_primary_key_values?(primary_key, values) ⇒ Boolean

Returns:

  • (Boolean)


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

def self._has_all_primary_key_values? primary_key, values
  if primary_key.is_a? Array
    all = TrueClass
    primary_key.each do |key|
      all &&= values.key? key
    end
    all
  else
    values.key? primary_key
  end
end

._insert_record(*args) ⇒ Object



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

def self._insert_record *args
  if ActiveRecord.gem_version < VERSION_7_2
    values, returning = args
  else
    _connection, values, returning = args
  end

  if _should_use_standard_insert_record? values
    return super values if ActiveRecord.gem_version < VERSION_7_1
    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

  return _buffer_record values, :insert, returning if buffered_mutations?

  _insert_record_dml values, returning
end

._insert_record_dml(values, returning) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/activerecord_spanner_adapter/base.rb', line 109

def self._insert_record_dml values, returning
  primary_key_value = _set_primary_key_value values, false
  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

._internal_insert_record(values) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/activerecord_spanner_adapter/base.rb', line 75

def self._internal_insert_record values
  if ActiveRecord.gem_version < VERSION_7_2
    _insert_record values
  else
    _insert_record nil, values
  end
end

._set_composite_primary_key_value(primary_key, values, is_mutation) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/activerecord_spanner_adapter/base.rb', line 256

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

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

  return value if is_auto_generated?(primary_key) \
    && !(is_mutation && connection.use_client_side_id_for_mutations)
  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, is_mutation) ⇒ Object



250
251
252
253
254
# File 'lib/activerecord_spanner_adapter/base.rb', line 250

def self._set_composite_primary_key_values primary_key, values, is_mutation
  primary_key.map do |col|
    _set_composite_primary_key_value col, values, is_mutation
  end
end

._set_primary_key_value(values, is_mutation) ⇒ Object



122
123
124
125
126
127
128
# File 'lib/activerecord_spanner_adapter/base.rb', line 122

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

._set_single_primary_key_value(primary_key, values, is_mutation) ⇒ Object



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/activerecord_spanner_adapter/base.rb', line 283

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

  return primary_key_value if has_auto_generated_primary_key? \
    && !(is_mutation && connection.use_client_side_id_for_mutations)
  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

._should_use_standard_insert_record?(values) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/activerecord_spanner_adapter/base.rb', line 56

def self._should_use_standard_insert_record? values
  !(buffered_mutations? || (primary_key && values.is_a?(Hash))) || !spanner_adapter?
end

._upsert_record(values, returning) ⇒ Object



149
150
151
# File 'lib/activerecord_spanner_adapter/base.rb', line 149

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

.active_transaction?Boolean

Returns:

  • (Boolean)


314
315
316
317
# File 'lib/activerecord_spanner_adapter/base.rb', line 314

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

.buffered_mutations?Boolean

Returns:

  • (Boolean)


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

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

.create(attributes = nil) ⇒ Object



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

def self.create(attributes = nil, &)
  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 = has_auto_generated_primary_key? ? nil : :buffered_mutations
  transaction isolation: isolation do
    return super
  end
end

.create!(attributes = nil) ⇒ 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.



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

def self.create!(attributes = nil, &)
  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.



305
306
307
308
309
310
311
312
# File 'lib/activerecord_spanner_adapter/base.rb', line 305

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

  transaction isolation: :buffered_mutations do
    return super
  end
end

.dml_batchObject



52
53
54
# File 'lib/activerecord_spanner_adapter/base.rb', line 52

def self.dml_batch(&)
  connection.dml_batch(&)
end

.has_auto_generated_primary_key?Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
68
69
# File 'lib/activerecord_spanner_adapter/base.rb', line 60

def self.has_auto_generated_primary_key?
  return true if sequence_name
  pk = primary_key
  if pk.is_a? Array
    return pk.any? do |col|
      columns_hash[col].auto_incremented_by_db?
    end
  end
  columns_hash[pk].auto_incremented_by_db?
end

.insert!(attributes, returning: nil, **kwargs) ⇒ Object



162
163
164
165
166
167
# File 'lib/activerecord_spanner_adapter/base.rb', line 162

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

  insert_all! [attributes], returning: returning, **kwargs
end

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



153
154
155
156
157
158
159
160
# File 'lib/activerecord_spanner_adapter/base.rb', line 153

def self.insert_all attributes, returning: nil, **_kwargs
  if active_transaction? && buffered_mutations?
    raise NotImplementedError,
          "Spanner does not support skip_duplicates for mutations. " \
          "Use a transaction that uses DML, or use insert! or upsert instead."
  end
  super
end

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



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/activerecord_spanner_adapter/base.rb', line 169

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|
      _internal_insert_record record
    end
  else
    transaction isolation: :buffered_mutations do
      attributes.each do |record|
        _internal_insert_record record
      end
    end
  end
end

.is_auto_generated?(col) ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/activerecord_spanner_adapter/base.rb', line 71

def self.is_auto_generated? col
  columns_hash[col]&.auto_incremented_by_db?
end

.spanner_adapter?Boolean

Returns:

  • (Boolean)


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

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

.unwrap_attribute(attr_or_value) ⇒ Object



319
320
321
322
323
324
325
# File 'lib/activerecord_spanner_adapter/base.rb', line 319

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(attributes, returning: nil, **kwargs) ⇒ Object



188
189
190
191
192
193
# File 'lib/activerecord_spanner_adapter/base.rb', line 188

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

  upsert_all [attributes], returning: returning, **kwargs
end

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



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

def self.upsert_all attributes, returning: nil, unique_by: 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|
      _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.



342
343
344
345
346
347
348
349
# File 'lib/activerecord_spanner_adapter/base.rb', line 342

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.



330
331
332
333
334
335
336
337
# File 'lib/activerecord_spanner_adapter/base.rb', line 330

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