launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/state/sequence.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package state
     5  
     6  import (
     7  	"labix.org/v2/mgo"
     8  	"labix.org/v2/mgo/bson"
     9  	"launchpad.net/errgo/errors"
    10  )
    11  
    12  type sequenceDoc struct {
    13  	Name    string `bson:"_id"`
    14  	Counter int
    15  }
    16  
    17  func (s *State) sequence(name string) (int, error) {
    18  	query := s.db.C("sequence").Find(D{{"_id", name}})
    19  	inc := mgo.Change{
    20  		Update: bson.M{"$inc": bson.M{"counter": 1}},
    21  		Upsert: true,
    22  	}
    23  	result := &sequenceDoc{}
    24  	_, err := query.Apply(inc, result)
    25  	if err != nil {
    26  		return -1, errors.Notef(err, "cannot increment %q sequence number", name)
    27  	}
    28  	return result.Counter, nil
    29  }