class MultiInsert::Query
A MultiInsert
query.
Most of the time, you do not need to instanciate it yourself.
Attributes
Public Class Methods
Create an insert query against the specified table and columns, with the specified values. The following options are supported:
-
time (true) Whether to insert created_at and updated_at.
@param table [String | Symbol] The table to be used for insertion. @param columns [Array<String | Symbol>] The columns to be inserted. @param values [Array<Array<String | Number | Boolean>>] The values to be inserted. @param opts [Hash<Object>] Options.
# File lib/multi_insert/query.rb, line 56 def initialize(table, columns, values, opts = {}) @table = table.to_sym @opts = opts @sql_insert = ::MultiInsert::QueryBuilder.insert(table, columns, values, opts) end
Public Instance Methods
Execute the query, and return eventual results.
Result may be:
-
Nil if no returning clause was present.
-
An array of IDs if the
returning_id
helper was called. -
An array of rows otherwise.
@return [nil | Array<Integer> | Array<Array<String | Number | Boolean>>]
# File lib/multi_insert/query.rb, line 122 def execute result = nil ActiveRecord::Base.connection_pool.with_connection do |con| result = con.execute(to_sql) end if @sql_returning.nil? nil else if @returning_flat result.values.map{|r| r.first} else result end end end
Begin a conflict clause.
@param column [String | Symbol] The column to watch for conflicts. @return [Query::OnConflict] A conflict clause.
# File lib/multi_insert/query.rb, line 86 def on_conflict(column = nil) ::MultiInsert::Query::OnConflict.new(self, column) end
Handle a conflict with raw SQL
You should probably use the friendly helper method instead. @param sql [String] An SQL expression starting with “ON CONFLICT”. @return [Query] self.
# File lib/multi_insert/query.rb, line 95 def on_conflict_sql(sql) @sql_on_conflict = sql self end
Add a returning clause to the query.
@param columns [Array<Symbol | String>] The columns to return. @return [Query] self.
# File lib/multi_insert/query.rb, line 66 def returning(columns) @sql_returning = ::MultiInsert::QueryBuilder.returning(columns) @returning_flat = false self end
Add a returning clause to the query, returning IDs.
The IDs will be returned as a flat array. @return [Query] self
# File lib/multi_insert/query.rb, line 76 def returning_id @sql_returning = ::MultiInsert::QueryBuilder.returning([:id]) @returning_flat = true self end
Equivalent to `to_sql`.
@return [String] An SQL query.
# File lib/multi_insert/query.rb, line 110 def to_s to_sql end
Convert the query to raw SQL.
@return [String] An SQL query.
# File lib/multi_insert/query.rb, line 103 def to_sql [@sql_insert, @sql_on_conflict, @sql_returning].reject(&:nil?).join(' ') end