github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/db/component.go (about) 1 package db 2 3 import ( 4 "database/sql" 5 "time" 6 7 sq "github.com/Masterminds/squirrel" 8 "github.com/lib/pq" 9 ) 10 11 var componentsQuery = psql.Select("c.id, c.name, c.interval, c.last_ran, c.paused"). 12 From("components c") 13 14 //go:generate counterfeiter . Component 15 16 type Component interface { 17 ID() int 18 Name() string 19 Interval() time.Duration 20 LastRan() time.Time 21 Paused() bool 22 23 Reload() (bool, error) 24 IntervalElapsed() bool 25 UpdateLastRan() error 26 } 27 28 type component struct { 29 id int 30 name string 31 interval time.Duration 32 lastRan time.Time 33 paused bool 34 35 conn Conn 36 } 37 38 func (c *component) ID() int { return c.id } 39 func (c *component) Name() string { return c.name } 40 func (c *component) Interval() time.Duration { return c.interval } 41 func (c *component) LastRan() time.Time { return c.lastRan } 42 func (c *component) Paused() bool { return c.paused } 43 44 func (c *component) Reload() (bool, error) { 45 row := componentsQuery.Where(sq.Eq{"c.id": c.id}). 46 RunWith(c.conn). 47 QueryRow() 48 49 err := scanComponent(c, row) 50 if err != nil { 51 if err == sql.ErrNoRows { 52 return false, nil 53 } 54 return false, err 55 } 56 57 return true, nil 58 } 59 60 func (c *component) IntervalElapsed() bool { 61 return time.Now().After(c.lastRan.Add(c.interval)) 62 } 63 64 func (c *component) UpdateLastRan() error { 65 _, err := psql.Update("components"). 66 Set("last_ran", sq.Expr("now()")). 67 Where(sq.Eq{ 68 "id": c.id, 69 }). 70 RunWith(c.conn). 71 Exec() 72 if err != nil { 73 return err 74 } 75 76 return nil 77 } 78 79 func scanComponent(c *component, row scannable) error { 80 var ( 81 lastRan pq.NullTime 82 interval string 83 ) 84 85 err := row.Scan( 86 &c.id, 87 &c.name, 88 &interval, 89 &lastRan, 90 &c.paused, 91 ) 92 if err != nil { 93 return err 94 } 95 96 c.lastRan = lastRan.Time 97 98 c.interval, err = time.ParseDuration(interval) 99 if err != nil { 100 return err 101 } 102 103 return nil 104 }