github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/db/migration/migrations/1551384520_fix_build_private_plan.up.go (about)

     1  package migrations
     2  
     3  import (
     4  	"database/sql"
     5  	"encoding/json"
     6  )
     7  
     8  func (self *migrations) Up_1550160079() error {
     9  
    10  	type build struct {
    11  		id    int
    12  		plan  sql.NullString
    13  		nonce sql.NullString
    14  	}
    15  
    16  	tx, err := self.DB.Begin()
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	defer tx.Rollback()
    22  
    23  	rows, err := tx.Query("SELECT id, private_plan, nonce FROM builds WHERE private_plan IS NOT NULL")
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	builds := []build{}
    29  	for rows.Next() {
    30  
    31  		build := build{}
    32  		if err = rows.Scan(&build.id, &build.plan, &build.nonce); err != nil {
    33  			return err
    34  		}
    35  
    36  		if build.plan.Valid {
    37  			builds = append(builds, build)
    38  		}
    39  	}
    40  
    41  	for _, build := range builds {
    42  
    43  		var noncense *string
    44  		if build.nonce.Valid {
    45  			noncense = &build.nonce.String
    46  		}
    47  
    48  		decrypted, err := self.Strategy.Decrypt(build.plan.String, noncense)
    49  		if err != nil {
    50  			return err
    51  		}
    52  
    53  		var payload map[string]interface{}
    54  		err = json.Unmarshal(decrypted, &payload)
    55  		if err != nil {
    56  			return err
    57  		}
    58  
    59  		fixed, err := json.Marshal(payload["plan"])
    60  		if err != nil {
    61  			return err
    62  		}
    63  
    64  		encrypted, newnonce, err := self.Strategy.Encrypt(fixed)
    65  		if err != nil {
    66  			return err
    67  		}
    68  
    69  		_, err = tx.Exec("UPDATE builds SET private_plan = $1, nonce = $2 WHERE id = $3", encrypted, newnonce, build.id)
    70  		if err != nil {
    71  			return err
    72  		}
    73  	}
    74  
    75  	return tx.Commit()
    76  }