Skip to content

Instantly share code, notes, and snippets.

@dmerrick
Created July 13, 2009 15:24
Show Gist options
  • Save dmerrick/146200 to your computer and use it in GitHub Desktop.
Save dmerrick/146200 to your computer and use it in GitHub Desktop.
Morgan wanted to see how Ruby could generate a SQL insert.
# 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