Skip to content

Commit

Permalink
feat: add method to clear index
Browse files Browse the repository at this point in the history
This adds `indexer.deleteAll()`, which deletes all rows from the docs
table and the backlinks table.

Addresses #22.
  • Loading branch information
EvanHahn committed Jan 22, 2024
1 parent c39ed31 commit e2504c6
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ Index an array of documents. Documents can be in any order. Documents must have

Set a listener for a doc at a specific version. Useful for performing an action based on completion of indexing of a document.

### indexer.deleteAll()

Delete all documents and backlinks. Useful if you want to reset the index.

### docs

_Requires_\
Expand Down
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export class DbApi {
#getBacklinkSql
#writeBacklinkSql
#updateForksSql
#deleteAll
#docDefaults
#tableInfo

Expand Down Expand Up @@ -87,6 +88,13 @@ export class DbApi {
`INSERT OR IGNORE INTO ${backlinkTableName} (versionId)
VALUES (?)`
)

const deleteDocsSql = db.prepare(`DELETE FROM ${docTableName}`)
const deleteBacklinksSql = db.prepare(`DELETE FROM ${backlinkTableName}`)
this.#deleteAll = db.transaction(() => {
deleteDocsSql.run()
deleteBacklinksSql.run()
})
}
/**
* @param {string} docId
Expand Down Expand Up @@ -141,6 +149,12 @@ export class DbApi {
writeBacklink(versionId) {
this.#writeBacklinkSql.run(versionId)
}
/**
* @returns {void}
*/
deleteAll() {
this.#deleteAll()
}
}

/**
Expand Down Expand Up @@ -222,6 +236,10 @@ export default class SqliteIndexer {
isLinked(versionId) {
return !!this.#dbApi.getBacklink(versionId)
}

deleteAll() {
this.#dbApi.deleteAll()
}
}

/**
Expand Down
29 changes: 29 additions & 0 deletions test/delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// @ts-check
import test from 'tape'
import { create } from './utils.js'

test('deleting everything', (t) => {
const { indexer, db, cleanup } = create()

const docCount = db.prepare('SELECT COUNT(*) FROM docs').pluck()
const backlinkCount = db.prepare('SELECT COUNT(*) FROM backlinks').pluck()

const updatedAt = new Date().toISOString()
indexer.batch([
{ docId: 'A', versionId: '1', links: [], updatedAt },
{ docId: 'A', versionId: '2', links: ['1'], updatedAt },
{ docId: 'B', versionId: '3', links: [], updatedAt },
])

t.equal(docCount.get(), 2, 'Test setup expected 2 documents')
t.equal(backlinkCount.get(), 1, 'Test setup expected 1 backlink')

indexer.deleteAll()

t.equal(docCount.get(), 0, 'Expected all documents to be deleted')
t.equal(backlinkCount.get(), 0, 'Expected all backlinks to be deleted')

cleanup()

t.end()
})

0 comments on commit e2504c6

Please sign in to comment.