forked from treeverse/lakeFS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcataloger_diff.go
279 lines (255 loc) · 9.5 KB
/
cataloger_diff.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package catalog
import (
"context"
"errors"
"fmt"
"strings"
sq "github.com/Masterminds/squirrel"
"github.com/google/uuid"
"github.com/treeverse/lakefs/db"
"github.com/treeverse/lakefs/logging"
)
type contextKey string
func (k contextKey) String() string {
return string(k)
}
const (
DiffMaxLimit = 1000
diffResultsTableNamePrefix = "catalog_diff_results"
contextDiffResultsKey contextKey = "diff_results_key"
)
var ErrMissingDiffResultsIDInContext = errors.New("missing diff results id in context")
func (c *cataloger) Diff(ctx context.Context, repository string, leftBranch string, rightBranch string, limit int, after string) (Differences, bool, error) {
if err := Validate(ValidateFields{
{Name: "repository", IsValid: ValidateRepositoryName(repository)},
{Name: "leftBranch", IsValid: ValidateBranchName(leftBranch)},
{Name: "rightBranch", IsValid: ValidateBranchName(rightBranch)},
}); err != nil {
return nil, false, err
}
if limit < 0 || limit > DiffMaxLimit {
limit = DiffMaxLimit
}
ctx, cancel := c.withDiffResultsContext(ctx)
defer cancel()
res, err := c.db.Transact(func(tx db.Tx) (interface{}, error) {
leftID, err := c.getBranchIDCache(tx, repository, leftBranch)
if err != nil {
return nil, fmt.Errorf("left branch: %w", err)
}
rightID, err := c.getBranchIDCache(tx, repository, rightBranch)
if err != nil {
return nil, fmt.Errorf("right branch: %w", err)
}
err = c.doDiff(ctx, tx, leftID, rightID)
if err != nil {
return nil, err
}
return getDiffDifferences(ctx, tx, limit+1, after)
}, c.txOpts(ctx)...)
if err != nil {
return nil, false, err
}
differences := res.(Differences)
hasMore := paginateSlice(&differences, limit)
return differences, hasMore, nil
}
func (c *cataloger) doDiff(ctx context.Context, tx db.Tx, leftID, rightID int64) error {
relation, err := getBranchesRelationType(tx, leftID, rightID)
if err != nil {
return err
}
return c.doDiffByRelation(ctx, tx, relation, leftID, rightID)
}
func (c *cataloger) doDiffByRelation(ctx context.Context, tx db.Tx, relation RelationType, leftID, rightID int64) error {
switch relation {
case RelationTypeFromParent:
return c.diffFromParent(ctx, tx, leftID, rightID)
case RelationTypeFromChild:
return c.diffFromChild(ctx, tx, leftID, rightID)
case RelationTypeNotDirect:
return c.diffNonDirect(ctx, tx, leftID, rightID)
default:
c.log.WithFields(logging.Fields{
"relation_type": relation,
"left_id": leftID,
"right_id": rightID,
}).Debug("Diff by relation - unsupported type")
return ErrFeatureNotSupported
}
}
func (c *cataloger) getDiffSummary(ctx context.Context, tx db.Tx) (map[DifferenceType]int, error) {
var results []struct {
DiffType int `db:"diff_type"`
Count int `db:"count"`
}
diffResultsTableName, err := diffResultsTableNameFromContext(ctx)
if err != nil {
return nil, err
}
err = tx.Select(&results, "SELECT diff_type, count(diff_type) as count FROM "+diffResultsTableName+" GROUP BY diff_type")
if err != nil {
return nil, fmt.Errorf("count diff resutls by type: %w", err)
}
m := make(map[DifferenceType]int, len(results))
for _, res := range results {
m[DifferenceType(res.DiffType)] = res.Count
}
return m, nil
}
func (c *cataloger) diffFromParent(ctx context.Context, tx db.Tx, parentID, childID int64) error {
// get the last child commit number of the last parent merge
// if there is none - then it is the first merge
var maxChildMerge CommitID
childLineage, err := getLineage(tx, childID, UncommittedID)
if err != nil {
return fmt.Errorf("child lineage failed: %w", err)
}
parentLineage, err := getLineage(tx, parentID, CommittedID)
if err != nil {
return fmt.Errorf("parent lineage failed: %w", err)
}
maxChildQuery, args, err := sq.Select("MAX(commit_id) as max_child_commit").
From("catalog_commits").
Where("branch_id = ? AND merge_type = 'from_parent'", childID).
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return fmt.Errorf("get child last commit sql: %w", err)
}
err = tx.Get(&maxChildMerge, maxChildQuery, args...)
if err != nil {
return fmt.Errorf("get child last commit failed: %w", err)
}
diffResultsTableName, err := diffResultsTableNameFromContext(ctx)
if err != nil {
return err
}
diffFromParentSQL, args, err := sqDiffFromParentV(parentID, childID, maxChildMerge, parentLineage, childLineage).
Prefix(`CREATE UNLOGGED TABLE ` + diffResultsTableName + " AS ").
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return fmt.Errorf("diff from parent sql: %w", err)
}
if _, err := tx.Exec(diffFromParentSQL, args...); err != nil {
return fmt.Errorf("select diff from parent: %w", err)
}
return nil
}
func getDiffDifferences(ctx context.Context, tx db.Tx, limit int, after string) (Differences, error) {
diffResultsTableName, err := diffResultsTableNameFromContext(ctx)
if err != nil {
return nil, err
}
var result Differences
query, args, err := psql.Select("diff_type", "path").
From(diffResultsTableName).
Where(sq.Gt{"path": after}).
OrderBy("path").
Limit(uint64(limit)).
ToSql()
if err != nil {
return nil, fmt.Errorf("format diff results query: %w", err)
}
err = tx.Select(&result, query, args...)
if err != nil {
return nil, fmt.Errorf("select diff results: %w", err)
}
return result, nil
}
func (c *cataloger) diffFromChild(ctx context.Context, tx db.Tx, childID, parentID int64) error {
// read last merge commit numbers from commit table
// if it is the first child-to-parent commit, than those commit numbers are calculated as follows:
// the child is 0, as any change in the child was never merged to the parent.
// the parent is the effective commit number of the first lineage record of the child that points to the parent
// it is possible that the child the have already done from_parent merge. so we have to take the minimal effective commit
effectiveCommits := struct {
ParentEffectiveCommit CommitID `db:"parent_effective_commit"` // last commit parent synchronized with child. If non - it is the commit where the child was branched
ChildEffectiveCommit CommitID `db:"child_effective_commit"` // last commit child synchronized to parent. if never - than it is 1 (everything in the child is a change)
}{}
effectiveCommitsQuery, args, err := sq.Select(`commit_id AS parent_effective_commit`, `merge_source_commit AS child_effective_commit`).
From("catalog_commits").
Where("branch_id = ? AND merge_source_branch = ? AND merge_type = 'from_child'", parentID, childID).
OrderBy(`commit_id DESC`).
Limit(1).
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return fmt.Errorf("effective commits sql: %w", err)
}
err = tx.Get(&effectiveCommits, effectiveCommitsQuery, args...)
effectiveCommitsNotFound := errors.Is(err, db.ErrNotFound)
if err != nil && !effectiveCommitsNotFound {
return fmt.Errorf("select effective commit: %w", err)
}
if effectiveCommitsNotFound {
effectiveCommits.ChildEffectiveCommit = 1 // we need all commits from the child. so any small number will do
parentEffectiveQuery, args, err := psql.Select("commit_id as parent_effective_commit").
From("catalog_commits").
Where("branch_id = ? AND merge_source_branch = ?", childID, parentID).
OrderBy("commit_id").
Limit(1).
ToSql()
if err != nil {
return fmt.Errorf("parent effective commit sql: %w", err)
}
err = tx.Get(&effectiveCommits.ParentEffectiveCommit, parentEffectiveQuery, args...)
if err != nil {
return fmt.Errorf("select parent effective commit: %w", err)
}
}
parentLineage, err := getLineage(tx, parentID, UncommittedID)
if err != nil {
return fmt.Errorf("parent lineage failed: %w", err)
}
childLineage, err := getLineage(tx, childID, CommittedID)
if err != nil {
return fmt.Errorf("child lineage failed: %w", err)
}
childLineageValues := getLineageAsValues(childLineage, childID, MaxCommitID)
mainDiffFromChild := sqDiffFromChildV(parentID, childID, effectiveCommits.ParentEffectiveCommit, effectiveCommits.ChildEffectiveCommit, parentLineage, childLineageValues)
diffResultsTableName, err := diffResultsTableNameFromContext(ctx)
if err != nil {
return err
}
diffFromChildSQL, args, err := mainDiffFromChild.
Prefix("CREATE UNLOGGED TABLE " + diffResultsTableName + " AS ").
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return fmt.Errorf("diff from child sql: %w", err)
}
if _, err := tx.Exec(diffFromChildSQL, args...); err != nil {
return fmt.Errorf("exec diff from child: %w", err)
}
return nil
}
// withDiffResultsContext generate diff results id used for temporary table name
func (c *cataloger) withDiffResultsContext(ctx context.Context) (context.Context, context.CancelFunc) {
id := strings.ReplaceAll(uuid.New().String(), "-", "")
return context.WithValue(ctx, contextDiffResultsKey, id), func() {
tableName := diffResultsTableNameFormat(id)
_, err := c.db.Exec("DROP TABLE IF EXISTS " + tableName)
if err != nil {
c.log.WithError(err).WithField("table_name", tableName).Warn("Failed to drop diff results table")
}
}
}
func diffResultsTableNameFromContext(ctx context.Context) (string, error) {
id, ok := ctx.Value(contextDiffResultsKey).(string)
if !ok {
return "", ErrMissingDiffResultsIDInContext
}
return diffResultsTableNameFormat(id), nil
}
func diffResultsTableNameFormat(id string) string {
return diffResultsTableNamePrefix + "_" + id
}
func (c *cataloger) diffNonDirect(_ context.Context, _ db.Tx, leftID, rightID int64) error {
c.log.WithFields(logging.Fields{
"left_id": leftID,
"right_id": rightID,
}).Debug("Diff not direct - feature not supported")
return ErrFeatureNotSupported
}