Home >Backend Development >Golang >How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?

How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 22:43:02994browse

How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?

Inserting and Selecting PostGIS Geometry with Gorm

Problem:

In Go, using Gorm to insert and retrieve PostGIS geometry types via the Orb library poses challenges due to Gorm's automatic insertion and data scanning. Simply inserting binary data into geometry columns doesn't suffice, and querying returns hex results.

Solution:

Using the @robbieperry22 answer as inspiration, an approach with a different encoding library eliminates the need for byte manipulation.

Implementation:

  1. Create custom Scan() and Value() methods for the geometry type, similar to:
<code class="go">type EWKBGeomPoint geom.Point

func (g *EWKBGeomPoint) Scan(input interface{}) error {
    gt, err := ewkb.Unmarshal(input.([]byte))
    if err != nil {
        return err
    }
    g = gt.(*EWKBGeomPoint)
    return nil
}

func (g EWKBGeomPoint) Value() (driver.Value, error) {
    b := geom.Point(g)
    bp := &b
    ewkbPt := ewkb.Point{Point: bp.SetSRID(4326)}
    return ewkbPt.Value()
}</code>
  1. Define a model struct with the geometry field:
<code class="go">type Track struct {
    gorm.Model
    GeometryPoint EWKBGeomPoint `gorm:"column:geom"`
}</code>
  1. Customize table creation to avoid default Gorm behavior for the geometry column:
<code class="go">err = db.Exec(`CREATE TABLE IF NOT EXISTS tracks (
    id SERIAL PRIMARY KEY,
    geom geometry(POINT, 4326) NOT NULL
);`).Error
if err != nil {
    return err
}

// Create table without geom column
mig := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
    {
        ID: "tracks_except_geom",
        Migrate: func(tx *gorm.DB) error {
            return tx.AutoMigrate(Track{}).Error
        },
    },
}
mig.Migrate()</code>

This approach seamlessly converts between EWKB bytes and the PostGIS geometry type, allowing for insertion and selection of geometries without additional customization or manual query generation.

The above is the detailed content of How to Insert and Select PostGIS Geometry Types with Gorm and EWKB?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn