Skip to content

Instantly share code, notes, and snippets.

@ggmartins
Created November 13, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggmartins/fe0f96a8b1110f371fdca4ea3d265826 to your computer and use it in GitHub Desktop.
Save ggmartins/fe0f96a8b1110f371fdca4ea3d265826 to your computer and use it in GitHub Desktop.
PostgresSQL database to CSV
CREATE OR REPLACE FUNCTION db_to_csv(path TEXT) RETURNS void AS $$
declare
tables RECORD;
statement TEXT;
begin
FOR tables IN
SELECT (table_schema || '.' || table_name) AS schema_table
FROM information_schema.tables t INNER JOIN information_schema.schemata s
ON s.schema_name = t.table_schema
WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema')
AND t.table_type NOT IN ('VIEW')
ORDER BY schema_table
LOOP
statement := 'COPY ' || tables.schema_table || ' TO ''' || path || '/' || tables.schema_table || '.csv' ||''' DELIMITER '';'' CSV HEADER';
EXECUTE statement;
END LOOP;
return;
end;
$$ LANGUAGE plpgsql;
@ggmartins
Copy link
Author

@ggmartins
Copy link
Author

#!/bin/bash

#   SELECT (table_schema || '.' || table_name) AS schema_table
#   FROM information_schema.tables t INNER JOIN information_schema.schemata s 
#   ON s.schema_name = t.table_schema 
#   WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema')
#   AND t.table_type NOT IN ('VIEW')
#   ORDER BY schema_table

for i in $(cat /scratch/csv/mst/dumpcsv.list); do
echo $i
psql -h host -U _admin -d performancedb -c "\\copy (SELECT * FROM $i) TO '/scratch/csv/mst/$i.csv' DELIMITER '|' CSV HEADER"
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment