Created
December 24, 2022 11:51
-
-
Save darioielardi/a4374f3994f3ee791f9681c7eab2be54 to your computer and use it in GitHub Desktop.
truncate tables passing entity classes with MikroORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Constructor } from '@mikro-orm/core'; | |
import { EntityManager } from '@mikro-orm/core'; | |
export async function truncate(em: EntityManager, entities: Constructor[]) { | |
const meta = em.getMetadata(); | |
for (const entity of entities) { | |
const entityMeta = meta.get(entity.name); | |
if (!entityMeta) { | |
throw new Error(`Entity ${entity.name} not found`); | |
} | |
if (entityMeta.embeddable || entityMeta.abstract || entityMeta.virtual) { | |
throw new Error(`Entity ${entity.name} is not a valid entity`); | |
} | |
await em | |
.getConnection() | |
.execute(`TRUNCATE ${entityMeta.tableName} CASCADE`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment