Estoy insertando con éxito archivos csv
en postgresql
con el siguiente comando:
\COPY tablename(col1, col2, col3) FROM '/home/user/mycsv.txt' WITH CSV HEADER DELIMITER ';' NULL AS 'null';
Sin embargo, me gustaría escribir algunos metadatos dentro de este archivo csv
con datos repetibles. Sé que podría crear un archivo diferente para almacenar estos datos, pero creo que sería mucho más conveniente almacenar estos metadatos en el mismo archivo csv
donde se almacena la mayoría de los datos. Me imagino un archivo como el siguiente:
-- commented line with some metadata col1;col2;col3 value;value;value value;value;value value;value;value
Intenté usar --
/* /*
y #
como comentarios pero el comando \copy
falla al importar los datos cuando lo hago. ¿Hay alguna forma de decirle al comando \copy
psql
que vea líneas específicas como comentarios para poder insertar datos con líneas que no forman parte del archivo csv
? ¿Es posible?
Use la construcción FROM PROGRAM para indicar algo más para filtrarlos.
\COPY tablename(col1, col2, col3) FROM PROGRAM 'egrep -v "^-- " mycsv.txt' WITH CSV HEADER DELIMITER ';' NULL AS 'null'
Ya ves cómo lo hace pg_dump:
pg_dump -d test -U postgres -t orders -a -f test.sql cat test.sql -- -- PostgreSQL database dump -- -- Dumped from database version 12.3 -- Dumped by pg_dump version 12.3 SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); SET check_function_bodies = false; SET xmloption = content; SET client_min_messages = warning; SET row_security = off; -- -- Data for Name: orders; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY public.orders (order_id, total, order_date, user_id) FROM stdin; 1 100 2020-06-20 00:00:00 1 2 250 2020-06-20 00:00:00 2 \. -- -- Name: orders_order_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres -- SELECT pg_catalog.setval('public.orders_order_id_seq', 2, true); -- -- PostgreSQL database dump complete -- psql -d test -U postgres -f test.sql Null display is "NULL". SET SET SET SET SET set_config ------------ (1 row) SET SET SET SET COPY 2 setval -------- 2 (1 row)