"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I insert and select PostGIS geometry types with Gorm?

How can I insert and select PostGIS geometry types with Gorm?

Posted on 2025-03-23
Browse:482

How can I insert and select PostGIS geometry types with Gorm?

Inserting and Selecting PostGIS Geometry with Gorm

Using Orb and Custom Value Scanning and Marshalling

Inserting and retrieving PostGIS geometry types with Gorm can be challenging. To address this issue, users can leverage the Orb library and implement custom Scan() and Value() methods to convert between Go types and the well-known binary (WKB) format expected by Gorm. Here's an example:

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()
}

By implementing these methods in a struct, Gorm's automated scanning and inserting functions can work seamlessly with geometry types.

Table Setup with Custom Migration

To create the table with the necessary geometry column, a custom migration step can be used to configure the column type:

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
}

err = gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
{
    ID: "init",
    Migrate: func(tx *gorm.DB) error {
        return tx.CreateTable(
            Tables...,
        ).Error
    },
},
{
    ID: "tracks_except_geom",
    Migrate: func(tx *gorm.DB) error {
        return db.AutoMigrate(Track{}).Error
    },
},
}).Migrate()

This migration ensures the geometry column is created before the rest of the table structure is set up.

Example Usage

Once the custom Scan(), Value(), and migration steps are implemented, using the geometry type in a Gorm model becomes straightforward:

type Track struct {
    gorm.Model

    GeometryPoint EWKBGeomPoint `gorm:"column:geom"`
}

With this setup, Gorm can effortlessly insert and select PostGIS geometry types, allowing for seamless usage of geometric data in Go applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3