Arihant Godha
Arihant Godha

Reputation: 2469

Export postgres table to csv error

I am trying to export all my tables of postrgres into individual csv files for that I am using the following function

CREATE OR REPLACE FUNCTION db_to_csv(path text)
  RETURNS void AS
$BODY$
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;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION db_to_csv(text)
  OWNER TO postgres;

but when I am calling this function I am getting could not open file "/home/user/Documents/public.tablename.csv" for writing: Permission denied

I have tried copying individual table using

COPY activities TO '/home/user/Documents/foldername/conversions/tablename.csv' DELIMITER ',' CSV HEADER;

It gives me the following error

ERROR:  could not open file "/home/user/Documents/foldername/conversions/tablename.csv" for writing: Permission denied


********** Error **********

 ERROR:  could not open file "/home/user/Documents/foldername/conversions/tablename.csv" for writing: Permission denied
SQL state: 42501

Any suggestions how to fix this.

Upvotes: 4

Views: 7195

Answers (3)

Nauman Shah
Nauman Shah

Reputation: 352

I was facing the same issue and I followed the second answer

Make a folder on which every user has access. Then run the COPY command on a file there. COPY works only on directories where postgres user has access

This didn't work for me.

So, I performed copy to /tmp/somename.csv and then copied the file to my actual required location for usage.

\copy query TO '/tmp/somename.csv' with csv;

Upvotes: 2

Anoop Saxena
Anoop Saxena

Reputation: 41

Not working after given permission.

Now I tried to export the same location where greenplum data available i.e greenplum/data, now permission denied problem get resolved.

COPY Table_Name TO '/home/greenplum/data/table_data_export.csv';

Upvotes: 1

Alexandros
Alexandros

Reputation: 2200

Make a folder on which every user has access. Then run the COPY command on a file there. COPY works only on directories where postgres user has access

sudo mkdir /media/export
sudo chmod 777 /media/export

COPY activities TO '/media/export/activities.csv' DELIMITER ',' CSV HEADER;

Upvotes: 7

Related Questions