Class: Roebe::SqlParadise::InsertInto

Inherits:
SQL_Command show all
Defined in:
lib/roebe/sql_paradise/insert_into.rb

Overview

#

This small class will do a proper INSERT INTO SQL statement.

Example:

INSERT INTO "table_name" ("column1", "column2") VALUES ("value1", "value2");
#

Constant Summary collapse

REMOVE_NEWLINES =
true

Class Method Summary collapse

Methods inherited from SQL_Command

#sanitize

Class Method Details

.[](name_of_table = :nodes, name_of_fields = '(tax_id, parent_tax_id, rank)', values = '5, "yo", "somewhere"') ⇒ Object

#

InsertInto[]

Use this class method to generate an INSERT INTO statement.

The three arguments are:

(1) name_of_table
(2) name_of_fields
(3) values (in string form)

Note that for the second argument, name_of_fields, we do not have to provide the () characters.

Specific Usage example:

InsertInto[:nodes, '(tax_id, parent_tax_id, rank)', '5, "yo", "somewhere"']
#


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/roebe/sql_paradise/insert_into.rb', line 44

def self.[](
    name_of_table = :nodes,
    name_of_fields = '(tax_id, parent_tax_id, rank)',
    values = '5, "yo", "somewhere"'
  )
  name_of_table  = name_of_table.to_s # Need to work with a string.
  name_of_fields = name_of_fields.to_s.strip
  name_of_fields.chop! if name_of_fields.end_with? ','
  values = values.to_s.strip
  values.chop! if values.end_with? ','
  
  append_this_string = ''.dup
  if block_given?
    data = yield
    if data.is_a?(Hash) and data.has_key?(:taxid) # For input: { :taxid => entry.to_i }
      append_this_string << ' WHERE taxid='+data[:taxid].to_s
    end
  end
  unless name_of_fields.include? '(' # Surround with () unless they were already added before.
    name_of_fields = "(#{name_of_fields})"
  end
  _ = <<EOF
INSERT INTO #{name_of_table}
#{name_of_fields} VALUES (#{values})#{append_this_string};
EOF
  _.delete!("\n") if REMOVE_NEWLINES
  return _.chomp
end