forked from go-spatial/tegola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
230 lines (208 loc) · 6.11 KB
/
util.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
package postgis
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"github.com/jackc/pgx"
"github.com/terranodo/tegola"
"github.com/terranodo/tegola/basic"
)
// genSQL will fill in the SQL field of a layer given a pool, and list of fields.
func genSQL(l *Layer, pool *pgx.ConnPool, tblname string, flds []string) (sql string, err error) {
if len(flds) == 0 {
// We need to hit the database to see what the fields are.
rows, err := pool.Query(fmt.Sprintf(fldsSQL, tblname))
if err != nil {
return "", err
}
defer rows.Close()
fdescs := rows.FieldDescriptions()
if len(fdescs) == 0 {
return "", fmt.Errorf("No fields were returned for table %v", tblname)
}
// to avoid field names possibly colliding with Postgres keywords,
// we wrap the field names in quotes
for i, _ := range fdescs {
flds = append(flds, fdescs[i].Name)
}
}
for i := range flds {
flds[i] = fmt.Sprintf(`"%v"`, flds[i])
}
var fgeom int = -1
var fgid bool
for i, f := range flds {
if f == `"`+l.geomField+`"` {
fgeom = i
}
if f == `"`+l.idField+`"` {
fgid = true
}
}
// to avoid field names possibly colliding with Postgres keywords,
// we wrap the field names in quotes
if fgeom == -1 {
flds = append(flds, fmt.Sprintf(`ST_AsBinary("%v") AS "%[1]v"`, l.geomField))
} else {
flds[fgeom] = fmt.Sprintf(`ST_AsBinary("%v") AS "%[1]v"`, l.geomField)
}
if !fgid {
flds = append(flds, fmt.Sprintf(`"%v"`, l.idField))
}
selectClause := strings.Join(flds, ", ")
return fmt.Sprintf(stdSQL, selectClause, tblname, l.geomField), nil
}
const (
bboxToken = "!BBOX!"
zoomToken = "!ZOOM!"
)
// replaceTokens replaces tokens in the provided SQL string
//
// !BBOX! - the bounding box of the tile
// !ZOOM! - the tile Z value
func replaceTokens(plyr *Layer, tile tegola.Tile) (string, error) {
textent := tile.BoundingBox()
minGeo, err := basic.FromWebMercator(plyr.srid, basic.Point{textent.Minx, textent.Miny})
if err != nil {
return "", fmt.Errorf("Error trying to convert tile point: %v ", err)
}
maxGeo, err := basic.FromWebMercator(plyr.srid, basic.Point{textent.Maxx, textent.Maxy})
if err != nil {
return "", fmt.Errorf("Error trying to convert tile point: %v ", err)
}
minPt, maxPt := minGeo.AsPoint(), maxGeo.AsPoint()
bbox := fmt.Sprintf("ST_MakeEnvelope(%v,%v,%v,%v,%v)", minPt.X(), minPt.Y(), maxPt.X(), maxPt.Y(), plyr.srid)
// replace query string tokens
tokenReplacer := strings.NewReplacer(
bboxToken, bbox,
zoomToken, strconv.Itoa(tile.Z),
)
return tokenReplacer.Replace(plyr.sql), nil
}
func transformVal(valType pgx.Oid, val interface{}) (interface{}, error) {
switch valType {
default:
switch vt := val.(type) {
default:
log.Printf("%v type is not supported. (Expected it to be a stringer type)", valType)
return nil, fmt.Errorf("%v type is not supported. (Expected it to be a stringer type)", valType)
case fmt.Stringer:
return vt.String(), nil
case string:
return vt, nil
}
case pgx.BoolOid, pgx.ByteaOid, pgx.TextOid, pgx.OidOid, pgx.VarcharOid, pgx.JsonbOid:
return val, nil
case pgx.Int8Oid, pgx.Int2Oid, pgx.Int4Oid, pgx.Float4Oid, pgx.Float8Oid:
switch vt := val.(type) {
case int8:
return int64(vt), nil
case int16:
return int64(vt), nil
case int32:
return int64(vt), nil
case int64, uint64:
return vt, nil
case uint8:
return int64(vt), nil
case uint16:
return int64(vt), nil
case uint32:
return int64(vt), nil
case float32:
return float64(vt), nil
case float64:
return vt, nil
default: // should never happen.
return nil, fmt.Errorf("%v type is not supported. (should never happen)", valType)
}
case pgx.DateOid, pgx.TimestampOid, pgx.TimestampTzOid:
return fmt.Sprintf("%v", val), nil
}
}
func decipherFields(ctx context.Context, geoFieldname, idFieldname string, descriptions []pgx.FieldDescription, values []interface{}) (gid uint64, geom []byte, tags map[string]interface{}, err error) {
tags = make(map[string]interface{})
var desc pgx.FieldDescription
var ok bool
for i, v := range values {
// Do a quick check
if ctx.Err() != nil {
return 0, nil, nil, ctx.Err()
}
// Skip nil values.
if values[i] == nil {
continue
}
desc = descriptions[i]
switch desc.Name {
case geoFieldname:
if geom, ok = v.([]byte); !ok {
return 0, nil, nil, fmt.Errorf("Unable to convert geometry field (%v) into bytes.", geoFieldname)
}
case idFieldname:
gid, err = gId(v)
default:
switch desc.DataTypeName {
// hstore is a special case
case "hstore":
// parse our Hstore values into keys and values
keys, values, err := pgx.ParseHstore(v.(string))
if err != nil {
return gid, geom, tags, fmt.Errorf("Unable to parse Hstore err: %v", err)
}
for i, k := range keys {
// if the value is Valid (i.e. not null) then add it to our tags map.
if values[i].Valid {
// we need to check if the key already exists. if it does, then don't overwrite it
if _, ok := tags[k]; !ok {
tags[k] = values[i].String
}
}
}
continue
case "numeric":
num, err := strconv.ParseFloat(v.(string), 64)
if err != nil {
return 0, nil, nil, fmt.Errorf("Unable to parse numeric (%v) to float64 err: %v", v.(string), err)
}
tags[desc.Name] = num
continue
default:
value, err := transformVal(desc.DataType, v)
if err != nil {
return gid, geom, tags, fmt.Errorf("Unable to convert field[%v] (%v) of type (%v - %v) to a suitable value.: [[ %T :: %[5]t ]]", i, desc.Name, desc.DataType, desc.DataTypeName, v)
}
tags[desc.Name] = value
}
}
}
return gid, geom, tags, err
}
func gId(v interface{}) (gid uint64, err error) {
switch aval := v.(type) {
case float64:
return uint64(aval), nil
case int64:
return uint64(aval), nil
case uint64:
return aval, nil
case uint:
return uint64(aval), nil
case int8:
return uint64(aval), nil
case uint8:
return uint64(aval), nil
case uint16:
return uint64(aval), nil
case int32:
return uint64(aval), nil
case uint32:
return uint64(aval), nil
case string:
return strconv.ParseUint(aval, 10, 64)
default:
return gid, fmt.Errorf("Unable to convert field into a uint64.")
}
}