Class: Simple::SQL::Connection::Inserter

Inherits:
Object
  • Object
show all
Defined in:
lib/simple/sql/connection/insert.rb

Constant Summary collapse

CONFICT_HANDLING =
{
  nil      => "",
  :nothing => "ON CONFLICT DO NOTHING",
  :ignore  => "ON CONFLICT DO NOTHING"
}

Instance Method Summary collapse

Constructor Details

#initialize(connection, table_name, columns, on_conflict, into) ⇒ Inserter

  • table_name - the name of the table

  • columns - name of columns, as Array or Array

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simple/sql/connection/insert.rb', line 41

def initialize(connection, table_name, columns, on_conflict, into)
  expect! on_conflict => CONFICT_HANDLING.keys
  raise ArgumentError, "Cannot insert a record without attributes" if columns.empty?

  @connection = connection
  @columns = columns
  @into = into

  cols = []
  vals = []

  cols += columns
  vals += columns.each_with_index.map { |_, idx| "$#{idx + 1}" }

  timestamp_columns = @connection.reflection.timestamp_columns(table_name) - columns.map(&:to_s)

  cols += timestamp_columns
  vals += timestamp_columns.map { "now()" }

  returning = into ? "*" : "id"

  @sql = "INSERT INTO #{table_name} (#{cols.join(',')}) VALUES(#{vals.join(',')}) #{CONFICT_HANDLING[on_conflict]} RETURNING #{returning}"
end

Instance Method Details

#insert(records:) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/simple/sql/connection/insert.rb', line 65

def insert(records:)
  SQL.transaction do
    records.map do |record|
      SQL.ask @sql, *record.values_at(*@columns), into: @into
    end
  end
end