Inserting and selecting PostGIS Geometry with Gorm

后端 未结 4 1798
星月不相逢
星月不相逢 2021-02-07 15:56

I\'ve been trying to find a way to insert and retrieve geometric types using Golang, and specifically the library gorm. I\'m also attempting to use the library orb that defines

4条回答
  •  情话喂你
    2021-02-07 16:32

    I used @robbieperry22's answer with a different encoding library and found I didn't need to tinker with bytes at all.

    Included gist for reference.

    import  "github.com/twpayne/go-geom/encoding/geojson"
    
    
    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()
    }
    
    
    type Track struct {
        gorm.Model
    
        GeometryPoint EWKBGeomPoint `gorm:"column:geom"`
    }
    

    And then used a little customization on the table set up/migrate part:

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

提交回复
热议问题