github.com/ethereum/go-ethereum@v1.16.1/core/rawdb/table.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rawdb
    18  
    19  import (
    20  	"github.com/ethereum/go-ethereum/ethdb"
    21  )
    22  
    23  // table is a wrapper around a database that prefixes each key access with a pre-
    24  // configured string.
    25  type table struct {
    26  	db     ethdb.Database
    27  	prefix string
    28  }
    29  
    30  // NewTable returns a database object that prefixes all keys with a given string.
    31  func NewTable(db ethdb.Database, prefix string) ethdb.Database {
    32  	return &table{
    33  		db:     db,
    34  		prefix: prefix,
    35  	}
    36  }
    37  
    38  // Close is a noop to implement the Database interface.
    39  func (t *table) Close() error {
    40  	return nil
    41  }
    42  
    43  // Has retrieves if a prefixed version of a key is present in the database.
    44  func (t *table) Has(key []byte) (bool, error) {
    45  	return t.db.Has(append([]byte(t.prefix), key...))
    46  }
    47  
    48  // Get retrieves the given prefixed key if it's present in the database.
    49  func (t *table) Get(key []byte) ([]byte, error) {
    50  	return t.db.Get(append([]byte(t.prefix), key...))
    51  }
    52  
    53  // Ancient is a noop passthrough that just forwards the request to the underlying
    54  // database.
    55  func (t *table) Ancient(kind string, number uint64) ([]byte, error) {
    56  	return t.db.Ancient(kind, number)
    57  }
    58  
    59  // AncientRange is a noop passthrough that just forwards the request to the underlying
    60  // database.
    61  func (t *table) AncientRange(kind string, start, count, maxBytes uint64) ([][]byte, error) {
    62  	return t.db.AncientRange(kind, start, count, maxBytes)
    63  }
    64  
    65  // Ancients is a noop passthrough that just forwards the request to the underlying
    66  // database.
    67  func (t *table) Ancients() (uint64, error) {
    68  	return t.db.Ancients()
    69  }
    70  
    71  // Tail is a noop passthrough that just forwards the request to the underlying
    72  // database.
    73  func (t *table) Tail() (uint64, error) {
    74  	return t.db.Tail()
    75  }
    76  
    77  // AncientSize is a noop passthrough that just forwards the request to the underlying
    78  // database.
    79  func (t *table) AncientSize(kind string) (uint64, error) {
    80  	return t.db.AncientSize(kind)
    81  }
    82  
    83  // ModifyAncients runs an ancient write operation on the underlying database.
    84  func (t *table) ModifyAncients(fn func(ethdb.AncientWriteOp) error) (int64, error) {
    85  	return t.db.ModifyAncients(fn)
    86  }
    87  
    88  func (t *table) ReadAncients(fn func(reader ethdb.AncientReaderOp) error) (err error) {
    89  	return t.db.ReadAncients(fn)
    90  }
    91  
    92  // TruncateHead is a noop passthrough that just forwards the request to the underlying
    93  // database.
    94  func (t *table) TruncateHead(items uint64) (uint64, error) {
    95  	return t.db.TruncateHead(items)
    96  }
    97  
    98  // TruncateTail is a noop passthrough that just forwards the request to the underlying
    99  // database.
   100  func (t *table) TruncateTail(items uint64) (uint64, error) {
   101  	return t.db.TruncateTail(items)
   102  }
   103  
   104  // SyncAncient is a noop passthrough that just forwards the request to the underlying
   105  // database.
   106  func (t *table) SyncAncient() error {
   107  	return t.db.SyncAncient()
   108  }
   109  
   110  // AncientDatadir returns the ancient datadir of the underlying database.
   111  func (t *table) AncientDatadir() (string, error) {
   112  	return t.db.AncientDatadir()
   113  }
   114  
   115  // Put inserts the given value into the database at a prefixed version of the
   116  // provided key.
   117  func (t *table) Put(key []byte, value []byte) error {
   118  	return t.db.Put(append([]byte(t.prefix), key...), value)
   119  }
   120  
   121  // Delete removes the given prefixed key from the database.
   122  func (t *table) Delete(key []byte) error {
   123  	return t.db.Delete(append([]byte(t.prefix), key...))
   124  }
   125  
   126  // DeleteRange deletes all of the keys (and values) in the range [start,end)
   127  // (inclusive on start, exclusive on end).
   128  func (t *table) DeleteRange(start, end []byte) error {
   129  	// The nilness will be lost by adding the prefix, explicitly converting it
   130  	// to a special flag representing the end of key range.
   131  	if end == nil {
   132  		end = ethdb.MaximumKey
   133  	}
   134  	return t.db.DeleteRange(append([]byte(t.prefix), start...), append([]byte(t.prefix), end...))
   135  }
   136  
   137  // NewIterator creates a binary-alphabetical iterator over a subset
   138  // of database content with a particular key prefix, starting at a particular
   139  // initial key (or after, if it does not exist).
   140  func (t *table) NewIterator(prefix []byte, start []byte) ethdb.Iterator {
   141  	innerPrefix := append([]byte(t.prefix), prefix...)
   142  	iter := t.db.NewIterator(innerPrefix, start)
   143  	return &tableIterator{
   144  		iter:   iter,
   145  		prefix: t.prefix,
   146  	}
   147  }
   148  
   149  // Stat returns the statistic data of the database.
   150  func (t *table) Stat() (string, error) {
   151  	return t.db.Stat()
   152  }
   153  
   154  // Compact flattens the underlying data store for the given key range. In essence,
   155  // deleted and overwritten versions are discarded, and the data is rearranged to
   156  // reduce the cost of operations needed to access them.
   157  //
   158  // A nil start is treated as a key before all keys in the data store; a nil limit
   159  // is treated as a key after all keys in the data store. If both is nil then it
   160  // will compact entire data store.
   161  func (t *table) Compact(start []byte, limit []byte) error {
   162  	// If no start was specified, use the table prefix as the first value
   163  	if start == nil {
   164  		start = []byte(t.prefix)
   165  	} else {
   166  		start = append([]byte(t.prefix), start...)
   167  	}
   168  	// If no limit was specified, use the first element not matching the prefix
   169  	// as the limit
   170  	if limit == nil {
   171  		limit = []byte(t.prefix)
   172  		for i := len(limit) - 1; i >= 0; i-- {
   173  			// Bump the current character, stopping if it doesn't overflow
   174  			limit[i]++
   175  			if limit[i] > 0 {
   176  				break
   177  			}
   178  			// Character overflown, proceed to the next or nil if the last
   179  			if i == 0 {
   180  				limit = nil
   181  			}
   182  		}
   183  	} else {
   184  		limit = append([]byte(t.prefix), limit...)
   185  	}
   186  	// Range correctly calculated based on table prefix, delegate down
   187  	return t.db.Compact(start, limit)
   188  }
   189  
   190  // SyncKeyValue ensures that all pending writes are flushed to disk,
   191  // guaranteeing data durability up to the point.
   192  func (t *table) SyncKeyValue() error {
   193  	return t.db.SyncKeyValue()
   194  }
   195  
   196  // NewBatch creates a write-only database that buffers changes to its host db
   197  // until a final write is called, each operation prefixing all keys with the
   198  // pre-configured string.
   199  func (t *table) NewBatch() ethdb.Batch {
   200  	return &tableBatch{t.db.NewBatch(), t.prefix}
   201  }
   202  
   203  // NewBatchWithSize creates a write-only database batch with pre-allocated buffer.
   204  func (t *table) NewBatchWithSize(size int) ethdb.Batch {
   205  	return &tableBatch{t.db.NewBatchWithSize(size), t.prefix}
   206  }
   207  
   208  // tableBatch is a wrapper around a database batch that prefixes each key access
   209  // with a pre-configured string.
   210  type tableBatch struct {
   211  	batch  ethdb.Batch
   212  	prefix string
   213  }
   214  
   215  // Put inserts the given value into the batch for later committing.
   216  func (b *tableBatch) Put(key, value []byte) error {
   217  	return b.batch.Put(append([]byte(b.prefix), key...), value)
   218  }
   219  
   220  // Delete inserts a key removal into the batch for later committing.
   221  func (b *tableBatch) Delete(key []byte) error {
   222  	return b.batch.Delete(append([]byte(b.prefix), key...))
   223  }
   224  
   225  // DeleteRange removes all keys in the range [start, end) from the batch for later committing.
   226  func (b *tableBatch) DeleteRange(start, end []byte) error {
   227  	// The nilness will be lost by adding the prefix, explicitly converting it
   228  	// to a special flag representing the end of key range.
   229  	if end == nil {
   230  		end = ethdb.MaximumKey
   231  	}
   232  	return b.batch.DeleteRange(append([]byte(b.prefix), start...), append([]byte(b.prefix), end...))
   233  }
   234  
   235  // ValueSize retrieves the amount of data queued up for writing.
   236  func (b *tableBatch) ValueSize() int {
   237  	return b.batch.ValueSize()
   238  }
   239  
   240  // Write flushes any accumulated data to disk.
   241  func (b *tableBatch) Write() error {
   242  	return b.batch.Write()
   243  }
   244  
   245  // Reset resets the batch for reuse.
   246  func (b *tableBatch) Reset() {
   247  	b.batch.Reset()
   248  }
   249  
   250  // tableReplayer is a wrapper around a batch replayer which truncates
   251  // the added prefix.
   252  type tableReplayer struct {
   253  	w      ethdb.KeyValueWriter
   254  	prefix string
   255  }
   256  
   257  // Put implements the interface KeyValueWriter.
   258  func (r *tableReplayer) Put(key []byte, value []byte) error {
   259  	trimmed := key[len(r.prefix):]
   260  	return r.w.Put(trimmed, value)
   261  }
   262  
   263  // Delete implements the interface KeyValueWriter.
   264  func (r *tableReplayer) Delete(key []byte) error {
   265  	trimmed := key[len(r.prefix):]
   266  	return r.w.Delete(trimmed)
   267  }
   268  
   269  // Replay replays the batch contents.
   270  func (b *tableBatch) Replay(w ethdb.KeyValueWriter) error {
   271  	return b.batch.Replay(&tableReplayer{w: w, prefix: b.prefix})
   272  }
   273  
   274  // tableIterator is a wrapper around a database iterator that prefixes each key access
   275  // with a pre-configured string.
   276  type tableIterator struct {
   277  	iter   ethdb.Iterator
   278  	prefix string
   279  }
   280  
   281  // Next moves the iterator to the next key/value pair. It returns whether the
   282  // iterator is exhausted.
   283  func (iter *tableIterator) Next() bool {
   284  	return iter.iter.Next()
   285  }
   286  
   287  // Error returns any accumulated error. Exhausting all the key/value pairs
   288  // is not considered to be an error.
   289  func (iter *tableIterator) Error() error {
   290  	return iter.iter.Error()
   291  }
   292  
   293  // Key returns the key of the current key/value pair, or nil if done. The caller
   294  // should not modify the contents of the returned slice, and its contents may
   295  // change on the next call to Next.
   296  func (iter *tableIterator) Key() []byte {
   297  	key := iter.iter.Key()
   298  	if key == nil {
   299  		return nil
   300  	}
   301  	return key[len(iter.prefix):]
   302  }
   303  
   304  // Value returns the value of the current key/value pair, or nil if done. The
   305  // caller should not modify the contents of the returned slice, and its contents
   306  // may change on the next call to Next.
   307  func (iter *tableIterator) Value() []byte {
   308  	return iter.iter.Value()
   309  }
   310  
   311  // Release releases associated resources. Release should always succeed and can
   312  // be called multiple times without causing error.
   313  func (iter *tableIterator) Release() {
   314  	iter.iter.Release()
   315  }