| 46 | } |
| 47 | |
| 48 | func (s *Store) CreateRelease(ctx context.Context, release *ReleaseMessage, creator string) (*ReleaseMessage, error) { |
| 49 | p, err := protojson.Marshal(release.Payload) |
| 50 | if err != nil { |
| 51 | return nil, errors.Wrapf(err, "failed to marshal release payload") |
| 52 | } |
| 53 | |
| 54 | tx, err := s.GetDB().BeginTx(ctx, nil) |
| 55 | if err != nil { |
| 56 | return nil, errors.Wrapf(err, "failed to begin tx") |
| 57 | } |
| 58 | defer tx.Rollback() |
| 59 | |
| 60 | // Atomically get next iteration for (project, train) |
| 61 | // Lock all rows for this (project, train) to prevent concurrent inserts with same iteration |
| 62 | var maxIteration sql.NullInt64 |
| 63 | err = tx.QueryRowContext(ctx, |
| 64 | `SELECT COALESCE(MAX(iteration), -1) FROM ( |
| 65 | SELECT iteration FROM release WHERE project = $1 AND train = $2 FOR UPDATE |
| 66 | ) sub`, |
| 67 | release.ProjectID, release.Train, |
| 68 | ).Scan(&maxIteration) |
| 69 | if err != nil && err != sql.ErrNoRows { |
| 70 | return nil, errors.Wrapf(err, "failed to get max iteration") |
| 71 | } |
| 72 | |
| 73 | nextIteration := int32(0) |
| 74 | if maxIteration.Valid { |
| 75 | nextIteration = int32(maxIteration.Int64) + 1 |
| 76 | } |
| 77 | |
| 78 | // Compute release_id = train + formatted iteration |
| 79 | releaseID := fmt.Sprintf("%s%02d", release.Train, nextIteration) |
| 80 | |
| 81 | q := qb.Q().Space(` |
| 82 | INSERT INTO release ( |
| 83 | creator, |
| 84 | project, |
| 85 | payload, |
| 86 | release_id, |
| 87 | train, |
| 88 | iteration, |
| 89 | category |
| 90 | ) VALUES ( |
| 91 | ?, |
| 92 | ?, |
| 93 | ?, |
| 94 | ?, |
| 95 | ?, |
| 96 | ?, |
| 97 | ? |
| 98 | ) RETURNING created_at |
| 99 | `, creator, release.ProjectID, p, releaseID, release.Train, nextIteration, release.Category) |
| 100 | |
| 101 | query, args, err := q.ToSQL() |
| 102 | if err != nil { |
| 103 | return nil, errors.Wrapf(err, "failed to build sql") |
| 104 | } |
| 105 | |