Level / abstract-level

Abstract class for a lexicographically sorted key-value database.
MIT License
128 stars 8 forks source link

Allow batches to write to a nondescendant sublevel #80

Closed vweevers closed 9 months ago

vweevers commented 9 months ago

This example from the v2 README doesn't work:

const charwise = require('charwise-compact')
const books = db.sublevel('books', { valueEncoding: 'json' })
const index = db.sublevel('authors', { keyEncoding: charwise })

books.hooks.prewrite.add(function (op, batch) {
  if (op.type === 'put') {
    batch.add({
      type: 'put',
      key: [op.value.author, op.key],
      value: '',
      sublevel: index
    })
  }
})

// Will atomically commit it to the author index as well
await books.put('12', { title: 'Siddhartha', author: 'Hesse' })

I added a constraint to db.batch() and to the prewrite hook that if a sublevel option is provided, that sublevel must be a descendant of the db. That simplified internals, but the above use case violates the constraint. It's a realistic use case, so I want to remove the constraint (which doesn't exist in v1).

Batch logic should then be, if sublevel is a descendant then prefix the key now, else pass the sublevel option "down" to the private API (aka "up" to the parent database) and skip events. E.g. in the above example, the 'write' event of books should not include the index op.

vweevers commented 9 months ago

Done in https://github.com/Level/abstract-level/pull/81.