Is it possible to get multipolygon type data as string from spatialite?

Issue

sql.Register("sqlite3_with_extensions",
    &sqlite3.SQLiteDriver{
        Extensions: []string{
            "mod_spatialite",
        },
    })

db, err := sql.Open("sqlite3_with_extensions", "./map.gpkg")
if err != nil {
    panic(err.Error())
}

query := "select AsText(geom) from level0"
rows, err := db.Query(query)
if err != nil {
    panic(err.Error())
}

for rows.Next() {
    var s []byte
    rows.Scan(&s)
    fmt.Print(s)
}

First of all, the code I wrote is as above, I want to receive the geom data as text like multipolygon((((……))) , but only an empty array is returned.

Below is what the database looks like, data is stored in multipolygon type
enter image description here

Loading this data into golang returns data like the picture belowenter image description here

I want text like multipolygon ((((……))) , not datatype like above, but I don’t know how to do it,

I have loaded extended spatialite into sqlite3 and loaded data through astext, but an empty array is returned as [], [], [] . How can I return the multipolygon text I want? Any help would be appreciated

Solution

Try this:

package main

import (
    "database/sql"
    "log"

    "github.com/twpayne/go-geom/encoding/wkb"
    "github.com/twpayne/go-geom/encoding/wkt"


    _ "github.com/mattn/go-sqlite3"
)

func main() {
    db, err := sql.Open("sqlite3", "./gadm36_levels.gpkg")
    if err != nil {
        log.Fatal(err)
    }

    rows, err := db.Query("select geom from level0 limit 1")
    if err != nil {
        log.Fatal(err)
    }

    defer rows.Close()

    for rows.Next() {
        var b []byte
        var mp wkb.MultiPolygon

        if err := rows.Scan(&b); err != nil {
            log.Fatal(err)
        }

        if err := mp.Scan(b[40:]); err != nil {
            log.Fatal(err)
        }

        log.Printf("%+v", *mp.MultiPolygon)

        text, err := wkt.Marshal(mp.MultiPolygon)
        if err != nil {
                log.Fatal(err)
        }

        log.Printf("%v\n", text)
    }
}

40 is offset of WKB block.

Answered By – serge-v

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.