forked from CrunchyData/pg_tileserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
layer_proc.go
284 lines (246 loc) · 7.88 KB
/
layer_proc.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
// Logging
log "github.com/sirupsen/logrus"
// Configuration
"github.com/spf13/viper"
)
// LayerFunction provides metadata about the function
type LayerFunction struct {
ID string
Schema string
Function string
Description string
Arguments map[string]FunctionArgument
MinZoom int
MaxZoom int
Tiles string
}
// FunctionArgument provides the metadata and order
// of arguments in function call.
type FunctionArgument struct {
Name string `json:"name"`
Type string `json:"type"`
Default string `json:"default,omitempty"`
order int
}
// FunctionDetailJSON gives the output structure for
// the function.
type FunctionDetailJSON struct {
ID string `json:"id"`
Schema string `json:"schema"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Arguments []FunctionArgument `json:"arguments"`
MinZoom int `json:"minzoom"`
MaxZoom int `json:"maxzoom"`
TileURL string `json:"tileurl"`
}
/********************************************************************************
* Layer Interface
*/
// GetType disambiguates between function and table layers
func (lyr LayerFunction) GetType() LayerType {
return LayerTypeFunction
}
// GetID returns the complete ID (schema.name) by which to reference a given layer
func (lyr LayerFunction) GetID() string {
return lyr.ID
}
// GetDescription returns the text description for a layer
// or an empty string if no description is set
func (lyr LayerFunction) GetDescription() string {
return lyr.Description
}
// GetName returns just the name of a given layer
func (lyr LayerFunction) GetName() string {
return lyr.Function
}
// GetSchema returns just the schema for a given layer
func (lyr LayerFunction) GetSchema() string {
return lyr.Schema
}
// GetTileRequest takes tile and request parameters as input and returns a TileRequest
// specifying the SQL and any additional arguments to fetch appropriate data
func (lyr LayerFunction) GetTileRequest(tile Tile, r *http.Request) TileRequest {
procArgs := lyr.getFunctionArgs(r.URL.Query())
sql, data, _ := lyr.requestSQL(tile, procArgs)
tr := TileRequest{
LayerID: lyr.ID,
Tile: tile,
SQL: sql,
Args: data,
}
return tr
}
// WriteLayerJSON outputs parameters and optional arguments for the function layer
func (lyr LayerFunction) WriteLayerJSON(w http.ResponseWriter, req *http.Request) error {
jsonTableDetail, err := lyr.getFunctionDetailJSON(req)
if err != nil {
return err
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(jsonTableDetail)
// all good, no error
return nil
}
/********************************************************************************/
func (lyr *LayerFunction) requestSQL(tile Tile, args map[string]string) (string, []interface{}, error) {
// Need ordered list of named parameters and values to
// pass into the Query
keys := []string{"x => $1", "y => $2", "z => $3"}
vals := []interface{}{tile.X, tile.Y, tile.Zoom}
i := 4
for k, v := range args {
keys = append(keys, fmt.Sprintf("%s => $%d", k, i))
vals = append(vals, v)
i++
}
// Build the SQL
sql := fmt.Sprintf("SELECT \"%s\".\"%s\"(%s)", lyr.Schema, lyr.Function, strings.Join(keys, ", "))
log.WithFields(log.Fields{
"event": "tile",
"topic": "sql",
"key": sql,
}).Debugf("requestSql: %s", sql)
return sql, vals, nil
}
func (lyr *LayerFunction) getFunctionArgs(vals url.Values) map[string]string {
funcArgs := make(map[string]string)
for k, v := range vals {
if arg, ok := lyr.Arguments[k]; ok {
funcArgs[arg.Name] = v[0]
}
}
log.WithFields(log.Fields{
"event": "tile",
"topic": "args",
"function": "getFunctionArgs",
"return": funcArgs,
}).Debugf("getFunctionArgs => %s", funcArgs)
return funcArgs
}
func (lyr *LayerFunction) getFunctionDetailJSON(req *http.Request) (FunctionDetailJSON, error) {
td := FunctionDetailJSON{
ID: lyr.ID,
Schema: lyr.Schema,
Name: lyr.Function,
Description: lyr.Description,
Arguments: make([]FunctionArgument, 0),
MinZoom: viper.GetInt("DefaultMinZoom"),
MaxZoom: viper.GetInt("DefaultMaxZoom"),
}
// TileURL is relative to server base
td.TileURL = fmt.Sprintf("%s/%s/{z}/{x}/{y}.pbf", serverURLBase(req), url.PathEscape(lyr.ID))
tmpMap := make(map[int]FunctionArgument)
tmpKeys := make([]int, 0, len(lyr.Arguments))
for _, v := range lyr.Arguments {
tmpMap[v.order] = v
tmpKeys = append(tmpKeys, v.order)
}
sort.Ints(tmpKeys)
for _, v := range tmpKeys {
td.Arguments = append(td.Arguments, tmpMap[v])
}
return td, nil
}
func getFunctionLayers() ([]LayerFunction, error) {
// Valid functions **must** have signature of
// function(z integer, x integer, y integer) returns bytea
layerSQL := `
SELECT
Format('%s.%s', n.nspname, p.proname) AS id,
n.nspname AS nspname,
p.proname AS proname,
coalesce(d.description, '') AS description,
coalesce(p.proargnames, ARRAY[]::text[]) AS argnames,
coalesce(string_to_array(oidvectortypes(p.proargtypes),', '), ARRAY[]::text[]) AS argtypes,
coalesce(string_to_array(regexp_replace(pg_get_expr(p.proargdefaults, 0::Oid), '''([a-zA-Z0-9_\-\.]+)''::[a-z1-9]+', '\1'),', ', 'g'), ARRAY[]::text[]) AS argdefaults
FROM pg_proc p
JOIN pg_namespace n ON (p.pronamespace = n.oid)
LEFT JOIN pg_description d ON (p.oid = d.objoid)
WHERE p.proargtypes[0:2] = ARRAY[23::oid, 23::oid, 23::oid]
AND p.proargnames[1:3] = ARRAY['z'::text, 'x'::text, 'y'::text]
AND prorettype = 17
AND has_schema_privilege(n.oid, 'usage')
AND has_function_privilege(Format('%s.%s(%s)', quote_ident(n.nspname), quote_ident(p.proname), oidvectortypes(proargtypes)), 'execute')
ORDER BY 1
`
db, connerr := dbConnect()
if connerr != nil {
return nil, connerr
}
rows, err := db.Query(context.Background(), layerSQL)
if err != nil {
return nil, err
}
// Reset array of layers
layerFunctions := make([]LayerFunction, 0)
for rows.Next() {
var (
id, schema, function, description string
argnames, argtypes, argdefaults []string
)
err := rows.Scan(&id, &schema, &function, &description, &argnames, &argtypes, &argdefaults)
if err != nil {
log.Fatal(err)
}
args := make(map[string]FunctionArgument)
arglen := len(argnames)
defstart := arglen - len(argdefaults)
// First three arguments have to be z, x, y
for i := 3; i < arglen; i++ {
argdef := ""
if i-defstart >= 0 {
argdef = argdefaults[i-defstart]
}
args[argnames[i]] = FunctionArgument{
order: i - 3,
Name: argnames[i],
Type: argtypes[i],
Default: parseArgDefault(argdef),
}
}
lyr := LayerFunction{
ID: id,
Schema: schema,
Function: function,
Description: description,
Arguments: args,
}
layerFunctions = append(layerFunctions, lyr)
}
// Check for errors from iterating over rows.
if err := rows.Err(); err != nil {
return nil, err
}
rows.Close()
return layerFunctions, nil
}
// parseArgDefault parses a default for an argument to a function-based
// tile layer. Most default arguments don't require special handling,
// but some are returned quoted with a type; e.g. a negative integer
// is `'-123'::integer` instead of `-123`.
func parseArgDefault(arg string) string {
// check for a value in the value::type format
sp := strings.Split(arg, "::")
if len(sp) > 1 {
// join back all but the last split parts.
// this allows for the edge case of a double colon :: in text strings
val := strings.Join(sp[:len(sp)-1], "::")
// check for a value wrapped in single quotes and return the value
// with them stripped. If the value is not wrapped in quotes,
// fall back to returning the value as is.
if val[0] == '\'' && val[len(val)-1] == '\'' {
return val[1 : len(val)-1]
}
}
return arg
}