github.com/ledgerwatch/erigon-lib@v1.0.0/kv/memdb/memory_mutation_diff.go (about)

     1  package memdb
     2  
     3  import "github.com/ledgerwatch/erigon-lib/kv"
     4  
     5  type entry struct {
     6  	k []byte
     7  	v []byte
     8  }
     9  
    10  type MemoryDiff struct {
    11  	diff              map[table][]entry // god.
    12  	deletedEntries    map[string][]string
    13  	clearedTableNames []string
    14  }
    15  
    16  type table struct {
    17  	name    string
    18  	dupsort bool
    19  }
    20  
    21  func (m *MemoryDiff) Flush(tx kv.RwTx) error {
    22  	// Obliterate buckets who are to be deleted
    23  	for _, bucket := range m.clearedTableNames {
    24  		if err := tx.ClearBucket(bucket); err != nil {
    25  			return err
    26  		}
    27  	}
    28  	// Obliterate entries who are to be deleted
    29  	for bucket, keys := range m.deletedEntries {
    30  		for _, key := range keys {
    31  			if err := tx.Delete(bucket, []byte(key)); err != nil {
    32  				return err
    33  			}
    34  		}
    35  	}
    36  	// Iterate over each bucket and apply changes accordingly.
    37  	for bucketInfo, bucketDiff := range m.diff {
    38  		if bucketInfo.dupsort {
    39  			dbCursor, err := tx.RwCursorDupSort(bucketInfo.name)
    40  			if err != nil {
    41  				return err
    42  			}
    43  			defer dbCursor.Close()
    44  			for _, entry := range bucketDiff {
    45  				if err := dbCursor.Put(entry.k, entry.v); err != nil {
    46  					return err
    47  				}
    48  			}
    49  		} else {
    50  			for _, entry := range bucketDiff {
    51  				if err := tx.Put(bucketInfo.name, entry.k, entry.v); err != nil {
    52  					return err
    53  				}
    54  			}
    55  		}
    56  	}
    57  	return nil
    58  }