Skip to content

Instantly share code, notes, and snippets.

@darioielardi
Created December 24, 2022 11:51
Show Gist options
  • Save darioielardi/a4374f3994f3ee791f9681c7eab2be54 to your computer and use it in GitHub Desktop.
Save darioielardi/a4374f3994f3ee791f9681c7eab2be54 to your computer and use it in GitHub Desktop.
truncate tables passing entity classes with MikroORM
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