Skip to content

Instantly share code, notes, and snippets.

@brendano
Created February 12, 2009 23:12
Show Gist options
  • Save brendano/62935 to your computer and use it in GitHub Desktop.
Save brendano/62935 to your computer and use it in GitHub Desktop.
2sql - turn a newline or whitespace-separated list into an SQL set/tuple/list literal
#!/usr/bin/env ruby
# 112
# 114
# 531
#
# =>
#
# (112,114,531)
#
# Intended for copy-and-paste into SQL statements
# E.g. vim via: %!2sql
items = STDIN.read.strip.split
if items.all?{|x| x =~ /^[0-9]+$/}
# they're fine raw, use as integers
else
# make them string literals
# um not sure what the single quote escape rule is
items = items.map{|x| x.gsub("'", "\\'") }
items = items.map{|x| "'#{x}'" }
end
puts "(" + items.join(",") + ")"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment