Created
January 13, 2021 11:50
-
-
Save TiagoGouvea/7adbc222bec4bb0b7a0bfb6019ddfc00 to your computer and use it in GitHub Desktop.
// You must add this command to your start/app.js ... const commands = ['App/Commands/MigrationFresh']; ...
This file contains hidden or 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
'use strict'; | |
const { Command } = require('@adonisjs/ace'); | |
const Seeder = require('../../database/seeds/Seeder'); | |
const ace = require('@adonisjs/ace'); | |
class MigrationFresh extends Command { | |
/** | |
* Command signature | |
*/ | |
static get signature() { | |
return 'migration:fresh { --seed : Run the database seeders }'; | |
} | |
/** | |
* Command description | |
*/ | |
static get description() { | |
return 'Drop public schema and recreates it'; | |
} | |
/** | |
* Command handler | |
*/ | |
async handle(args, options) { | |
const Database = use('Database'); | |
const Config = use('Config'); | |
const config = Config.get('database.' + Config.get('database.connection')); | |
try { | |
// Recreate database schema by connection | |
this.info('Recreating database schema...'); | |
if (Config.get('database.connection') === 'pg') { | |
await Database.raw('DROP SCHEMA public CASCADE'); | |
await Database.raw('CREATE SCHEMA public'); | |
} else if (Config.get('database.connection') === 'mysql') { | |
await Database.raw('SET FOREIGN_KEY_CHECKS=0'); | |
let tables = await Database.raw(`SHOW TABLES FROM ${config.connection.database}`); | |
tables = JSON.parse(JSON.stringify(tables)); | |
tables = tables[0]; | |
for (const table of tables) { | |
const tableName = Object.values(table)[0]; | |
await Database.raw(`DROP TABLE ${config.connection.database}.${tableName}`); | |
} | |
await Database.raw('SET FOREIGN_KEY_CHECKS=1'); | |
} | |
this.success(`${this.icon('success')} All tables drop successfully`); | |
// Migrate | |
await ace.call('migration:run'); | |
// Seed | |
if (options.seed) await new Seeder().run(); | |
} catch (e) { | |
this.failed(`${this.icon('error')} Error recreating: ${e.message}`); | |
} | |
Database.close(); | |
} | |
} | |
module.exports = MigrationFresh; |
This file contains hidden or 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
// You must add this command to your start/app.js commands array | |
... | |
const commands = ['App/Commands/MigrationFresh']; | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment