Skip to content

Commit

Permalink
support deletes
Browse files Browse the repository at this point in the history
  • Loading branch information
mafintosh committed Sep 5, 2024
1 parent b657a57 commit 983a5d8
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
30 changes: 30 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,36 @@ class HyperDB {
return this.engine.get(key)
}

async delete (collectionName, doc) {
const collection = this.definition.resolveCollection(collectionName)
if (collection === null) return

const key = collection.encodeKey(doc)

const prevValue = await this.engine.get(key)
if (prevValue === null) return

const prevDoc = collection.restructure(this.version, key, prevValue)

const u = {
key,
value: null,
indexes: []
}

for (let i = 0; i < collection.indexes.length; i++) {
const idx = collection.indexes[i]
const prevKey = idx.encodeKey(prevDoc)
const ups = []

u.indexes.push(ups)

if (prevKey !== null) ups.push({ key: prevKey, del: true })
}

this.updates.set(b4a.toString(u.key, 'hex'), u)
}

async insert (collectionName, doc) {
const collection = this.definition.resolveCollection(collectionName)
if (collection === null) throw new Error('Unknown collection')
Expand Down
45 changes: 45 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,48 @@ test('basic full example on rocks', async function (t) {

await db.close()
})

test('delete record', async function (t) {
const db = HyperDB.rocksdb(await tmp(t), definition)

await db.insert('members', { id: 'maf', age: 34 })
await db.insert('members', { id: 'andrew', age: 34 })
await db.flush()

await db.delete('members', { id: 'maf' })

{
const result = await collect(db.query('members'))
t.alike(result, [
{ id: 'andrew', age: 34 }
])
}

{
const result = await collect(db.query('members/by-age', { gte: { age: 33 }, lt: { age: 99 } }))
t.alike(result, [
{ id: 'andrew', age: 34 }
])
}

await db.flush()

{
const result = await collect(db.query('members'))
t.alike(result, [
{ id: 'andrew', age: 34 }
])
}

{
const result = await collect(db.query('members/by-age', { gte: { age: 33 }, lt: { age: 99 } }))
t.alike(result, [
{ id: 'andrew', age: 34 }
])
}

t.alike(await db.get('members', { id: 'maf' }), null)
t.alike(await db.get('members', { id: 'andrew' }), { id: 'andrew', age: 34 })

await db.close()
})

0 comments on commit 983a5d8

Please sign in to comment.