-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosuretab.go
261 lines (233 loc) · 6.53 KB
/
closuretab.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package closuretab
import (
"context"
"database/sql"
"fmt"
"strings"
)
type AttrType int
const (
Child AttrType = iota
Parent
Depth
)
type AttrMapping = map[AttrType]string
type Querier interface {
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}
type Node struct {
ID int64
ParentID int64
Depth int
}
type ClosureRelation struct {
table string
attrs map[AttrType]string
}
func InitClosureRelation(tableName string, attrs AttrMapping) *ClosureRelation {
return &ClosureRelation{table: tableName, attrs: attrs}
}
func (r *ClosureRelation) GetChildren(ctx context.Context, q Querier, parentID int64) ([]Node, error) {
rows, err := q.QueryContext(
ctx,
fmt.Sprintf(
"SELECT %s, %s, %s FROM %s WHERE %s = ? ORDER BY %s ASC",
r.attrs[Child], r.attrs[Parent], r.attrs[Depth], r.table,
r.attrs[Parent], r.attrs[Depth],
),
parentID,
)
if err != nil {
return nil, fmt.Errorf("get child nodes for parent ID %d: %w", parentID, err)
}
return scanNodes(rows)
}
func (r *ClosureRelation) GetParents(ctx context.Context, q Querier, nodeID int64) ([]Node, error) {
rows, err := q.QueryContext(
ctx,
fmt.Sprintf(
"SELECT %s, %s, %s FROM %s WHERE %s = ? AND %s != ? ORDER BY %s DESC",
r.attrs[Parent], r.attrs[Parent], r.attrs[Depth], r.table,
r.attrs[Child], r.attrs[Parent],
r.attrs[Depth],
),
nodeID, nodeID,
)
if err != nil {
return nil, fmt.Errorf("get parent nodes for node ID %d: %w", nodeID, err)
}
return scanNodes(rows)
}
func (r *ClosureRelation) Insert(ctx context.Context, q Querier, parentID, nodeID int64) (Node, error) {
_, err := q.ExecContext(
ctx,
fmt.Sprintf(
"INSERT INTO %s (%s, %s, %s) "+
"SELECT ?, %s, %s + 1 FROM %s WHERE %s = ?",
r.table, r.attrs[Child], r.attrs[Parent], r.attrs[Depth],
r.attrs[Parent], r.attrs[Depth], r.table, r.attrs[Child],
),
nodeID, parentID,
)
if err != nil {
return Node{}, fmt.Errorf("insert hierarchy references: %w", err)
}
_, err = q.ExecContext(
ctx,
fmt.Sprintf(
"INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)",
r.table, r.attrs[Child], r.attrs[Parent], r.attrs[Depth],
),
nodeID, nodeID, 0,
)
if err != nil {
return Node{}, fmt.Errorf("insert self-reference: %w", err)
}
return Node{}, nil
}
func (r *ClosureRelation) Delete(ctx context.Context, q Querier, nodeID int64) error {
if _, err := q.ExecContext(
ctx,
fmt.Sprintf(
"DELETE FROM %s WHERE %s IN (SELECT %s FROM %s WHERE %s = ?)",
r.table, r.attrs[Child], r.attrs[Child], r.table, r.attrs[Parent],
),
nodeID,
); err != nil {
return fmt.Errorf("remove node ID %d: %w", nodeID, err)
}
if _, err := q.ExecContext(
ctx,
fmt.Sprintf(
"DELETE FROM %s WHERE %s = ? OR %s = ?",
r.table, r.attrs[Child], r.attrs[Parent],
),
nodeID, nodeID,
); err != nil {
return fmt.Errorf("remove node ID %d: %w", nodeID, err)
}
return nil
}
func (r *ClosureRelation) Move(ctx context.Context, q Querier, nodeID, newParentID int64) error {
if _, deleteErr := q.ExecContext(
ctx,
fmt.Sprintf(
"DELETE FROM %s "+
"WHERE %s IN "+
"(SELECT %s FROM %s WHERE %s = ?) "+
"AND %s IN "+
"(SELECT %s FROM %s WHERE %s = ? AND %s != %s) ",
r.table,
r.attrs[Child],
r.attrs[Child], r.table, r.attrs[Parent],
r.attrs[Parent],
r.attrs[Parent], r.table, r.attrs[Child], r.attrs[Parent], r.attrs[Child],
),
nodeID, nodeID,
); deleteErr != nil {
return fmt.Errorf("remove node ID %d: %w", nodeID, deleteErr)
}
parents, err := r.GetParents(ctx, q, newParentID)
if err != nil {
return fmt.Errorf("get new parents for moved nodes: %w", err)
}
parentIDs := NodeIDs(parents)
parentIDs = append(parentIDs, newParentID)
parentIDsPlaceholders := makePlaceholders("?", len(parentIDs))
children, err := r.GetChildren(ctx, q, nodeID)
if err != nil {
return fmt.Errorf("get all nodes being moved: %w", err)
}
childrenIDs := NodeIDs(children)
childrenIDsPlaceholders := makePlaceholders("?", len(childrenIDs))
args := make([]interface{}, len(parentIDs)+len(childrenIDs))
for i := 0; i < len(args); i++ {
if i < len(parentIDs) {
args[i] = parentIDs[i]
} else {
args[i] = childrenIDs[i-len(parentIDs)]
}
}
query := fmt.Sprintf(
`INSERT INTO %s (%s, %s, %s)
SELECT supertree.%s, subtree.%s, MAX(supertree.%s + subtree.%s + 1)
FROM %s AS supertree, %s AS subtree
WHERE
supertree.%s IN %s
AND subtree.%s IN %s
GROUP BY supertree.%s, subtree.%s`,
r.table, r.attrs[Parent], r.attrs[Child], r.attrs[Depth],
r.attrs[Parent], r.attrs[Child], r.attrs[Depth], r.attrs[Depth],
r.table, r.table,
r.attrs[Parent], parentIDsPlaceholders,
r.attrs[Child], childrenIDsPlaceholders,
r.attrs[Parent], r.attrs[Child],
)
if _, insertErr := q.ExecContext(
ctx,
query,
args...,
); insertErr != nil {
return fmt.Errorf("insert nodes under new parent: %w", insertErr)
}
return nil
}
func (r *ClosureRelation) Empty(ctx context.Context, q Querier) (bool, error) {
row := q.QueryRowContext(ctx, fmt.Sprintf("SELECT count(*) FROM %s", r.table))
var cnt int
if err := row.Scan(&cnt); err != nil {
return false, fmt.Errorf("count closure table rows: %w", err)
}
return cnt == 0, nil
}
func NodeIDs(nodes []Node) []int64 {
res := make([]int64, 0, len(nodes))
for i := range nodes {
res = append(res, nodes[i].ID)
}
return res
}
type scanner interface {
Scan(dest ...interface{}) error
}
func scanNodes(rows *sql.Rows) ([]Node, error) {
result := make([]Node, 0)
if _, scanErr := scanEachRow(rows, func(s scanner) error {
n := Node{}
if rowErr := s.Scan(&n.ID, &n.ParentID, &n.Depth); rowErr != nil {
return rowErr
}
result = append(result, n)
return nil
}); scanErr != nil {
return nil, fmt.Errorf("scan nodes: %w", scanErr)
}
return result, nil
}
func scanEachRow(rows *sql.Rows, scanRow func(s scanner) error) (rowsProcessed int, err error) {
defer func() { _ = rows.Close() }()
count := 0
for rows.Next() {
err = scanRow(rows)
if err != nil {
return 0, fmt.Errorf("scan row: %w", err)
}
count++
}
if err = rows.Err(); err != nil {
if err == sql.ErrNoRows {
return 0, nil
}
return 0, fmt.Errorf("rows scan: %w", err)
}
return count, nil
}
func makePlaceholders(pHolder string, argLen int) string {
pHolders := make([]string, argLen)
for i := 0; i < argLen; i++ {
pHolders[i] = pHolder
}
return fmt.Sprintf("(%s)", strings.Join(pHolders, ", "))
}