Commit The transaction commits, writes the transient data to the data file, and updates the in-memory index
()
| 86 | |
| 87 | // Commit The transaction commits, writes the transient data to the data file, and updates the in-memory index |
| 88 | func (wb *WriteBatch) Commit() error { |
| 89 | wb.lock.Lock() |
| 90 | defer wb.lock.Unlock() |
| 91 | |
| 92 | if len(wb.temporaryDataWrites) == 0 { |
| 93 | return nil |
| 94 | } |
| 95 | if uint(len(wb.temporaryDataWrites)) > wb.options.MaxBatchNum { |
| 96 | return _const.ErrExceedMaxBatchNum |
| 97 | } |
| 98 | |
| 99 | // Gets the current, most recent transaction sequence number |
| 100 | transSeq := atomic.AddUint64(&wb.db.transSeqNo, 1) |
| 101 | |
| 102 | // Start writing data to the data file |
| 103 | // The index is not updated immediately after a single piece of data is written. |
| 104 | // It needs to be stored temporarily |
| 105 | positions := make(map[string]*data.LogRecordPst) |
| 106 | for _, record := range wb.temporaryDataWrites { |
| 107 | logRecordPst, err := wb.db.appendLogRecord(&data.LogRecord{ |
| 108 | Key: encodeLogRecordKeyWithSeq(record.Key, transSeq), |
| 109 | Value: record.Value, |
| 110 | Type: record.Type, |
| 111 | }) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | positions[string(record.Key)] = logRecordPst |
| 116 | } |
| 117 | |
| 118 | // Write a piece of data that identifies the completion of the transaction |
| 119 | finishedRecord := &data.LogRecord{ |
| 120 | Key: encodeLogRecordKeyWithSeq(lgrTransFinaKey, transSeq), |
| 121 | Type: data.LogRecordTransFinished, |
| 122 | } |
| 123 | if _, err := wb.db.appendLogRecord(finishedRecord); err != nil { |
| 124 | return err |
| 125 | } |
| 126 | |
| 127 | // Decide whether to persist based on the configuration |
| 128 | if wb.options.SyncWrites && wb.db.activeFile != nil { |
| 129 | if err := wb.db.activeFile.Sync(); err != nil { |
| 130 | return err |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // Update memory index |
| 135 | for _, record := range wb.temporaryDataWrites { |
| 136 | pst := positions[string(record.Key)] |
| 137 | if record.Type == data.LogRecordNormal { |
| 138 | // Put the record in the index if it is of type LogRecordNormal |
| 139 | wb.db.index.Put(record.Key, pst) |
| 140 | } |
| 141 | if record.Type == data.LogRecordDeleted { |
| 142 | // Delete the record from the index if it is of type LogRecordDeleted |
| 143 | wb.db.index.Delete(record.Key) |
| 144 | } |
| 145 | } |