forked from sqlc-dev/sqlc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
82 lines (77 loc) · 2.13 KB
/
cmd.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
package validate
import (
"errors"
"fmt"
"github.com/michaelzx/sqlc-stand-alone-queries-struct/internal/metadata"
"github.com/michaelzx/sqlc-stand-alone-queries-struct/internal/sql/ast"
)
func validateCopyfrom(n ast.Node) error {
stmt, ok := n.(*ast.InsertStmt)
if !ok {
return errors.New(":copyfrom requires an INSERT INTO statement")
}
if stmt.OnConflictClause != nil {
return errors.New(":copyfrom is not compatible with ON CONFLICT")
}
if stmt.WithClause != nil {
return errors.New(":copyfrom is not compatible with WITH clauses")
}
if stmt.ReturningList != nil && len(stmt.ReturningList.Items) > 0 {
return errors.New(":copyfrom is not compatible with RETURNING")
}
sel, ok := stmt.SelectStmt.(*ast.SelectStmt)
if !ok {
return nil
}
if len(sel.FromClause.Items) > 0 {
return errors.New(":copyfrom is not compatible with INSERT INTO ... SELECT")
}
if sel.ValuesLists == nil || len(sel.ValuesLists.Items) != 1 {
return errors.New(":copyfrom requires exactly one example row to be inserted")
}
sublist, ok := sel.ValuesLists.Items[0].(*ast.List)
if !ok {
return nil
}
for _, v := range sublist.Items {
if _, ok := v.(*ast.ParamRef); !ok {
return errors.New(":copyfrom doesn't support non-parameter values")
}
}
return nil
}
func validateBatch(n ast.Node) error {
nums, _, _ := ParamRef(n)
if len(nums) == 0 {
return errors.New(":batch* commands require parameters")
}
return nil
}
func Cmd(n ast.Node, name, cmd string) error {
if cmd == metadata.CmdCopyFrom {
return validateCopyfrom(n)
}
if (cmd == metadata.CmdBatchExec || cmd == metadata.CmdBatchMany) || cmd == metadata.CmdBatchOne {
return validateBatch(n)
}
if !(cmd == metadata.CmdMany || cmd == metadata.CmdOne) {
return nil
}
var list *ast.List
switch stmt := n.(type) {
case *ast.SelectStmt:
return nil
case *ast.DeleteStmt:
list = stmt.ReturningList
case *ast.InsertStmt:
list = stmt.ReturningList
case *ast.UpdateStmt:
list = stmt.ReturningList
default:
return nil
}
if list == nil || len(list.Items) == 0 {
return fmt.Errorf("query %q specifies parameter %q without containing a RETURNING clause", name, cmd)
}
return nil
}