diff --git a/packages/server/src/sdk/app/tables/internal/sqs.ts b/packages/server/src/sdk/app/tables/internal/sqs.ts index 2d49adf96e..706e0ca167 100644 --- a/packages/server/src/sdk/app/tables/internal/sqs.ts +++ b/packages/server/src/sdk/app/tables/internal/sqs.ts @@ -176,9 +176,24 @@ export async function addTable(table: Table) { export async function removeTable(table: Table) { const db = context.getAppDB() try { - const definition = await db.get(SQLITE_DESIGN_DOC_ID) - if (definition.sql?.tables?.[table._id!]) { - delete definition.sql.tables[table._id!] + let response = await Promise.all([ + tablesSdk.getAllInternalTables(), + db.get(SQLITE_DESIGN_DOC_ID), + ]) + const tables: Table[] = response[0], + definition: SQLiteDefinition = response[1] + const tableIds = tables + .map(tbl => tbl._id!) + .filter(id => !id.includes(table._id!)) + let cleanup = false + for (let tableKey of Object.keys(definition.sql?.tables || {})) { + // there are no tables matching anymore + if (!tableIds.find(id => tableKey.includes(id))) { + delete definition.sql.tables[tableKey] + cleanup = true + } + } + if (cleanup) { await db.put(definition) // make sure SQS is cleaned up, tables removed await db.sqlDiskCleanup()