forked from pgpkg/pgpkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrewrite.go
More file actions
90 lines (76 loc) · 2.46 KB
/
rewrite.go
File metadata and controls
90 lines (76 loc) · 2.46 KB
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
package pgpkg
import (
pg_query "github.com/pganalyze/pg_query_go/v5"
)
// Rewrite the statement source to set the search_path to [schema, temp, public]
// NOTE: rewriting doesn't seem to preserve the quotes in function arguments.
// This appears to be a problem with pg_analyze_go.
func rewrite(stmt *Statement) error {
parseResult, err := pg_query.Parse(stmt.Source)
if err != nil {
return PKGErrorf(stmt, err, "unable to rewrite function")
}
createFuncStmt := parseResult.Stmts[0].Stmt.GetCreateFunctionStmt()
// FIXME: fire an error if search_path or SECURITY DEFINER is already set.
//schemaNames := append([]string{"pgpkg"}, stmt.Unit.Bundle.Package.SchemaNames...)
//schemaNames = append([]string{"pg_temp", "public"}...)
schemaNames := []string{"pgpkg", "pg_temp", "public"}
createFuncStmt.Options = append(createFuncStmt.Options /* getSecurityDefinerOption(), */, getSetSchemaOption(schemaNames))
stmt.Source, err = pg_query.Deparse(parseResult)
if err != nil {
return PKGErrorf(stmt, err, "unable to generate rewritten function")
}
return nil
}
func getSecurityDefinerOption() *pg_query.Node {
return &pg_query.Node{
Node: &pg_query.Node_DefElem{
DefElem: &pg_query.DefElem{
Defname: "security",
Arg: &pg_query.Node{
Node: &pg_query.Node_Boolean{
Boolean: &pg_query.Boolean{
Boolval: true,
},
},
},
},
},
}
}
// Set search path for all functions in the package, to the schemas declared for the package.
// This means you don't need to schema-qualify code inside the package, but it's still a good
// idea.
// See https://www.postgresql.org/docs/current/sql-createfunction.html#SQL-CREATEFUNCTION-SECURITY
func getSetSchemaOption(schemaNames []string) *pg_query.Node {
return &pg_query.Node{
Node: &pg_query.Node_DefElem{
DefElem: &pg_query.DefElem{
Defname: "set",
Arg: &pg_query.Node{
Node: &pg_query.Node_VariableSetStmt{
VariableSetStmt: &pg_query.VariableSetStmt{
Kind: pg_query.VariableSetKind_VAR_SET_VALUE,
Name: "search_path",
Args: getSchemaNameArgs(schemaNames),
IsLocal: false,
},
},
},
},
},
}
}
func getSchemaNameArgs(schemaNames []string) []*pg_query.Node {
var nodes []*pg_query.Node
for _, schema := range schemaNames {
nodes = append(nodes, &pg_query.Node{
Node: &pg_query.Node_AConst{
AConst: &pg_query.A_Const{
Val: &pg_query.A_Const_Sval{&pg_query.String{Sval: schema}},
},
},
})
}
return nodes
}