Skip to content

Commit f5eb33c

Browse files
lunny6543
andauthored
Fix orphaned objects deletion bug (#15657)
* Fix orphaned objects deletion bug * extend test Co-authored-by: 6543 <[email protected]>
1 parent c80d7f3 commit f5eb33c

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

models/consistency.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -296,11 +296,15 @@ func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
296296

297297
// DeleteOrphanedObjects delete subjects with have no existing refobject anymore
298298
func DeleteOrphanedObjects(subject, refobject, joinCond string) error {
299-
_, err := x.In("id", builder.Select("`"+subject+"`.id").
299+
subQuery := builder.Select("`"+subject+"`.id").
300300
From("`"+subject+"`").
301301
Join("LEFT", "`"+refobject+"`", joinCond).
302-
Where(builder.IsNull{"`" + refobject + "`.id"})).
303-
Delete("`" + subject + "`")
302+
Where(builder.IsNull{"`" + refobject + "`.id"})
303+
sql, args, err := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`").ToSQL()
304+
if err != nil {
305+
return err
306+
}
307+
_, err = x.Exec(append([]interface{}{sql}, args...)...)
304308
return err
305309
}
306310

models/consistency_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2021 Gitea. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package models
6+
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestDeleteOrphanedObjects(t *testing.T) {
14+
assert.NoError(t, PrepareTestDatabase())
15+
16+
countBefore, err := x.Count(&PullRequest{})
17+
assert.NoError(t, err)
18+
19+
_, err = x.Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003})
20+
assert.NoError(t, err)
21+
22+
orphaned, err := CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
23+
assert.NoError(t, err)
24+
assert.EqualValues(t, 3, orphaned)
25+
26+
err = DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
27+
assert.NoError(t, err)
28+
29+
countAfter, err := x.Count(&PullRequest{})
30+
assert.NoError(t, err)
31+
assert.EqualValues(t, countBefore, countAfter)
32+
}

0 commit comments

Comments
 (0)