Last active
September 8, 2022 02:48
-
-
Save ptrv/6335248 to your computer and use it in GitHub Desktop.
SpatiaLite example in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"github.com/mattn/go-sqlite3" | |
"log" | |
"os" | |
) | |
func runQuery(db *sql.DB, query string) { | |
tx, err := db.Begin() | |
if err != nil { | |
log.Fatal(err) | |
} | |
stmt, err := tx.Prepare(query) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer stmt.Close() | |
_, err = stmt.Exec() | |
if err != nil { | |
log.Fatal(err) | |
} | |
tx.Commit() | |
} | |
func main() { | |
sql.Register("sqlite3_with_spatialite", | |
&sqlite3.SQLiteDriver{ | |
Extensions: []string{"libspatialite"}, | |
}) | |
os.Remove("./foo.db") | |
db, err := sql.Open("sqlite3_with_spatialite", "./foo.db") | |
if err != nil { | |
log.Panic(err) | |
} | |
defer db.Close() | |
// This has to be surrounded by Begin and Commit, | |
// otherwise InitSpatialMetaData() is very slow | |
q := "SELECT InitSpatialMetaData();" | |
runQuery(db, q) | |
sqls := []string{ | |
"DROP TABLE IF EXISTS testtable", | |
"CREATE TABLE testtable (id INTEGER PRIMARY KEY AUTOINCREMENT, name CHAR(255));", | |
"SELECT AddGeometryColumn('testtable', 'geom', 4326, 'POLYGON', 2);", | |
"SELECT CreateSpatialIndex('testtable', 'geom');", | |
} | |
for _, sql := range sqls { | |
_, err = db.Exec(sql) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
q = "INSERT INTO testtable (name, geom) VALUES ('Test', GeomFromText('POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))', 4326));" | |
runQuery(db, q) | |
} |
Initialize SELECT InitSpatialMetaData(1)
with 1
as an argument, to get it very faster. Just in one transaction.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It should be
mod_spatialite
instead oflibspatialite
nowadays.Also short tip that might be helpful
go run --tags "libsqlite3 darwin" ./main.go
(For OSx)