Home >Backend Development >Golang >How can I insert and select PostGIS geometry types with Gorm?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-05 10:50:02335browse

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.

The above is the detailed content of How can I insert and select PostGIS geometry types with Gorm?. 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