diff --git a/src/mapeo-manager.js b/src/mapeo-manager.js index 94e451f7..bc97493e 100644 --- a/src/mapeo-manager.js +++ b/src/mapeo-manager.js @@ -4,7 +4,6 @@ import { KeyManager } from '@mapeo/crypto' import Database from 'better-sqlite3' import { eq } from 'drizzle-orm' import { drizzle } from 'drizzle-orm/better-sqlite3' -import { migrate } from 'drizzle-orm/better-sqlite3/migrator' import Hypercore from 'hypercore' import { TypedEmitter } from 'tiny-typed-emitter' import pTimeout from 'p-timeout' @@ -26,6 +25,7 @@ import { } from './schema/client.js' import { ProjectKeys } from './generated/keys.js' import { + ExhaustivenessError, deNullify, getDeviceId, keyToId, @@ -35,6 +35,7 @@ import { projectKeyToPublicId, } from './utils.js' import { openedNoiseSecretStream } from './lib/noise-secret-stream-helpers.js' +import { migrate } from './lib/drizzle-helpers.js' import { omit } from './lib/omit.js' import { RandomAccessFilePool } from './core-manager/random-access-file-pool.js' import BlobServerPlugin from './fastify-plugins/blobs.js' @@ -152,7 +153,28 @@ export class MapeoManager extends TypedEmitter { : path.join(dbFolder, CLIENT_SQLITE_FILE_NAME) ) this.#db = drizzle(sqlite) - migrate(this.#db, { migrationsFolder: clientMigrationsFolder }) + + const indexedTables = [projectSettingsTable] + + const migrationResult = migrate(this.#db, { + migrationsFolder: clientMigrationsFolder, + }) + let reindex + switch (migrationResult) { + case 'initialized database': + case 'no migration': + reindex = false + break + case 'migrated': + reindex = true + break + default: + throw new ExhaustivenessError(migrationResult) + } + + if (reindex) { + for (const table of indexedTables) this.#db.delete(table).run() + } this.#localPeers = new LocalPeers({ logger }) this.#localPeers.on('peers', (peers) => { @@ -165,7 +187,7 @@ export class MapeoManager extends TypedEmitter { }) this.#projectSettingsIndexWriter = new IndexWriter({ - tables: [projectSettingsTable], + tables: indexedTables, sqlite, logger, })