Created
July 13, 2009 15:24
-
-
Save dmerrick/146200 to your computer and use it in GitHub Desktop.
Morgan wanted to see how Ruby could generate a SQL insert.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# given: arg = { 'col1':'foobar', | |
# 'col2':'fubar', | |
# 'col3':'fuck'} | |
# | |
# generate: | |
# INSERT INTO table (col1, col2, col3) VALUES("foobar","fubar","fuck") | |
# | |
input = { :col1 => "foobar", :col2 => "fubar", :col3 => "fuck" } | |
def one_line_generate_query( hash ) | |
"INSERT INTO table (#{hash.keys.join(", ")}) VALUES ('#{hash.values.join("', '")}')" | |
end | |
puts one_line_generate_query(input) | |
# => INSERT INTO table (col1, col2, col3) VALUES ('foobar', 'fubar', 'fuck') | |
def verbose_generate_query( hash ) | |
query = "INSERT INTO table (" | |
query += hash.keys.join(", ") | |
query += ") VALUES ('" | |
query += hash.values.join("', '") | |
query += "')" | |
end | |
puts verbose_generate_query(input) | |
# => INSERT INTO table (col1, col2, col3) VALUES ('foobar', 'fubar', 'fuck') | |
# With sqldsl (sqldsl.rubyforge.org) | |
# require 'sqldsl/insert' | |
# Insert.into[:table][input.keys.to_sql].values[input.values.to_sql] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment