Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Trabalhando com dados espaciais com Gorm e MySQL


Aqui está outra abordagem; usar codificação binária.

De acordo com este doc , o MySQL armazena valores de geometria usando 4 bytes para indicar o SRID (ID de Referência Espacial) seguido pela representação WKB (Binário Bem Conhecido) do valor.

Assim, um tipo pode usar a codificação WKB e adicionar e remover o prefixo de quatro bytes nas funções Value() e Scan(). A biblioteca go-geom encontrada em outras respostas possui um pacote de codificação WKB, github.com/twpayne/go-geom/encoding/wkb.

Por exemplo:
type MyPoint struct {
    Point wkb.Point
}

func (m *MyPoint) Value() (driver.Value, error) {
    value, err := m.Point.Value()
    if err != nil {
        return nil, err
    }

    buf, ok := value.([]byte)
    if !ok {
        return nil, fmt.Errorf("did not convert value: expected []byte, but was %T", value)
    }

    mysqlEncoding := make([]byte, 4)
    binary.LittleEndian.PutUint32(mysqlEncoding, 4326)
    mysqlEncoding = append(mysqlEncoding, buf...)

    return mysqlEncoding, err
}

func (m *MyPoint) Scan(src interface{}) error {
    if src == nil {
        return nil
    }

    mysqlEncoding, ok := src.([]byte)
    if !ok {
        return fmt.Errorf("did not scan: expected []byte but was %T", src)
    }

    var srid uint32 = binary.LittleEndian.Uint32(mysqlEncoding[0:4])

    err := m.Point.Scan(mysqlEncoding[4:])

    m.Point.SetSRID(int(srid))

    return err
}

Definindo um Tag usando o tipo MyPoint:
type Tag struct {
    Name string   `gorm:"type:varchar(50);primary_key"`
    Loc  *MyPoint `gorm:"column:loc"`
}

func (t Tag) String() string {
    return fmt.Sprintf("%s @ Point(%f, %f)", t.Name, t.Loc.Point.Coords().X(), t.Loc.Point.Coords().Y())
}

Criando uma tag usando o tipo:
tag := &Tag{
    Name: "London",
    Loc: &MyPoint{
        wkb.Point{
            geom.NewPoint(geom.XY).MustSetCoords([]float64{0.1275, 51.50722}).SetSRID(4326),
        },
    },
}

err = db.Create(&tag).Error
if err != nil {
    log.Fatalf("create: %v", err)
}

Resultados do MySQL:
mysql> describe tag;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name  | varchar(50) | NO   | PRI | NULL    |       |
| loc   | geometry    | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+


mysql> select name, st_astext(loc) from tag;
+--------+------------------------+
| name   | st_astext(loc)         |
+--------+------------------------+
| London | POINT(0.1275 51.50722) |
+--------+------------------------+
  • (ArcGIS diz 4326 é a referência espacial mais comum para armazenar dados de referência em todo o mundo. Ele serve como padrão tanto para o banco de dados espacial PostGIS quanto para o padrão GeoJSON. Ele também é usado por padrão na maioria das bibliotecas de mapeamento da web.)