Class: QueryKit::InsertQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/querykit/insert_query.rb

Overview

InsertQuery class for building INSERT SQL queries

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = nil) ⇒ InsertQuery

Initialize a new InsertQuery instance.



9
10
11
12
13
# File 'lib/querykit/insert_query.rb', line 9

def initialize(table = nil)
  @table = table
  @values = []
  @bindings = []
end

Instance Attribute Details

#bindingsObject (readonly)

Returns the value of attribute bindings.



6
7
8
# File 'lib/querykit/insert_query.rb', line 6

def bindings
  @bindings
end

#tableObject (readonly)

Returns the value of attribute table.



6
7
8
# File 'lib/querykit/insert_query.rb', line 6

def table
  @table
end

#values(data) ⇒ Object (readonly)

Set the table to insert into.



22
23
24
# File 'lib/querykit/insert_query.rb', line 22

def values
  @values
end

Instance Method Details

#into(table) ⇒ Object

Set the table to insert into.



16
17
18
19
# File 'lib/querykit/insert_query.rb', line 16

def into(table)
  @table = table
  self
end

#to_sObject



54
55
56
# File 'lib/querykit/insert_query.rb', line 54

def to_s
  to_sql
end

#to_sqlObject

Generate the SQL INSERT statement.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/querykit/insert_query.rb', line 32

def to_sql
  raise "No table specified" unless @table
  raise "No values specified" if @values.empty?

  first_row = @values.first
  columns = first_row.keys
  @bindings = @values.flat_map { |row| columns.map { |col| row[col] } }

  sql = []
  sql << "INSERT INTO #{@table}"
  sql << "(#{columns.join(', ')})"
  sql << "VALUES"

  value_sets = @values.map do |row|
    placeholders = (['?'] * columns.size).join(', ')
    "(#{placeholders})"
  end

  sql << value_sets.join(', ')
  sql.join(' ')
end