github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/db/component_factory.go (about)

     1  package db
     2  
     3  import (
     4  	"database/sql"
     5  
     6  	sq "github.com/Masterminds/squirrel"
     7  	"github.com/pf-qiu/concourse/v6/atc"
     8  )
     9  
    10  //go:generate counterfeiter . ComponentFactory
    11  
    12  type ComponentFactory interface {
    13  	CreateOrUpdate(atc.Component) (Component, error)
    14  	Find(string) (Component, bool, error)
    15  }
    16  
    17  type componentFactory struct {
    18  	conn Conn
    19  }
    20  
    21  func NewComponentFactory(conn Conn) ComponentFactory {
    22  	return &componentFactory{
    23  		conn: conn,
    24  	}
    25  }
    26  
    27  func (f *componentFactory) Find(componentName string) (Component, bool, error) {
    28  	component := &component{
    29  		conn: f.conn,
    30  	}
    31  
    32  	row := componentsQuery.
    33  		Where(sq.Eq{"c.name": componentName}).
    34  		RunWith(f.conn).
    35  		QueryRow()
    36  
    37  	err := scanComponent(component, row)
    38  	if err != nil {
    39  		if err == sql.ErrNoRows {
    40  			return nil, false, nil
    41  		}
    42  		return nil, false, err
    43  	}
    44  
    45  	return component, true, nil
    46  }
    47  
    48  func (f *componentFactory) CreateOrUpdate(c atc.Component) (Component, error) {
    49  	tx, err := f.conn.Begin()
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	defer Rollback(tx)
    55  
    56  	obj := &component{
    57  		conn: f.conn,
    58  	}
    59  
    60  	row := psql.Insert("components").
    61  		Columns("name", "interval").
    62  		Values(c.Name, c.Interval.String()).
    63  		Suffix(`
    64  			ON CONFLICT (name) DO UPDATE SET interval=EXCLUDED.interval
    65  			RETURNING id, name, interval, last_ran, paused
    66  		`).
    67  		RunWith(tx).
    68  		QueryRow()
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  
    73  	err = scanComponent(obj, row)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  
    78  	err = tx.Commit()
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  
    83  	return obj, nil
    84  }