Skip to content

Commit cefcc76

Browse files
6543lunny
andauthored
Fix orphaned objects deletion bug (#15657) (#15682)
* Fix orphaned objects deletion bug * extend test Co-authored-by: 6543 <[email protected]> Co-authored-by: Lunny Xiao <[email protected]>
1 parent 05f266c commit cefcc76

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
@@ -297,11 +297,15 @@ func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
297297

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

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)