2022-06-13 09:37:59 +00:00
|
|
|
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package db
|
|
|
|
|
2022-11-19 08:12:33 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"xorm.io/builder"
|
|
|
|
)
|
2022-06-13 09:37:59 +00:00
|
|
|
|
|
|
|
// CountOrphanedObjects count subjects with have no existing refobject anymore
|
2022-11-19 08:12:33 +00:00
|
|
|
func CountOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) (int64, error) {
|
|
|
|
return GetEngine(ctx).
|
|
|
|
Table("`"+subject+"`").
|
2022-06-13 09:37:59 +00:00
|
|
|
Join("LEFT", "`"+refobject+"`", joinCond).
|
|
|
|
Where(builder.IsNull{"`" + refobject + "`.id"}).
|
|
|
|
Select("COUNT(`" + subject + "`.`id`)").
|
|
|
|
Count()
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteOrphanedObjects delete subjects with have no existing refobject anymore
|
2022-11-19 08:12:33 +00:00
|
|
|
func DeleteOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) error {
|
2022-06-13 09:37:59 +00:00
|
|
|
subQuery := builder.Select("`"+subject+"`.id").
|
|
|
|
From("`"+subject+"`").
|
|
|
|
Join("LEFT", "`"+refobject+"`", joinCond).
|
|
|
|
Where(builder.IsNull{"`" + refobject + "`.id"})
|
|
|
|
b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`")
|
2022-11-19 08:12:33 +00:00
|
|
|
_, err := GetEngine(ctx).Exec(b)
|
2022-06-13 09:37:59 +00:00
|
|
|
return err
|
|
|
|
}
|