-
Notifications
You must be signed in to change notification settings - Fork 1
/
driver.go
64 lines (55 loc) · 1.41 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Package spatialite is a thin wrapper around https://github.com/mattn/go-sqlite3
// that automatically loads the mod_spatialite extension.
package spatialite
// #define SQLITE_ENABLE_RTREE 1
// #include <sqlite3.h>
// #include <spatialite.h>
import "C"
import (
"database/sql"
"database/sql/driver"
sqlite "github.com/mattn/go-sqlite3"
)
// Conn is a spatialite database connection.
type Conn struct {
*sqlite.SQLiteConn
}
// Driver is the spatialite driver.Driver implementation.
type Driver struct {
*sqlite.SQLiteDriver
}
// Open opens a new database connection.
func (d *Driver) Open(name string) (driver.Conn, error) {
conn, err := d.SQLiteDriver.Open(name)
if err != nil {
return nil, err
}
// https://www.gaia-gis.it/gaia-sins/spatialite-cookbook/html/metadata.html
stmt, err := conn.Prepare(`SELECT InitSpatialMetaData(1)`)
if err != nil {
return nil, err
}
defer func() { _ = stmt.Close() }()
rows, err := stmt.Query(nil)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
defer func() { _ = rows.Close() }()
if err != sql.ErrNoRows {
if err := rows.Next(nil); err != nil {
return nil, err
}
}
return &Conn{
SQLiteConn: conn.(*sqlite.SQLiteConn),
}, nil
}
func init() {
sql.Register("spatialite", &Driver{
SQLiteDriver: &sqlite.SQLiteDriver{
Extensions: []string{
"mod_spatialite", // https://groups.google.com/forum/#!topic/golang-nuts/Kj0WKQaLBqY
},
},
})
}