Search code examples
postgresqlpostgiswkt

Does PostGIS automatically convert upon inserting WKT?


I'm quite new to PostGIS so bear with me.

Suppose I have a table defined as follows:

CREATE TABLE gtest (name varchar, geom geometry);

At first, to insert, I was doing something like:

INSERT INTO gtest
VALUES (
    'Polygon',
    ST_GeomFromText('POLYGON((0 0,1 0,1 1,0 1,0 0))',4326)
);

I then discovered that it still works by only doing this:

INSERT INTO gtest
VALUES (
    'Polygon',
    'SRID=4326;POLYGON((0 0,1 0,1 1,0 1,0 0))'
);

When I do a query without converting the geom values back into WKT, they are both encoded properly. Same if I convert the column to EWKT, everything displays properly.

Is there a conversion going on behind the scenes? And if I insert without calling ST_GeomFromText(), will all other functions using the column work fine?

Thanks


Solution

  • There are several automatic cast to and from the geometry type.

    You can type \dC in PostgreSQL and you will see all available casts, including:

                                         List of casts
         Source type         |         Target type         |      Function      |   Implicit?
    -------------------------+-----------------------------+--------------------+---------------
    text                     | geometry                    | geometry           | yes
    

    This information is also available in the doc or in this tutorial.

    Since the cast in implicit, it means you don't have to specify it to use it. Note that you can "force" it using ::geometry:

    select st_asText('SRID=4326;POLYGON((0 0,1 0,1 1,0 1,0 0))'::geometry);
               st_astext
    --------------------------------
     POLYGON((0 0,1 0,1 1,0 1,0 0))
    (1 row)
    

    Regarding the column usability, the column is of type geometry so anything that is in this column is a geometry and can be used by any function requiring a geometry. How the data got there (automatic cast, conversion, extraction from another geometry etc) is not relevant anymore.