Class: Simple::SQL::Inserter

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

Constant Summary collapse

SQL =
::Simple::SQL
CONFICT_HANDLING =
{
  nil      => "",
  :nothing => "ON CONFLICT DO NOTHING",
  :ignore  => "ON CONFLICT DO NOTHING"
}
@@inserters =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_name:, columns:, on_conflict:) ⇒ Inserter

  • table_name - the name of the table

  • columns - name of columns, as Array or Array



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/simple/sql/insert.rb', line 40

def initialize(table_name:, columns:, on_conflict:)
  @columns = columns

  cols = []
  vals = []

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

  timestamp_columns = SQL::Reflection.timestamp_columns(table_name) - columns.map(&:to_s)

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

  @sql = "INSERT INTO #{table_name} (#{cols.join(',')}) VALUES(#{vals.join(',')}) #{confict_handling(on_conflict)} RETURNING id"
end

Class Method Details

.create(table_name:, columns:, on_conflict:) ⇒ Object



32
33
34
# File 'lib/simple/sql/insert.rb', line 32

def self.create(table_name:, columns:, on_conflict:)
  @@inserters[[table_name, columns, on_conflict]] ||= new(table_name: table_name, columns: columns, on_conflict: on_conflict)
end

Instance Method Details

#confict_handling(on_conflict) ⇒ Object



63
64
65
66
67
# File 'lib/simple/sql/insert.rb', line 63

def confict_handling(on_conflict)
  CONFICT_HANDLING.fetch(on_conflict) do
    raise(ArgumentError, "Invalid on_conflict value #{on_conflict.inspect}")
  end
end

#insert(records:) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/simple/sql/insert.rb', line 69

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