Search code examples
postgresqlgogo-pg

How to CRUD Postgres Point data type using go pg


I am using Point datatype for storing coordinates in Postgres DB. How do I map Point datatype to Go lang datatypes? I am not finding any documentation for the same.


Solution

  • go-pg does not have native support to Point type (as of PostGIS). What I've done to overpass that (may not be the best solution but I did manage to make it work) was to put on my model individual Latitude and Longitude fields, and on the query itself use ColumnExpr to get individual values using ST_X (for longitude) and ST_Y (for latitude, don't forget that).

    Model:

    type MyModel struct {
        ID              int64
        Name            string
        LocationLat     float64
        LocationLon     float64
    }
    

    Query:

    err := db.Model(&myModel).
            Column("id", "name").
            ColumnExpr("ST_X(location) AS location_lon").
            ColumnExpr("ST_Y(location) AS location_lat").
            Where("id = ?", id).
            Select()