-
Notifications
You must be signed in to change notification settings - Fork 261
/
functions.go
84 lines (71 loc) · 1.87 KB
/
functions.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
package db_local
import (
"context"
"fmt"
"strings"
"github.com/turbot/steampipe/pkg/constants"
"github.com/turbot/steampipe/pkg/schema"
"github.com/turbot/steampipe/pkg/utils"
)
/**
Query to get functions:
SELECT
p.proname AS function_name
FROM
pg_proc p
LEFT JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE
n.nspname = 'functionSchema'
ORDER BY
function_name;
**/
func refreshFunctions(ctx context.Context) error {
utils.LogTime("db.refreshFunctions start")
defer utils.LogTime("db.refreshFunctions end")
queries := []string{
"lock table pg_namespace;",
fmt.Sprintf(`create schema if not exists %s;`, constants.FunctionSchema),
fmt.Sprintf(`grant usage on schema %s to %s;`, constants.FunctionSchema, constants.DatabaseUsersRole),
}
queries = append(queries, getFunctionAddStrings(constants.Functions)...)
if _, err := executeSqlAsRoot(ctx, queries...); err != nil {
return err
}
return nil
}
func getFunctionAddStrings(functions []schema.SQLFunc) []string {
addStrings := []string{}
for _, function := range functions {
addStrings = append(addStrings, getFunctionAddString(function))
}
return addStrings
}
func getFunctionAddString(function schema.SQLFunc) string {
if err := validateFunction(function); err != nil {
// panic - this should never happen,
// since the function definitions are
// tightly bound to development
panic(err)
}
inputParams := []string{}
for argName, argType := range function.Params {
inputParams = append(inputParams, fmt.Sprintf("%s %s", argName, argType))
}
return strings.TrimSpace(fmt.Sprintf(
`
;create or replace function %s.%s (%s) returns %s language %s as
$$
%s
$$;
`,
constants.FunctionSchema,
function.Name,
strings.Join(inputParams, ","),
function.Returns,
function.Language,
strings.TrimSpace(function.Body),
))
}
func validateFunction(f schema.SQLFunc) error {
return nil
}