Last active
March 15, 2020 08:20
-
-
Save nnennajohn/459079a37e9336f65310fbdd605f9d9b to your computer and use it in GitHub Desktop.
Reset Prisma2 records
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 camelCase from 'lodash/camelCase'; | |
import { prisma } from '@cpath/universal/shared/db'; | |
import knexClient from './knex'; | |
// Contents of the knexClient import above | |
// import Knex from 'knex'; | |
// const knexClient: Knex = Knex({ | |
// client: 'pg', | |
// connection: { | |
// user: process.env.POSTGRES_USER, | |
// password: process.env.POSTGRES_PASSWORD, | |
// host: process.env.POSTGRES_HOST, | |
// port: Number(process.env.POSTGRES_PORT), | |
// database: process.env.POSTGRES_DB, | |
// }, | |
// }); | |
// Contents of the prisma import above | |
// export const prisma = new PrismaClient(); | |
function deleteRecords(tablesList) { | |
const validTables = tablesList.filter((tableName) => tableName[0] !== '_'); | |
console.log('These are the valid tables', validTables); | |
const recordsDeletions = validTables.map((table) => { | |
return prisma[camelCase(table)].deleteMany({}); | |
}); | |
return Promise.all(recordsDeletions); | |
} | |
function listTables() { | |
const query = | |
'SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_catalog = ?'; | |
const bindings = [knexClient.client.database()]; | |
return knexClient.raw(query, bindings).then((results) => { | |
return results.rows.map((row) => row.table_name); | |
}); | |
} | |
async function main() { | |
const tablesList = await listTables(); | |
console.log('This is the list of knex tables', tablesList); | |
if (tablesList && tablesList.length) { | |
deleteRecords(tablesList) | |
.then((res) => { | |
console.log('Successfully deleted table records', res); | |
}) | |
.catch((err) => { | |
console.log('Error deleting table records', err); | |
}); | |
} | |
} | |
main() | |
.catch((e) => console.error(e)) | |
.finally(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment