PostgreSQL COPY FROM STDIN Expressions

postgis, postgresql

Solution

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.

Problem

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?

Original source