github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/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  	"fmt"
     8  
     9  	"labix.org/v2/mgo"
    10  	"labix.org/v2/mgo/bson"
    11  )
    12  
    13  type sequenceDoc struct {
    14  	Name    string `bson:"_id"`
    15  	Counter int
    16  }
    17  
    18  func (s *State) sequence(name string) (int, error) {
    19  	query := s.db.C("sequence").Find(bson.D{{"_id", name}})
    20  	inc := mgo.Change{
    21  		Update: bson.M{"$inc": bson.M{"counter": 1}},
    22  		Upsert: true,
    23  	}
    24  	result := &sequenceDoc{}
    25  	_, err := query.Apply(inc, result)
    26  	if err != nil {
    27  		return -1, fmt.Errorf("cannot increment %q sequence number: %v", name, err)
    28  	}
    29  	return result.Counter, nil
    30  }