forked from sqlc-dev/sqlc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.go
More file actions
122 lines (112 loc) · 2.5 KB
/
func.go
File metadata and controls
122 lines (112 loc) · 2.5 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
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
package catalog
import (
"errors"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/sqlerr"
)
// Function describes a database function
//
// A database function is a method written to perform a specific operation on data within the database.
type Function struct {
Name string
Args []*Argument
ReturnType *ast.TypeName
Comment string
Desc string
ReturnTypeNullable bool
}
type Argument struct {
Name string
Type *ast.TypeName
HasDefault bool
Mode ast.FuncParamMode
}
func (f *Function) InArgs() []*Argument {
var args []*Argument
for _, a := range f.Args {
switch a.Mode {
case ast.FuncParamTable, ast.FuncParamOut:
continue
default:
args = append(args, a)
}
}
return args
}
func (f *Function) OutArgs() []*Argument {
var args []*Argument
for _, a := range f.Args {
switch a.Mode {
case ast.FuncParamOut:
args = append(args, a)
}
}
return args
}
func (c *Catalog) createFunction(stmt *ast.CreateFunctionStmt) error {
ns := stmt.Func.Schema
if ns == "" {
ns = c.DefaultSchema
}
s, err := c.getSchema(ns)
if err != nil {
return err
}
fn := &Function{
Name: stmt.Func.Name,
Args: make([]*Argument, len(stmt.Params.Items)),
ReturnType: stmt.ReturnType,
}
types := make([]*ast.TypeName, len(stmt.Params.Items))
for i, item := range stmt.Params.Items {
arg := item.(*ast.FuncParam)
var name string
if arg.Name != nil {
name = *arg.Name
}
fn.Args[i] = &Argument{
Name: name,
Type: arg.Type,
Mode: arg.Mode,
HasDefault: arg.DefExpr != nil,
}
types[i] = arg.Type
}
_, idx, err := s.getFunc(stmt.Func, types)
if err == nil && !stmt.Replace {
return sqlerr.RelationExists(stmt.Func.Name)
}
if idx >= 0 {
s.Funcs[idx] = fn
} else {
s.Funcs = append(s.Funcs, fn)
}
return nil
}
func (c *Catalog) dropFunction(stmt *ast.DropFunctionStmt) error {
for _, spec := range stmt.Funcs {
ns := spec.Name.Schema
if ns == "" {
ns = c.DefaultSchema
}
s, err := c.getSchema(ns)
if errors.Is(err, sqlerr.NotFound) && stmt.MissingOk {
continue
} else if err != nil {
return err
}
var idx int
if spec.HasArgs {
_, idx, err = s.getFunc(spec.Name, spec.Args)
} else {
_, idx, err = s.getFuncByName(spec.Name)
}
if errors.Is(err, sqlerr.NotFound) && stmt.MissingOk {
continue
} else if err != nil {
return err
}
s.Funcs = append(s.Funcs[:idx], s.Funcs[idx+1:]...)
}
return nil
}