2022-06-13 03:37:59 -06:00
|
|
|
// Copyright 2022 The Gitea Authors. All rights reserved.
|
2022-11-27 11:20:29 -07:00
|
|
|
// SPDX-License-Identifier: MIT
|
2022-06-13 03:37:59 -06:00
|
|
|
|
|
|
|
package db
|
|
|
|
|
2022-11-19 01:12:33 -07:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"xorm.io/builder"
|
|
|
|
)
|
2022-06-13 03:37:59 -06:00
|
|
|
|
|
|
|
// CountOrphanedObjects count subjects with have no existing refobject anymore
|
2024-04-07 22:13:34 -06:00
|
|
|
func CountOrphanedObjects(ctx context.Context, subject, refObject, joinCond string) (int64, error) {
|
2022-11-19 01:12:33 -07:00
|
|
|
return GetEngine(ctx).
|
|
|
|
Table("`"+subject+"`").
|
2024-04-07 22:13:34 -06:00
|
|
|
Join("LEFT", "`"+refObject+"`", joinCond).
|
|
|
|
Where(builder.IsNull{"`" + refObject + "`.id"}).
|
2022-06-13 03:37:59 -06:00
|
|
|
Select("COUNT(`" + subject + "`.`id`)").
|
|
|
|
Count()
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteOrphanedObjects delete subjects with have no existing refobject anymore
|
2024-04-07 22:13:34 -06:00
|
|
|
func DeleteOrphanedObjects(ctx context.Context, subject, refObject, joinCond string) error {
|
2022-06-13 03:37:59 -06:00
|
|
|
subQuery := builder.Select("`"+subject+"`.id").
|
|
|
|
From("`"+subject+"`").
|
2024-04-07 22:13:34 -06:00
|
|
|
Join("LEFT", "`"+refObject+"`", joinCond).
|
|
|
|
Where(builder.IsNull{"`" + refObject + "`.id"})
|
2022-06-13 03:37:59 -06:00
|
|
|
b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`")
|
2022-11-19 01:12:33 -07:00
|
|
|
_, err := GetEngine(ctx).Exec(b)
|
2022-06-13 03:37:59 -06:00
|
|
|
return err
|
|
|
|
}
|