/
assign_update_join.go
100 lines (79 loc) · 2.31 KB
/
assign_update_join.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
package analyzer
import (
"fmt"
"github.com/Ciyfly/FakerMysql/sql"
"github.com/Ciyfly/FakerMysql/sql/expression"
"github.com/Ciyfly/FakerMysql/sql/plan"
)
// modifyUpdateExpressionsForJoin searches for a JOIN for UPDATE query and updates the child of the original update
// node to use a plan.UpdateJoin node as a child.
func modifyUpdateExpressionsForJoin(ctx *sql.Context, a *Analyzer, n sql.Node, scope *Scope) (sql.Node, error) {
switch n := n.(type) {
case *plan.Update:
us, ok := n.Child.(*plan.UpdateSource)
if !ok {
return n, nil
}
var jn sql.Node
plan.Inspect(us, func(node sql.Node) bool {
switch node.(type) {
case *plan.CrossJoin, plan.JoinNode:
jn = node
return false
default:
return true
}
})
if jn == nil {
return n, nil
}
if _, ok = jn.(*plan.InnerJoin); !ok {
return n, sql.ErrUnsupportedFeature.New()
}
updaters, err := rowUpdatersByTable(ctx, us, jn)
if err != nil {
return nil, err
}
uj := plan.NewUpdateJoin(updaters, us)
ret, err := n.WithChildren(uj)
if err != nil {
return nil, err
}
return ret, nil
}
return n, nil
}
// rowUpdatersByTable maps a set of tables to their RowUpdater objects.
func rowUpdatersByTable(ctx *sql.Context, node sql.Node, ij sql.Node) (map[string]sql.RowUpdater, error) {
namesOfTableToBeUpdated := getTablesToBeUpdated(node)
resolvedTables := getTablesByName(ij)
ret := make(map[string]sql.RowUpdater)
for k, v := range resolvedTables {
if _, exists := namesOfTableToBeUpdated[k]; exists {
updatable, ok := v.Table.(sql.UpdatableTable)
if !ok {
continue
}
keyless := sql.IsKeyless(updatable.Schema())
if keyless {
return nil, fmt.Errorf("error: keyless tables unsupported for UPDATE JOIN")
}
ret[k] = updatable.Updater(ctx)
}
}
return ret, nil
}
// getTablesToBeUpdated takes a node and looks for the tables to modified by a SetField.
func getTablesToBeUpdated(node sql.Node) map[string]struct{} {
ret := make(map[string]struct{})
plan.InspectExpressions(node, func(e sql.Expression) bool {
switch e := e.(type) {
case *expression.SetField:
gf := e.Left.(*expression.GetField)
ret[gf.Table()] = struct{}{}
return false
}
return true
})
return ret
}