code.gitea.io/gitea@v1.22.3/models/migrations/v1_22/v294.go (about)

     1  // Copyright 2024 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package v1_22 //nolint
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"xorm.io/xorm"
    10  	"xorm.io/xorm/schemas"
    11  )
    12  
    13  // AddUniqueIndexForProjectIssue adds unique indexes for project issue table
    14  func AddUniqueIndexForProjectIssue(x *xorm.Engine) error {
    15  	// remove possible duplicated records in table project_issue
    16  	type result struct {
    17  		IssueID   int64
    18  		ProjectID int64
    19  		Cnt       int
    20  	}
    21  	var results []result
    22  	if err := x.Select("issue_id, project_id, count(*) as cnt").
    23  		Table("project_issue").
    24  		GroupBy("issue_id, project_id").
    25  		Having("count(*) > 1").
    26  		Find(&results); err != nil {
    27  		return err
    28  	}
    29  	for _, r := range results {
    30  		if x.Dialect().URI().DBType == schemas.MSSQL {
    31  			if _, err := x.Exec(fmt.Sprintf("delete from project_issue where id in (SELECT top %d id FROM project_issue WHERE issue_id = ? and project_id = ?)", r.Cnt-1), r.IssueID, r.ProjectID); err != nil {
    32  				return err
    33  			}
    34  		} else {
    35  			var ids []int64
    36  			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 {
    37  				return err
    38  			}
    39  			if _, err := x.Table("project_issue").In("id", ids).Delete(); err != nil {
    40  				return err
    41  			}
    42  		}
    43  	}
    44  
    45  	// add unique index for project_issue table
    46  	type ProjectIssue struct { //revive:disable-line:exported
    47  		ID        int64 `xorm:"pk autoincr"`
    48  		IssueID   int64 `xorm:"INDEX unique(s)"`
    49  		ProjectID int64 `xorm:"INDEX unique(s)"`
    50  	}
    51  
    52  	return x.Sync(new(ProjectIssue))
    53  }