Class: ActiveRecord::MassInsert::Projection

Inherits:
Statement
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/activerecord/mass_insert/projection.rb

Overview

Handles the building of the select statement that projects the JSON array

Instance Attribute Summary

Attributes inherited from Statement

#mapped_columns, #matching_columns, #model, #payload

Instance Method Summary collapse

Methods inherited from Statement

#initialize

Constructor Details

This class inherits a constructor from ActiveRecord::MassInsert::Statement

Instance Method Details

#arel_tableObject



55
56
57
# File 'lib/activerecord/mass_insert/projection.rb', line 55

def arel_table
  @arel_table ||= Arel::Table.new(table_name)
end

#column_sql_definitionsObject



43
44
45
46
47
48
49
# File 'lib/activerecord/mass_insert/projection.rb', line 43

def column_sql_definitions
  matching_columns.map do |column|
    column_for_attribute(column)
  end.map do |column_objects|
    [column_objects.name, column_objects.sql_type].join(' ')
  end
end

#selectObject



24
25
26
27
28
29
# File 'lib/activerecord/mass_insert/projection.rb', line 24

def select
  [
    *matching_columns.map { |column| arel_table[column] },
    *select_mapped_columns
  ]
end

#select_mapped_columnsObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/activerecord/mass_insert/projection.rb', line 31

def select_mapped_columns
  mapped_columns.map do |column, mapping|
    mapping = mapping.call(arel_table, column) if mapping.is_a?(Proc)
    case mapping
    when Arel::Nodes::Node
      mapping
    else
      Arel::Nodes::SqlLiteral.new(mapping.to_s)
    end
  end
end

#statementObject



14
15
16
17
18
19
20
21
22
# File 'lib/activerecord/mass_insert/projection.rb', line 14

def statement
  init_args = []
  init_args << arel_table.engine if arel_table.respond_to?(:engine)

  Arel::SelectManager.new(*init_args).tap do |select_manager|
    select_manager.project(select)
    select_manager.from(table)
  end
end

#tableObject



59
60
61
62
63
64
65
# File 'lib/activerecord/mass_insert/projection.rb', line 59

def table
  Arel::Nodes::NamedFunction.new(
    'json_to_recordset', [Arel::Nodes::SqlLiteral.new('?')]
  ).as(
    [table_name, '(', column_sql_definitions.join(', '), ')'].join
  )
end

#table_nameObject



51
52
53
# File 'lib/activerecord/mass_insert/projection.rb', line 51

def table_name
  @table_name ||= ['json_projection', SecureRandom.hex].join('_')
end