Class: Lyra::IdGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/lyra/id_generator.rb

Overview

Generates IDs for new records before event storage in event_sourcing mode.

In event_sourcing mode, we need the record ID before the event is stored (since we abort the actual database save). This class handles ID generation for different database adapters and primary key types.

Strategies:

  • PostgreSQL: Use nextval() to reserve sequence value
  • SQLite: Use max(id) + 1 (less safe for concurrent writes)
  • MySQL/Other: Hi-Lo algorithm with configurable block size
  • UUID columns: Generate SecureRandom.uuid

Class Method Summary collapse

Class Method Details

.next_id(model_class) ⇒ Integer, String

Generate the next ID for a model class

Parameters:

  • model_class (Class) —

    The ActiveRecord model class

Returns:

  • (Integer, String) —

    The generated ID



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/lyra/id_generator.rb', line 26

def next_id(model_class)
  pk_column = model_class.columns_hash[model_class.primary_key]

  case pk_column&.type
  when :uuid
    SecureRandom.uuid
  when :integer, :bigint, nil
    next_integer_id(model_class)
  else
    # Default to UUID for unknown types
    SecureRandom.uuid
  end
end