Class: Archon::InsertIntoSelect

Inherits:
Arel::InsertManager
  • Object
show all
Defined in:
lib/archon/insert_into_select.rb

Overview

InsertIntoSelect

Extends an ARel InsertManager that will generate an ‘INSERT INTO (…) SELECT` query, which will insert data into the given table from the given selection - either an ARel SelectManager-ish, or an ActiveRecord::Relation.

It will try to determine the columns that will be inserted from the projections specified in the given selection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tableish, selectish, options = {}) ⇒ InsertIntoSelect

Returns a new instance of InsertIntoSelect.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/archon/insert_into_select.rb', line 17

def initialize(tableish, selectish, options = {})
  super()
  self.into tableish.respond_to?(:arel_table) ? tableish.arel_table : tableish
  self.select selectish.respond_to?(:arel) ? selectish.arel : selectish

  # Fetch the insert columns from the options - default to the select column names interpolated
  # into the inserted table:
  self.columns.concat options.fetch(
    :columns,
    ast.select.projections.map do |projection|
      column_name = case projection
                    when Arel::Attributes::Attribute
                      projection.name
                    when Arel::Nodes::As
                      projection.right.delete('"').to_sym
                    when Arel::Nodes::NamedFunction
                      projection.alias.delete('"').to_sym
                    when String
                      _table, name = projection.split('.') if projection['.']
                      (name || projection).delete('"').to_sym
                    else
                      raise "Don't know how to..."
                    end
      ast.relation[column_name]
    end
  )
end

Instance Attribute Details

#projectionsObject (readonly)

Returns the value of attribute projections.



16
17
18
# File 'lib/archon/insert_into_select.rb', line 16

def projections
  @projections
end