1package db
2
3import (
4	"database/sql"
5	sq "github.com/Masterminds/squirrel"
6
7	"github.com/concourse/concourse/atc/db/lock"
8)
9
10// A lot of struct refer to a pipeline. This is a helper interface that should
11// embedded in those interfaces that need to refer to a pipeline. Accordingly,
12// implementations of those interfaces should embed "pipelineRef".
13type PipelineRef interface {
14	PipelineID() int
15	PipelineName() string
16	Pipeline() (Pipeline, bool, error)
17}
18
19type pipelineRef struct {
20	pipelineID   int
21	pipelineName string
22
23	conn        Conn
24	lockFactory lock.LockFactory
25}
26
27func NewPipelineRef(id int, name string, conn Conn, lockFactory lock.LockFactory) PipelineRef {
28	return pipelineRef{
29		pipelineID:   id,
30		pipelineName: name,
31		conn:         conn,
32		lockFactory:  lockFactory,
33	}
34}
35
36func (r pipelineRef) PipelineID() int {
37	return r.pipelineID
38}
39
40func (r pipelineRef) PipelineName() string {
41	return r.pipelineName
42}
43
44func (r pipelineRef) Pipeline() (Pipeline, bool, error) {
45	if r.PipelineID() == 0 {
46		return nil, false, nil
47	}
48
49	row := pipelinesQuery.
50		Where(sq.Eq{"p.id": r.PipelineID()}).
51		RunWith(r.conn).
52		QueryRow()
53
54	pipeline := newPipeline(r.conn, r.lockFactory)
55	err := scanPipeline(pipeline, row)
56	if err != nil {
57		if err == sql.ErrNoRows {
58			return nil, false, nil
59		}
60		return nil, false, err
61	}
62
63	return pipeline, true, nil
64}
65