Search This Blog

Saturday, January 18, 2014

Postgreql - Import All Tables to CSV

Hi all,
Today  i came across a situation where i need to import and export csv to postgresql db and to migrate all tables in a db to csv format. Lets see what i did,

Step 1: Change to 'postgres user'

# su postgres

Step 2: Login to a database (In my case i used a local database to test)

# psql <database name>

Example:
# psql testdb

Step 3: Lets see how to export just one table

# COPY <table name> to '/path/to/csv file' delimeters',';

Example:
# COPY zones to '/tmp/test.csv' delimeters',';

Step 4: Lets see how to import from csv

# COPY <table name> from '/path/to/csv file' delimeters',';

Example:
# COPY zones from '/tmp/test.csv' delimeters',';

Step 4: Lets see how to import all tables in a database. For that we need to create a function like below

# CREATE OR REPLACE FUNCTION all_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', 'configuration')
         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;

Next we can use the above function to export to a folder

# SELECT all_csv('/path/to/directiry');

example:
SELECT all_csv('/tmp/tt');

Thats it, we are done. Enjoy with your work....

No comments:

Post a Comment