Created
December 15, 2017 04:59
-
-
Save AdamDimech/139afd1ce5b4f5c7aa2ef3041d3fc013 to your computer and use it in GitHub Desktop.
Convert tables in a SQL database to individual CSVs
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
/* | |
1. Log in to psql as a superuser | |
2. CHMOD target directory to 777 | |
3. Execute via SELECT db_to_csv('/path/to/output'); | |
4. Use complete file path. | |
*/ | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment