forked from forgejo/forgejo
[PORT] gitea#30190: Add unique index for project_issue to prevent duplicate data
Fix #27639 --- Remove MSSQL specific code per https://codeberg.org/forgejo/discussions/issues/122 (cherry picked from commit b4825670596fe745cebdcc63a8ead4388602d42c)
This commit is contained in:
parent
efc2f53954
commit
f0004760f6
5 changed files with 124 additions and 0 deletions
44
models/migrations/v1_23/v294.go
Normal file
44
models/migrations/v1_23/v294.go
Normal file
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
// AddUniqueIndexForProjectIssue adds unique indexes for project issue table
|
||||
func AddUniqueIndexForProjectIssue(x *xorm.Engine) error {
|
||||
// remove possible duplicated records in table project_issue
|
||||
type result struct {
|
||||
IssueID int64
|
||||
ProjectID int64
|
||||
Cnt int
|
||||
}
|
||||
var results []result
|
||||
if err := x.Select("issue_id, project_id, count(*) as cnt").
|
||||
Table("project_issue").
|
||||
GroupBy("issue_id, project_id").
|
||||
Having("count(*) > 1").
|
||||
Find(&results); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range results {
|
||||
var ids []int64
|
||||
if err := x.SQL("SELECT id FROM project_issue WHERE issue_id = ? and project_id = ? limit ?", r.IssueID, r.ProjectID, r.Cnt-1).Find(&ids); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := x.Table("project_issue").In("id", ids).Delete(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// add unique index for project_issue table
|
||||
type ProjectIssue struct { //revive:disable-line:exported
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
IssueID int64 `xorm:"INDEX unique(s)"`
|
||||
ProjectID int64 `xorm:"INDEX unique(s)"`
|
||||
}
|
||||
|
||||
return x.Sync(new(ProjectIssue))
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue