Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 471
Arihant Godha Avatar asked Oct 22 '25 00:10

Arihant Godha


1 Answers

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;
like image 191
Alexandros Avatar answered Oct 23 '25 14:10

Alexandros