1632219307742-cleanup_orphan_items_and_revisions.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { MigrationInterface, QueryRunner } from 'typeorm'
  2. export class cleanupOrphanItemsAndRevisions1632219307742 implements MigrationInterface {
  3. public async up(queryRunner: QueryRunner): Promise<void> {
  4. const usersTableExistsQueryResult = await queryRunner.manager.query(
  5. 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = "users"',
  6. )
  7. const usersTableExists = usersTableExistsQueryResult[0].count === 1
  8. if (usersTableExists) {
  9. const orphanedItems = await queryRunner.manager.query(
  10. 'SELECT i.uuid as uuid FROM items i LEFT JOIN users u ON i.user_uuid = u.uuid WHERE u.uuid IS NULL',
  11. )
  12. for (const orphanedItem of orphanedItems) {
  13. await queryRunner.manager.query(`DELETE FROM revisions WHERE item_uuid = "${orphanedItem['uuid']}"`)
  14. await queryRunner.manager.query(`DELETE FROM items WHERE uuid = "${orphanedItem['uuid']}"`)
  15. }
  16. }
  17. await queryRunner.manager.query('DELETE FROM items WHERE user_uuid IS NULL')
  18. const orphanedRevisions = await queryRunner.manager.query(
  19. 'SELECT r.uuid as uuid FROM revisions r LEFT JOIN items i ON r.item_uuid = i.uuid WHERE i.uuid IS NULL',
  20. )
  21. for (const orphanedRevision of orphanedRevisions) {
  22. await queryRunner.manager.query(`DELETE FROM revisions WHERE uuid = "${orphanedRevision['uuid']}"`)
  23. }
  24. await queryRunner.manager.query('DELETE FROM revisions WHERE item_uuid IS NULL')
  25. }
  26. public async down(): Promise<void> {
  27. return
  28. }
  29. }