// Commit writes all changes to disk.
// An error is returned when a write error occurs, or when a Commit() is called
// from a read-only transaction.
324711
func (tx *Tx) Commit() error {
	if tx.funcd {
		panic("managed tx commit not allowed")
	}
	if tx.db == nil {
		return ErrTxClosed
	} else if !tx.writable {
		return ErrTxNotWritable
	}
	var err error
	if tx.db.persist && (len(tx.wc.commitItems) > 0 || tx.wc.rbkeys != nil) {
		tx.db.buf = tx.db.buf[:0]
		// write a flushdb if a deleteAll was called.
		if tx.wc.rbkeys != nil {
			tx.db.buf = append(tx.db.buf, "*1\r\n$7\r\nflushdb\r\n"...)
		}
		// Each committed record is written to disk
		for key, item := range tx.wc.commitItems {
			if item == nil {
				tx.db.buf = (&dbItem{key: key}).writeDeleteTo(tx.db.buf)
			} else {
				tx.db.buf = item.writeSetTo(tx.db.buf)
			}
		}
		// Flushing the buffer only once per transaction.
		// If this operation fails then the write did failed and we must
		// rollback.
		if _, err = tx.db.file.Write(tx.db.buf); err != nil {
			tx.rollbackInner()
		}
		if tx.db.config.SyncPolicy == Always {
			_ = tx.db.file.Sync()
		}
		// Increment the number of flushes. The background syncing uses this.
		tx.db.flushes++
	}
	// Unlock the database and allow for another writable transaction.
	tx.unlock()
	// Clear the db field to disable this transaction from future use.
	tx.db = nil
	return err
}
879643
func (t *Transaction) Commit() ([]*Reply, error) {
	if t.conn.state != connStateConnected {
		return nil, ErrNotConnected
	}
	t.commands = append(t.commands, NewCommand("EXEC"))
	if t.conn.RequestTimeout != 0 {
		t.conn.tcpConn.SetWriteDeadline(time.Now().Add(t.conn.RequestTimeout * time.Duration(len(t.commands)/10+1)))
	}
	for _, cmd := range t.commands {
		err := cmd.writeCommand(t.conn)
		if err != nil {
			t.conn.fail()
			return nil, ErrWrite
		}
	}
	err := t.conn.wb.Flush()
	if err != nil {
		t.conn.fail()
		return nil, ErrWrite
	}
	if t.conn.RequestTimeout != 0 {
		t.conn.tcpConn.SetReadDeadline(time.Now().Add(t.conn.RequestTimeout * time.Duration(len(t.commands)/10+1)))
	}
	replies := make([]*Reply, len(t.commands))
	for i := range replies {
		rep, err := readReply(t.conn)
		if err != nil {
			t.conn.fail()
			return nil, err
		}
		replies[i] = rep
	}
	execReply := replies[len(replies)-1]
	if execReply.IsError() {
		return replies, ErrTransactionAborted
	}
	if execReply.IsNil() {
		return replies, ErrKeyChanged
	}
	if !execReply.IsArray() {
		t.conn.fail()
		return replies, ErrType
	}
	return execReply.Array()
}
367258
func (historyDB *historyDB) Commit(block *common.Block) error {

	blockNo := block.Header.Number
	//Set the starting tranNo to 0
	var tranNo uint64

	dbBatch := leveldbhelper.NewUpdateBatch()

	logger.Debugf("Channel [%s]: Updating history database for blockNo [%v] with [%d] transactions",
		historyDB.dbName, blockNo, len(block.Data.Data))

	// Get the invalidation byte array for the block
	txsFilter := util.TxValidationFlags(block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER])

	// write each tran's write set to history db
	for _, envBytes := range block.Data.Data {

		// If the tran is marked as invalid, skip it
		if txsFilter.IsInvalid(int(tranNo)) {
			logger.Debugf("Channel [%s]: Skipping history write for invalid transaction number %d",
				historyDB.dbName, tranNo)
			tranNo++
			continue
		}

		env, err := putils.GetEnvelopeFromBlock(envBytes)
		if err != nil {
			return err
		}

		payload, err := putils.GetPayload(env)
		if err != nil {
			return err
		}

		chdr, err := putils.UnmarshalChannelHeader(payload.Header.ChannelHeader)
		if err != nil {
			return err
		}

		if common.HeaderType(chdr.Type) == common.HeaderType_ENDORSER_TRANSACTION {

			// extract actions from the envelope message
			respPayload, err := putils.GetActionFromEnvelope(envBytes)
			if err != nil {
				return err
			}

			//preparation for extracting RWSet from transaction
			txRWSet := &rwsetutil.TxRwSet{}

			// Get the Result from the Action and then Unmarshal
			// it into a TxReadWriteSet using custom unmarshalling
			if err = txRWSet.FromProtoBytes(respPayload.Results); err != nil {
				return err
			}
			// for each transaction, loop through the namespaces and writesets
			// and add a history record for each write
			for _, nsRWSet := range txRWSet.NsRwSets {
				ns := nsRWSet.NameSpace

				for _, kvWrite := range nsRWSet.KvRwSet.Writes {
					writeKey := kvWrite.Key

					//composite key for history records is in the form ns~key~blockNo~tranNo
					compositeHistoryKey := historydb.ConstructCompositeHistoryKey(ns, writeKey, blockNo, tranNo)

					// No value is required, write an empty byte array (emptyValue) since Put() of nil is not allowed
					dbBatch.Put(compositeHistoryKey, emptyValue)
				}
			}

		} else {
			logger.Debugf("Skipping transaction [%d] since it is not an endorsement transaction\n", tranNo)
		}
		tranNo++
	}

	// add savepoint for recovery purpose
	height := version.NewHeight(blockNo, tranNo)
	dbBatch.Put(savePointKey, height.ToBytes())

	// write the block's history records and savepoint to LevelDB
	// Setting snyc to true as a precaution, false may be an ok optimization after further testing.
	if err := historyDB.db.WriteBatch(dbBatch, true); err != nil {
		return err
	}

	logger.Debugf("Channel [%s]: Updates committed to history database for blockNo [%v]", historyDB.dbName, blockNo)
	return nil
}
422071
func (tx *Tx) Commit() error {
	for _, pre := range tx.preHooks {
		if err := pre(tx); err != nil {
			return err
		}
	}
	err := tx.Tx.Commit()
	for _, post := range tx.postHooks {
		post(err)
	}
	return err
}
1232290
func (d *LogBatch) Commit() (err error) {
	log.Printf("%s: BatchCommit\n", d.Name)
	return d.child.Commit()
}
172166
func (w *writer) Commit(ctx context.Context, descriptor distribution.Descriptor) (distribution.Descriptor, error) {
	desc := descriptor
	switch {
	case w.closed:
		return desc, fmt.Errorf("already closed")
	case w.committed:
		return desc, fmt.Errorf("already committed")
	case w.cancelled:
		return desc, fmt.Errorf("already cancelled")
	}
	w.committed = true
	return desc, nil
}
492054
func (conn *FakeVTGateConn) Commit(ctx context.Context, session *vtgatepb.Session, twopc bool) error {
	if session == nil {
		return errors.New("commit: not in transaction")
	}
	return nil
}
555139
func (te *TxEngine) Commit(ctx context.Context, transactionID int64, mc messageCommitter) (string, error) {
	span, ctx := trace.NewSpan(ctx, "TxEngine.Commit")
	defer span.Finish()
	return te.txPool.Commit(ctx, transactionID, mc)
}
705940
func (q *query) Commit(ctx context.Context, request *querypb.CommitRequest) (response *querypb.CommitResponse, err error) {
	defer q.server.HandlePanic(&err)
	ctx = callerid.NewContext(callinfo.GRPCCallInfo(ctx),
		request.EffectiveCallerId,
		request.ImmediateCallerId,
	)
	if err := q.server.Commit(ctx, request.Target, request.TransactionId); err != nil {
		return nil, vterrors.ToGRPC(err)
	}
	return &querypb.CommitResponse{}, nil
}
1208659
func (st *TxnState) Commit(ctx context.Context) error {
	defer st.reset()
	if len(st.mutations) != 0 || len(st.dirtyTableOP) != 0 || st.buf.Len() != 0 {
		logutil.Logger(context.Background()).Error("the code should never run here",
			zap.String("TxnState", st.GoString()),
			zap.Stack("something must be wrong"))
		return errors.New("invalid transaction")
	}
	if st.doNotCommit != nil {
		if err1 := st.Transaction.Rollback(); err1 != nil {
			logutil.Logger(context.Background()).Error("rollback error", zap.Error(err1))
		}
		return errors.Trace(st.doNotCommit)
	}

	// mockCommitError8942 is used for PR #8942.
	failpoint.Inject("mockCommitError8942", func(val failpoint.Value) {
		if val.(bool) {
			failpoint.Return(kv.ErrRetryable)
		}
	})

	// mockCommitRetryForAutoID is used to mock an commit retry for adjustAutoIncrementDatum.
	failpoint.Inject("mockCommitRetryForAutoID", func(val failpoint.Value) {
		if val.(bool) && !mockAutoIDRetry() {
			enableMockAutoIDRetry()
			failpoint.Return(kv.ErrRetryable)
		}
	})

	return st.Transaction.Commit(ctx)
}
332368
func (ix *Index) commit(mm *mutationMap) error {
	// We want the update of the deletes cache to be atomic
	// with the transaction commit, so we lock here instead
	// of within updateDeletesCache.
	ix.deletes.Lock()
	defer ix.deletes.Unlock()
	bm := ix.s.BeginBatch()
	for k, v := range mm.kv {
		bm.Set(k, v)
	}
	err := ix.s.CommitBatch(bm)
	if err != nil {
		return err
	}
	for _, cl := range mm.deletes {
		if err := ix.updateDeletesCache(cl); err != nil {
			return fmt.Errorf("Could not update the deletes cache after deletion from %v: %v", cl, err)
		}
	}
	return nil
}
1065003
func (c *ChtIndexerBackend) Commit() error {
	root, err := c.trie.Commit(nil)
	if err != nil {
		return err
	}
	c.triedb.Commit(root, false)

	log.Info("Storing CHT", "section", c.section, "head", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
	StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
	return nil
}
184675
func (b *FailBatch) Commit() error {
	if err := b.dstore.errfunc("batch-commit"); err != nil {
		return err
	}

	return b.cb.Commit()
}
1121870
func (pool *ReaderPool) commit(infos *SegmentInfos) error {
	pool.Lock() // synchronized
	defer pool.Unlock()

	for _, info := range infos.Segments {
		if rld, ok := pool.readerMap[info]; ok {
			assert(rld.info == info)
			ok, err := rld.writeLiveDocs(pool.owner.directory)
			if err != nil {
				return err
			}
			if ok {
				// Make sure we only write del docs for a live segment:
				assert(pool.infoIsLive(info))
				// Must checkpoint because we just created new _X_N.del and
				// field updates files; don't call IW.checkpoint because that
				// also increments SIS.version, which we do not want to do
				// here: it was doen previously (after we invoked
				// BDS.applyDeletes), whereas here all we did was move the
				// stats to disk:
				err = pool.owner.checkpointNoSIS()
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}
896365
func (txn *BytesTxn) Commit(ctx context.Context) error {
	txn.access.Lock()
	defer txn.access.Unlock()

	kvs := map[string]datasync.ChangeValue{}
	for key, item := range txn.items {
		changeType := datasync.Put
		if item.delete {
			changeType = datasync.Delete
		}

		kvs[key] = syncbase.NewChangeBytes(key, item.data, 0, changeType)
	}
	return txn.commit(ctx, kvs)
}
1121722
func (tx *bytesTxn) Commit(ctx context.Context) error {
	_, err := tx.kv.Txn(ctx).Then(tx.ops...).Commit()
	return err
}
620444
func (si *SolrInterface) Commit() (*SolrUpdateResponse, error) {
	params := &url.Values{}
	params.Add("commit", "true")
	return si.Update(M{}, params)
}