Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL COPY FROM STDIN Expressions

I am attempting to use COPY FROM STDIN to import data into my table. One of the columns in my table is of type geometry. My command looks something like this...

COPY "WeatherStations" ("Station_ID", "Station_Code", "Station_Name", "Station_Location") FROM stdin;
1       KAVP    WILKES-BARRE    ST_GeomFromText('POINT(41.338055 -75.724166)')
2       KOKV    WINCHESTER      ST_GeomFromText('POINT(39.143333 -78.144444)')
3       KSHD    SHENANDOAH      ST_GeomFromText('POINT(38.263611 -78.896388)')
...

However, I think it is attempting to insert the text "ST_GeomFromText('POINT..." and failing instead of evaluating the expression and inserting the result of the expression. Does anyone know what might be going on here and how I can get the actual geoms inserted?

like image 222
elynnaie Avatar asked Apr 18 '12 19:04

elynnaie


People also ask

What is Stdin in Postgres?

Stdin: It is a standard input stream. It is used where the program reads the input data. Stdout: This implies the standard output stream used when the application writes the data (output) to the file.

What is psql's \copy?

Psql \copy command is used when you want to export the data from Postgres table to a CSV file on a client machine. To use this command, you will need access to the psql prompt. You will understand it more with the following psql copy examples. To copy the entire table to a csv file, use \copy.


1 Answers

I had a bad time figuring out how to bulk copy/load geometry data into PostGIS using the COPY FROM STDIN command, I couldn't find official documentation on this topic.

Altering the column during the bulk load (the ALTER TABLE / SET DATA TYPE / USING) was not an option to me because it is only supported in PostGIS 2.0+ for the Geometry type, nor was acceptable the use of a temporary table.

There is indeed a direct way to do it (at least in PostGIS 1.5.2+). You can simply rewrite the data for your copy statement this way, using a simple WKT (Well-known text) representation for your Geometry data:

1       KAVP    WILKES-BARRE    POINT(41.338055 -75.724166)
2       KOKV    WINCHESTER      POINT(39.143333 -78.144444)
3       KSHD    SHENANDOAH      POINT(38.263611 -78.896388)

If you have enforced a SRID constraint on the geometry column you'll have to use the following syntax (in this example the SRID is 4326) known as EWKT (Extended Well-Known Text, which is a PostGIS specific format):

1       KAVP    WILKES-BARRE    SRID=4326;POINT(41.338055 -75.724166)
2       KOKV    WINCHESTER      SRID=4326;POINT(39.143333 -78.144444)
3       KSHD    SHENANDOAH      SRID=4326;POINT(38.263611 -78.896388)

Closing note: there must be no space between "POINT" and the opening parenthesis "(", or the COPY will still return error saying your geometry data has an invalid format.

like image 172
Fulvio Avatar answered Sep 24 '22 14:09

Fulvio