Skip to content

Commit

Permalink
refactor(utils): Improve runFreshMigration function to drop all table…
Browse files Browse the repository at this point in the history
…s before running fresh migrations
  • Loading branch information
wajeht committed Aug 16, 2024
1 parent 978ded0 commit 6729d4e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { db } from './db/db';
import { Request, Response } from 'express';
import { cleanDatabase, runFreshMigration, runMigrations, seedDatabase } from './utils';
import { cleanDatabase, runFreshMigration, seedDatabase } from './utils';

// GET /healthz
export function getHealthzHandler(req: Request, res: Response) {
Expand Down
38 changes: 30 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,19 @@ export async function cleanDatabase() {
}
}

export async function runFreshMigration() {
export async function runFreshMigration(force: boolean = false) {
try {
if (appConfig.env !== 'production') {
console.log('Cannot run fresh migration on non-production environment');
return;
}
// if (appConfig.env === 'production' && !force) {
// console.log('Cannot run fresh migration on production environment without force flag');
// return;
// }

const config = {
directory: path.resolve(path.join(process.cwd(), 'dist', 'src', 'db', 'migrations')),
};

console.log('Rolling back all migrations...');
await db.migrate.rollback(config, true);
console.log('All migrations have been rolled back.');
console.log('Dropping all tables...');
await dropAllTables();

console.log('Running fresh migrations...');
const [batchNo, migrations] = await db.migrate.latest(config);
Expand All @@ -93,6 +92,29 @@ export async function runFreshMigration() {
}
}

async function dropAllTables() {
const tables = await db.raw(`
SELECT tablename FROM pg_tables
WHERE schemaname = current_schema()
AND tablename != 'knex_migrations'
AND tablename != 'knex_migrations_lock'
`);

await db.raw('SET session_replication_role = replica');

for (const row of tables.rows) {
const tableName = row.tablename;
try {
await db.schema.dropTableIfExists(tableName);
console.log(`Dropped table: ${tableName}`);
} catch (error) {
console.warn(`Failed to drop table ${tableName}:`, error);
}
}

await db.raw('SET session_replication_role = DEFAULT');
}

export async function runMigrations() {
try {
if (appConfig.env !== 'production') {
Expand Down

0 comments on commit 6729d4e

Please sign in to comment.