/
catalog_db_fun.go
287 lines (258 loc) · 8.21 KB
/
catalog_db_fun.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
285
286
287
package data
/*
Copyright 2019 - 2024 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import (
"context"
"fmt"
"time"
"github.com/CrunchyData/pg_featureserv/internal/conf"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
log "github.com/sirupsen/logrus"
)
// FunctionIDColumnName is the name for a function-supplied ID
const FunctionIDColumnName = "id"
const SchemaPostGISFTW = "postgisftw"
func (cat *catalogDB) Functions() ([]*Function, error) {
cat.refreshFunctions(true)
return cat.functions, nil
}
func (cat *catalogDB) FunctionByName(name string) (*Function, error) {
cat.refreshFunctions(false)
fn, ok := cat.functionMap[name]
if !ok {
return nil, nil
}
return fn, nil
}
func (cat *catalogDB) refreshFunctions(force bool) {
// TODO: refresh on timed basis?
if force || !isFunctionsLoaded {
cat.loadFunctions()
}
isFunctionsLoaded = true
}
func (cat *catalogDB) loadFunctions() {
cat.functions, cat.functionMap = readFunctionDefs(cat.dbconn, conf.Configuration.Database.FunctionIncludes)
}
func readFunctionDefs(db *pgxpool.Pool, funSchemas []string) ([]*Function, map[string]*Function) {
sql := sqlFunctions(funSchemas)
log.Debugf("Load function catalog:\n%v", sql)
rows, err := db.Query(context.Background(), sql)
if err != nil {
log.Fatal(err)
}
var functions []*Function
functionMap := make(map[string]*Function)
for rows.Next() {
fn := scanFunctionDef(rows)
// TODO: for now only show geometry functions
//if fn.IsGeometryFunction() {
functions = append(functions, fn)
functionMap[fn.ID] = fn
//}
}
// Check for errors from iterating over rows.
if err := rows.Err(); err != nil {
log.Fatal(err)
}
rows.Close()
return functions, functionMap
}
func scanFunctionDef(rows pgx.Rows) *Function {
var (
id, schema, name, description string
inNamesTA, inTypesTA, inDefaultsTA, outNamesTA, outTypesTA pgtype.TextArray
)
err := rows.Scan(&id, &schema, &name, &description,
&inNamesTA, &inTypesTA, &inDefaultsTA, &outNamesTA, &outTypesTA)
if err != nil {
log.Fatalf("Error reading function catalog: %v", err)
}
inNames := toArray(inNamesTA)
inTypes := toArray(inTypesTA)
inDefaultsDB := toArray(inDefaultsTA)
numNoDefault := len(inNames) - len(inDefaultsDB)
inDefaults := extendLeft(inDefaultsDB, len(inNames))
outNames := toArray(outNamesTA)
outTypes := toArray(outTypesTA)
outJSONTypes := toJSONTypeFromPGArray(outTypes)
inTypeMap := make(map[string]string)
addTypes(inTypeMap, inNames, inTypes)
datatypes := make(map[string]string)
addTypes(datatypes, inNames, inTypes)
addTypes(datatypes, outNames, outTypes)
// synthesize a description if none provided
if description == "" {
description = fmt.Sprintf("The function %v", id)
}
geomCol := geometryColumn(outNames, datatypes)
funDef := Function{
ID: id,
Schema: schema,
Name: name,
Description: description,
InNames: inNames,
InDbTypes: inTypes,
InTypeMap: inTypeMap,
InDefaults: inDefaults,
NumNoDefault: numNoDefault,
OutNames: outNames,
OutDbTypes: outTypes,
OutJSONTypes: outJSONTypes,
Types: datatypes,
GeometryColumn: geomCol,
}
//fmt.Printf("DEBUG: Function definitions: %v\n", funDef)
return &funDef
}
func addTypes(typeMap map[string]string, names []string, types []string) {
for i, name := range names {
typeMap[name] = types[i]
}
}
func geometryColumn(names []string, types map[string]string) string {
// TODO: extract from outNames, outTypes
for _, name := range names {
if types[name] == PGTypeGeometry {
return name
}
}
return ""
}
func toArray(ta pgtype.TextArray) []string {
arrLen := 0
arrStart := 0
if len(ta.Dimensions) > 0 {
arrLen = int(ta.Dimensions[0].Length)
arrStart = int(ta.Dimensions[0].LowerBound - 1)
}
arr := make([]string, arrLen)
for i := arrStart; i < arrLen; i++ {
val := ta.Elements[i].String
arr[i] = val
}
return arr
}
// extendLeft extends an array to have given size, with original contents right-aligned
func extendLeft(arr []string, size int) []string {
if size <= len(arr) {
return arr
}
// create array of requested size and right-justify input
arr2 := make([]string, size)
offset := size - len(arr)
for i := 0; i < len(arr); i++ {
arr2[i+offset] = arr[i]
}
return arr2
}
func (cat *catalogDB) FunctionFeatures(ctx context.Context, name string, args map[string]string, param *QueryParam) ([]string, error) {
fn, err := cat.FunctionByName(name)
if err != nil || fn == nil {
return nil, err
}
errArg := checkArgsValid(fn, args)
if errArg != nil {
log.Debug("ERROR: " + errArg.Error())
return nil, errArg
}
propCols := removeNames(param.Columns, fn.GeometryColumn, "")
idColIndex := indexOfName(propCols, FunctionIDColumnName)
sql, argValues := sqlGeomFunction(fn, args, propCols, param)
log.Debugf("Function features query: %v", sql)
log.Debugf("Function %v Args: %v", name, argValues)
features, err := readFeaturesWithArgs(ctx, cat.dbconn, sql, argValues, idColIndex, propCols)
return features, err
}
func (cat *catalogDB) FunctionData(ctx context.Context, name string, args map[string]string, param *QueryParam) ([]map[string]interface{}, error) {
fn, err := cat.FunctionByName(name)
if err != nil || fn == nil {
return nil, err
}
errArg := checkArgsValid(fn, args)
if errArg != nil {
return nil, errArg
}
propCols := param.Columns
sql, argValues := sqlFunction(fn, args, propCols, param)
log.Debugf("Function data query: %v", sql)
log.Debugf("Function %v Args: %v", name, argValues)
data, err := readDataWithArgs(ctx, cat.dbconn, propCols, sql, argValues)
return data, err
}
// inputArgs extracts function arguments from any provided in the query parameters
// Arg values are stored as strings, and relies on Postgres to convert
// to the actual types required by the function
func checkArgsValid(fn *Function, args map[string]string) error {
for argName := range args {
if _, ok := fn.InTypeMap[argName]; !ok {
return fmt.Errorf("'%v' is not a parameter of function '%v'", argName, fn.ID)
}
}
return nil
}
func removeNames(names []string, ex1 string, ex2 string) []string {
var newNames []string
for _, name := range names {
if name != ex1 && name != ex2 {
newNames = append(newNames, name)
}
}
return newNames
}
func readDataWithArgs(ctx context.Context, db *pgxpool.Pool, propCols []string, sql string, args []interface{}) ([]map[string]interface{}, error) {
start := time.Now()
rows, err := db.Query(context.Background(), sql, args...)
if err != nil {
log.Warnf("Error running Data query: %v", err)
return nil, err
}
defer rows.Close()
data := scanData(ctx, rows, propCols)
log.Debugf(fmtQueryStats, len(data), time.Since(start))
return data, nil
}
func scanData(ctx context.Context, rows pgx.Rows, propCols []string) []map[string]interface{} {
// init data array to empty (not nil)
var data []map[string]interface{} = []map[string]interface{}{}
for rows.Next() {
obj := scanDataRow(rows, true, propCols)
//log.Println(feature)
data = append(data, obj)
}
// context check done outside rows loop,
// because a long-running function might not produce any rows before timeout
if err := ctx.Err(); err != nil {
//log.Debugf("Context error scanning Features: %v", err)
return data
}
// Check for errors from iterating over rows.
if err := rows.Err(); err != nil {
log.Warnf("Error scanning Data rows: %v", err)
// TODO: return nil here ?
}
return data
}
func scanDataRow(rows pgx.Rows, hasID bool, propNames []string) map[string]interface{} {
vals, err := rows.Values()
if err != nil {
log.Warnf("Error getting Data row values: %v", err)
return nil
}
//fmt.Println(vals)
//fmt.Println(geom)
props := extractProperties(vals, 0, propNames)
return props
}