-
-
Save seamusabshere/6708941 to your computer and use it in GitHub Desktop.
hcsv - dump id + values from one hstore column
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
#!/usr/bin/env ruby | |
# Usage: hcsv DBNAME TBLNAME HSTORECOL | |
# Output columns will be id + all the hstore keys | |
dbname, tblname, hstorecol = ARGV[0..2] | |
# Get hstore keys | |
out = `psql #{dbname} --tuples --command "SELECT DISTINCT k FROM (SELECT skeys(#{hstorecol}) AS k FROM #{tblname}) AS dt ORDER BY k"` | |
headers = out.split(/\n/).map(&:strip) | |
# Dump CSV of id + all hstore keys | |
hstore_headers_sql = headers.map { |k| %{#{hstorecol}->'#{k}' AS "#{k}"} }.join(', ') | |
system 'psql', dbname, '--tuples', '--command', "COPY (SELECT id, #{hstore_headers_sql} FROM #{tblname}) TO STDOUT (FORMAT 'csv', HEADER)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment