diff --git a/.changeset/five-lies-confess.md b/.changeset/five-lies-confess.md new file mode 100644 index 0000000000..eefd2bd6fa --- /dev/null +++ b/.changeset/five-lies-confess.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Improve the query for orphan pruning diff --git a/plugins/catalog-backend/src/database/operations/util/deleteOrphanedEntities.ts b/plugins/catalog-backend/src/database/operations/util/deleteOrphanedEntities.ts index 920acae7bd..eeab85f59e 100644 --- a/plugins/catalog-backend/src/database/operations/util/deleteOrphanedEntities.ts +++ b/plugins/catalog-backend/src/database/operations/util/deleteOrphanedEntities.ts @@ -33,13 +33,16 @@ export async function deleteOrphanedEntities(options: { // Limit iterations for sanity for (let i = 0; i < 100; ++i) { const candidates = await tx - .with('orphans', orphans => + .with('orphans', ['entity_id', 'entity_ref'], orphans => orphans - .from('refresh_state') - .select('entity_id', 'entity_ref') - .whereNotIn('entity_ref', keep => - keep.distinct('target_entity_ref').from('refresh_state_references'), - ), + .from('refresh_state') + .select('refresh_state.entity_id', 'refresh_state.entity_ref') + .leftOuterJoin( + 'refresh_state_references', + 'refresh_state_references.target_entity_ref', + 'refresh_state.entity_ref', + ) + .whereNull('refresh_state_references.target_entity_ref'), ) .select({ entityId: 'orphans.entity_id',