class HecksAdapters::SQLDatabase::Commands::Create::FindOrCreateReferences

Find and update, or create Reference Rows

Attributes

reference_ids[R]

Public Class Methods

new(head:, attributes:) click to toggle source
# File lib/commands/create/find_or_create_references.rb, line 9
def initialize(head:, attributes:)
  @head = head
  @attributes = attributes
  @reference_ids = {}
end

Public Instance Methods

call() click to toggle source
# File lib/commands/create/find_or_create_references.rb, line 15
def call

  find_or_create_reference
  find_or_create_references

  self
end

Private Instance Methods

find_or_create_reference() click to toggle source
# File lib/commands/create/find_or_create_references.rb, line 25
def find_or_create_reference
  @head.references.each do |reference|
    next if reference.list?
    attributes = @attributes.delete(reference.name.to_sym)
    column = Column.factory(reference)
    result = DB[column.to_table_name].first(attributes)

    @reference_ids[reference.name] = result[:id] and return if result
    id = SecureRandom.uuid
    with_id = attributes.merge!(id: id)
    DB[column.to_table_name].insert(with_id)
    @reference_ids[reference.name] = id
  end
end
find_or_create_references() click to toggle source
# File lib/commands/create/find_or_create_references.rb, line 40
def find_or_create_references
  @head.references.each do |reference|
    next unless reference.list?
    attributes = @attributes.delete(reference.name.to_sym)
    attributes.each do |attributes|
      @reference_ids[reference.name] = [] unless @reference_ids[reference.name]

      column = Column.factory(reference)
      result = DB[column.to_table_name].first(attributes)

      @reference_ids[reference.name] << result[:id] and return if result
      id = SecureRandom.uuid
      with_id = attributes.merge!(id: id)
      DB[column.to_table_name].insert(with_id)
      @reference_ids[reference.name] << id
    end
  end
end