Class: QueryKit::InsertQuery
- Inherits:
-
Object
- Object
- QueryKit::InsertQuery
- Defined in:
- lib/querykit/insert_query.rb
Overview
InsertQuery class for building INSERT SQL queries
Instance Attribute Summary collapse
-
#bindings ⇒ Object
readonly
Returns the value of attribute bindings.
-
#table ⇒ Object
readonly
Returns the value of attribute table.
-
#values(data) ⇒ Object
readonly
Set the table to insert into.
Instance Method Summary collapse
-
#initialize(table = nil) ⇒ InsertQuery
constructor
Initialize a new InsertQuery instance.
-
#into(table) ⇒ Object
Set the table to insert into.
- #to_s ⇒ Object
-
#to_sql ⇒ Object
Generate the SQL INSERT statement.
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
#bindings ⇒ Object (readonly)
Returns the value of attribute bindings.
6 7 8 |
# File 'lib/querykit/insert_query.rb', line 6 def bindings @bindings end |
#table ⇒ Object (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_s ⇒ Object
54 55 56 |
# File 'lib/querykit/insert_query.rb', line 54 def to_s to_sql end |
#to_sql ⇒ Object
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 |