All files / src/utils truncateDB.ts

80.64% Statements 25/31
90.9% Branches 20/22
90.9% Functions 10/11
88% Lines 22/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  6x 96x 6x 96x   102x 6x     6x 6x   6x 6x 6x 6x   6x 6x     6x   6x   6x       84x 72x    
import prisma from '@/services/prisma.service';
import { logger } from './winston';
 
export async function truncateAllTables() {
  if (process.env.NODE_ENV === 'production' || process.env.STAGE !== 'TEST') {
    throw new Error('This function can only be used in test environment');
  }
  try {
    // Disable triggers
    await prisma.$queryRaw`SET session_replication_role = 'replica';`;
 
    // Get all table names
    const tables = await prisma.$queryRawUnsafe(`
        SELECT tablename FROM pg_tables WHERE schemaname = 'public';
      `);
 
    // Truncate each table
    for (const { tablename } of (tables as { tablename: string }[]).filter(
      (table) => !table.tablename.startsWith('_')
    )) {I
      await prisma.$queryRawUnsafe(`TRUNCATE TABLE ${tablename} CASCADE;`);
    }
 
    // Re-enable triggers
    await prisma.$queryRawUnsafe(`SET session_replication_role = 'origin';`);
 
    logger.info('All tables truncated successfully');
  } catch (error) {
    logger.error('Error truncating tables:', error);
  } finally {
    await prisma.$disconnect();
  }
}