code.gitea.io/gitea@v1.21.7/models/migrations/v1_14/v176.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package v1_14 //nolint
     5  
     6  import (
     7  	"xorm.io/xorm"
     8  )
     9  
    10  // RemoveInvalidLabels looks through the database to look for comments and issue_labels
    11  // that refer to labels do not belong to the repository or organization that repository
    12  // that the issue is in
    13  func RemoveInvalidLabels(x *xorm.Engine) error {
    14  	type Comment struct {
    15  		ID      int64 `xorm:"pk autoincr"`
    16  		Type    int   `xorm:"INDEX"`
    17  		IssueID int64 `xorm:"INDEX"`
    18  		LabelID int64
    19  	}
    20  
    21  	type Issue struct {
    22  		ID     int64 `xorm:"pk autoincr"`
    23  		RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
    24  		Index  int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
    25  	}
    26  
    27  	type Repository struct {
    28  		ID        int64  `xorm:"pk autoincr"`
    29  		OwnerID   int64  `xorm:"UNIQUE(s) index"`
    30  		LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
    31  	}
    32  
    33  	type Label struct {
    34  		ID     int64 `xorm:"pk autoincr"`
    35  		RepoID int64 `xorm:"INDEX"`
    36  		OrgID  int64 `xorm:"INDEX"`
    37  	}
    38  
    39  	type IssueLabel struct {
    40  		ID      int64 `xorm:"pk autoincr"`
    41  		IssueID int64 `xorm:"UNIQUE(s)"`
    42  		LabelID int64 `xorm:"UNIQUE(s)"`
    43  	}
    44  
    45  	if err := x.Sync(new(Comment), new(Issue), new(Repository), new(Label), new(IssueLabel)); err != nil {
    46  		return err
    47  	}
    48  
    49  	if _, err := x.Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
    50  		SELECT il_too.id FROM (
    51  			SELECT il_too_too.id
    52  				FROM issue_label AS il_too_too
    53  					INNER JOIN label ON il_too_too.label_id = label.id
    54  					INNER JOIN issue on issue.id = il_too_too.issue_id
    55  					INNER JOIN repository on repository.id = issue.repo_id
    56  				WHERE
    57  					(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)
    58  	) AS il_too )`); err != nil {
    59  		return err
    60  	}
    61  
    62  	if _, err := x.Exec(`DELETE FROM comment WHERE comment.id IN (
    63  		SELECT il_too.id FROM (
    64  			SELECT com.id
    65  				FROM comment AS com
    66  					INNER JOIN label ON com.label_id = label.id
    67  					INNER JOIN issue on issue.id = com.issue_id
    68  					INNER JOIN repository on repository.id = issue.repo_id
    69  				WHERE
    70  					com.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))
    71  	) AS il_too)`, 7); err != nil {
    72  		return err
    73  	}
    74  
    75  	return nil
    76  }