Class: Insert

Inherits:
SqlStatement show all
Defined in:
lib/insert.rb

Instance Attribute Summary

Attributes inherited from SqlStatement

#tables, #to_sql

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from SqlStatement

#and, #and_with_or_conditions, #initialize, #or, #where

Constructor Details

This class inherits a constructor from SqlStatement

Class Method Details

.[](table) ⇒ Object

call-seq: Insert -> an_insert

Returns an Insert instance with the SQL initialized to ‘insert into [table] ’

Insert[:table1].to_sql       #=> "insert into table1 "


17
18
19
# File 'lib/insert.rb', line 17

def [](table)
  self.new("insert into #{table.to_sql}")
end

.intoObject

call-seq: Insert.into -> Insert

Returns the Insert class. Unnecessary and only available to mimic SQL statements.

Insert.into       #=> Insert


8
9
10
# File 'lib/insert.rb', line 8

def into
  self
end

Instance Method Details

#[](*columns) ⇒ Object

call-seq: insert -> an_insert

Returns an Insert instance with the columns appended to the SQL statement.

Insert.into[:table1][:column1, :column2].to_sql       #=> "insert into table1 (column1, column2)"


27
28
29
30
# File 'lib/insert.rb', line 27

def [](*columns)
  @to_sql += " (#{columns.join(', ')})"
  self
end

#values(*args) ⇒ Object

call-seq: insert.values { block } -> an_insert

insert.values(arg,...)

If a block is given: Ignores any parameters given to the method. Executes the block then calls to_sql on the result. Returns an Insert instance with the result of the block’s execution appended to the SQL statement.

insert = Insert.into[:table1][:column1].values { Select['book'] }       
insert.to_sql      #=> "insert into table1 (column1) select 'book'"

If no block is given: Returns an Insert instance with the args appended to the SQL statement as values

insert = Insert.into[:table1][:column1, :column2].values(10, 'book')
insert.to_sql      #=> "insert into table1 (column1, column2) values (10, 'book')"


48
49
50
51
52
53
54
# File 'lib/insert.rb', line 48

def values(*args)
  @to_sql += case
    when block_given? then " #{yield.to_sql}"
    else " values (#{args.to_sql})"
  end
  self
end