Last active
September 8, 2023 13:22
-
-
Save suhjohn/db1ffba13841dbd775fae83402d645d6 to your computer and use it in GitHub Desktop.
Prisma migrate down
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 { exec } from 'child_process'; | |
import { log } from 'console'; | |
import * as fs from 'fs'; | |
import * as path from 'path'; | |
import { Client } from 'pg'; // Assuming you have 'pg' npm package installed. | |
import * as util from 'util'; | |
const execPromise = util.promisify(exec); | |
const executeMigrationDown = async (migrationPath: string) => { | |
const { stdout, stderr } = await execPromise( | |
`npx prisma db execute --file ${migrationPath} --schema prisma/schema.prisma`, | |
); | |
log('Output:', stdout); | |
if (stderr) { | |
console.error('Error:', stderr); | |
} | |
}; | |
const deletePrismaMigrationEntry = async ( | |
migrationName: string, | |
client: Client, | |
) => { | |
const deleteQuery = `DELETE FROM "_prisma_migrations" WHERE "migration_name" = $1`; | |
await client.query(deleteQuery, [migrationName]); | |
}; | |
const runDownMigrations = async (n: number) => { | |
const migrationsDir = path.join(process.cwd(), 'prisma', 'migrations'); | |
const client = new Client({ | |
connectionString: process.env.DATABASE_URL, | |
}); | |
try { | |
await client.connect(); | |
const migrationFolders = fs | |
.readdirSync(migrationsDir) | |
.filter((folder) => folder !== 'migration_lock.toml') | |
.sort() | |
.reverse() | |
.slice(0, n); | |
/* eslint-disable no-restricted-syntax */ | |
for (const folder of migrationFolders) { | |
const downScriptPath = path.join(migrationsDir, folder, 'down.sql'); | |
if (fs.existsSync(downScriptPath)) { | |
log(`Running down migration for: ${folder}`); | |
// eslint-disable-next-line no-await-in-loop | |
await executeMigrationDown(downScriptPath); | |
log(`Deleting Prisma migration entry for: ${folder}`); | |
// eslint-disable-next-line no-await-in-loop | |
await deletePrismaMigrationEntry(folder, client); | |
} else { | |
log(`No down.sql found for migration: ${folder}`); | |
} | |
} | |
} catch (error) { | |
console.error('An error occurred:', error); | |
} finally { | |
await client.end(); | |
} | |
}; | |
const n = Number(process.argv[2]) || 0; | |
if (n === 0) { | |
console.error('Please specify the number of migrations to run down.'); | |
process.exit(1); | |
} | |
void runDownMigrations(n); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment