This repository has been archived by the owner on Aug 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gpkg.go
263 lines (213 loc) · 6.33 KB
/
gpkg.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// +build cgo
package gpkg
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/go-spatial/geom"
"github.com/go-spatial/geom/encoding/wkb"
"github.com/go-spatial/tegola-postgis/internal/log"
"github.com/go-spatial/tegola-postgis/proj"
"github.com/go-spatial/tegola-postgis/provider"
)
const (
Name = "gpkg"
DefaultSRID = proj.WebMercator
DefaultIDFieldName = "fid"
DefaultGeomFieldName = "geom"
)
// config keys
const (
ConfigKeyFilePath = "filepath"
ConfigKeyLayers = "layers"
ConfigKeyLayerName = "name"
ConfigKeyTableName = "tablename"
ConfigKeySQL = "sql"
ConfigKeyGeomIDField = "id_fieldname"
ConfigKeyFields = "fields"
)
func decodeGeometry(bytes []byte) (*BinaryHeader, geom.Geometry, error) {
h, err := NewBinaryHeader(bytes)
if err != nil {
log.Error("error decoding geometry header: %v", err)
return h, nil, err
}
geo, err := wkb.DecodeBytes(bytes[h.Size():])
if err != nil {
log.Errorf("error decoding geometry: %v", err)
return h, nil, err
}
return h, geo, nil
}
type Provider struct {
// path to the geopackage file
Filepath string
// map of layer name and corresponding sql
layers map[string]Layer
// reference to the database connection
db *sql.DB
}
func (p *Provider) Layers() ([]provider.LayerInfo, error) {
log.Debug("attempting gpkg.Layers()")
ls := make([]provider.LayerInfo, len(p.layers))
var i int
for _, player := range p.layers {
ls[i] = player
i++
}
log.Debugf("returning LayerInfo array: %v", ls)
return ls, nil
}
func (p *Provider) TileFeatures(ctx context.Context, layer string, tile provider.Tile, fn func(f *provider.Feature) error) error {
log.Debugf("fetching layer %v", layer)
pLayer := p.layers[layer]
// read the tile extent
tileBBox, tileSRID := tile.BufferedExtent()
// TODO(arolek): reimplement once the geom package has reprojection
// check if the SRID of the layer differs from that of the tile. tileSRID is assumed to always be WebMercator
if pLayer.srid != tileSRID {
minGeo, err := proj.FromWebMercator(pLayer.srid, geom.Point{tileBBox.MinX(), tileBBox.MinY()})
if err != nil {
return fmt.Errorf("error converting point: %v ", err)
}
maxGeo, err := proj.FromWebMercator(pLayer.srid, geom.Point{tileBBox.MaxX(), tileBBox.MaxY()})
if err != nil {
return fmt.Errorf("error converting point: %v ", err)
}
tileBBox = geom.NewExtent(minGeo.(geom.Point), maxGeo.(geom.Point))
}
var qtext string
if pLayer.tablename != "" {
// If layer was specified via "tablename" in config, construct query.
rtreeTablename := fmt.Sprintf("rtree_%v_%s", pLayer.tablename, pLayer.geomFieldname)
selectClause := fmt.Sprintf("SELECT l.`%v`, l.`%v`", pLayer.idFieldname, pLayer.geomFieldname)
for _, tf := range pLayer.tagFieldnames {
selectClause += fmt.Sprintf(", l.`%v`", tf)
}
// l - layer table, si - spatial index
qtext = fmt.Sprintf("%v FROM `%v` l JOIN `%v` si ON l.`%v` = si.id WHERE l.`%v` IS NOT NULL AND !BBOX! ORDER BY l.`%v`", selectClause, pLayer.tablename, rtreeTablename, pLayer.idFieldname, pLayer.geomFieldname, pLayer.idFieldname)
z, _, _ := tile.ZXY()
qtext = replaceTokens(qtext, z, tileBBox)
} else {
// If layer was specified via "sql" in config, collect it
z, _, _ := tile.ZXY()
qtext = replaceTokens(pLayer.sql, z, tileBBox)
}
log.Debugf("qtext: %v", qtext)
rows, err := p.db.Query(qtext)
if err != nil {
log.Errorf("err during query: %v - %v", qtext, err)
return err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return err
}
for rows.Next() {
// check if the context cancelled or timed out
if ctx.Err() != nil {
return ctx.Err()
}
vals := make([]interface{}, len(cols))
valPtrs := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
valPtrs[i] = &vals[i]
}
if err = rows.Scan(valPtrs...); err != nil {
log.Errorf("err reading row values: %v", err)
return err
}
feature := provider.Feature{
Tags: map[string]interface{}{},
}
for i := range cols {
// check if the context cancelled or timed out
if ctx.Err() != nil {
return ctx.Err()
}
if vals[i] == nil {
continue
}
switch cols[i] {
case pLayer.idFieldname:
feature.ID, err = provider.ConvertFeatureID(vals[i])
if err != nil {
return err
}
case pLayer.geomFieldname:
log.Debug("extracting geopackage geometry header.", vals[i])
geomData, ok := vals[i].([]byte)
if !ok {
log.Errorf("unexpected column type for geom field. got %t", vals[i])
return errors.New("unexpected column type for geom field. expected blob")
}
h, geo, err := decodeGeometry(geomData)
if err != nil {
return err
}
feature.SRID = uint64(h.SRSId())
feature.Geometry = geo
case "minx", "miny", "maxx", "maxy", "min_zoom", "max_zoom":
// Skip these columns used for bounding box and zoom filtering
continue
default:
// Grab any non-nil, non-id, non-bounding box, & non-geometry column as a tag
switch v := vals[i].(type) {
case []uint8:
asBytes := make([]byte, len(v))
for j := 0; j < len(v); j++ {
asBytes[j] = v[j]
}
feature.Tags[cols[i]] = string(asBytes)
case int64:
feature.Tags[cols[i]] = v
case string:
feature.Tags[cols[i]] = v
default:
// TODO(arolek): return this error?
log.Errorf("unexpected type for sqlite column data: %v: %T", cols[i], v)
}
}
}
// pass the feature to the provided call back
if err = fn(&feature); err != nil {
return err
}
}
return nil
}
// Close will close the Provider's database connection
func (p *Provider) Close() error {
return p.db.Close()
}
type GeomTableDetails struct {
geomFieldname string
geomType geom.Geometry
srid uint64
bbox geom.Extent
}
type GeomColumn struct {
name string
geometryType string
geom geom.Geometry // to populate Layer.geomType
srsId int
}
func geomNameToGeom(name string) (geom.Geometry, error) {
switch name {
case "POINT":
return geom.Point{}, nil
case "LINESTRING":
return geom.LineString{}, nil
case "POLYGON":
return geom.Polygon{}, nil
case "MULTIPOINT":
return geom.MultiPoint{}, nil
case "MULTILINESTRING":
return geom.MultiLineString{}, nil
case "MULTIPOLYGON":
return geom.MultiPolygon{}, nil
}
return nil, fmt.Errorf("unsupported geometry type: %v", name)
}