Ejemplo n.º 1
0
// ContextTransaction retrieves the transaction cached within the context (and
// creates one if it hasn't already been cached).
func ContextTransaction(context *hookstate.Context) *Transaction {
	// Check for one already cached
	transaction, ok := context.Cached(cachedTransaction{}).(*Transaction)
	if ok {
		return transaction
	}

	// It wasn't already cached, so create and cache a new one
	transaction = NewTransaction(context.State())

	context.OnDone(func() error {
		transaction.Commit()
		return nil
	})

	context.Cache(cachedTransaction{}, transaction)
	return transaction
}
Ejemplo n.º 2
0
func getTransaction(context *hookstate.Context) (*configstate.Transaction, error) {
	context.Lock()
	defer context.Unlock()

	// Extract the transaction from the context. If none, make one and cache it
	// in the context.
	transaction, ok := context.Cached(cachedTransaction{}).(*configstate.Transaction)
	if !ok {
		var err error
		transaction, err = configstate.NewTransaction(context.State())
		if err != nil {
			return nil, fmt.Errorf("cannot create transaction: %s", err)
		}

		context.OnDone(func() error {
			transaction.Commit()
			return nil
		})

		context.Cache(cachedTransaction{}, transaction)
	}

	return transaction, nil
}