Created
September 15, 2016 14:42
-
-
Save ikouchiha47/f945e48df71857fc8a3810b6c194f71d to your computer and use it in GitHub Desktop.
migration generator
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 fs = require('fs') | |
| const path = require('path') | |
| const migrationsFolder = path.join(__dirname, "/migrations") | |
| const recordFile = path.join(__dirname, "/schema_migrations") | |
| let client = require('./connection')() | |
| let Commands = { | |
| make: make, | |
| run: run | |
| } | |
| // npm run migrate:make make stuff_in_underscore_or_whatever | |
| function make(filename) { | |
| // check if a file_name is passed else throw an error | |
| // create a file with the timestamp followed by the first text that follows | |
| if(!filename) throw new Error("Expected a file name, npm run migrate:make filename") | |
| let calculatedFilename = `${Date.now()}_${filename}` | |
| let filepath = `${migrationsFolder}/${calculatedFilename}.sql` | |
| fs.closeSync(fs.openSync(filepath, 'w')); | |
| console.log('Created file ', filepath); | |
| console.log('write your migrations and run npm run migrate:latest') | |
| } | |
| function run() { | |
| // if a schema_migrations file is not present, create it | |
| // get the files in directory ./db/migrations | |
| // get the last run migration version | |
| // filter the files and run the migrations | |
| let files = getFiles(migrationsFolder) | |
| let lastMigration = fs.readFileSync(recordFile, 'utf8') | |
| client.connect(); | |
| Promise.all(files.slice(files.indexOf(lastMigration) + 1).map(file => runQuery(client, file, lastMigration))) | |
| .then(() => client.end()) | |
| .then(() => console.log("migrations completed")) | |
| .catch(e => { | |
| client.end(); | |
| console.log("migration failed at ", lastMigration, " error ", e.message) | |
| }) | |
| } | |
| function runQuery(conn, file, lastMigration) { | |
| let migration = fs.readFileSync(migrationsFolder + '/' + file, 'utf8') | |
| return conn.query(migration).then(() => { | |
| lastMigration = file | |
| return new Promise(res => fs.writeFile(recordFile, file, 'utf8', res)) | |
| }) | |
| } | |
| function getFiles(dir){ | |
| let fileList = []; | |
| let files = fs.readdirSync(dir); | |
| for (let i = 0, len = files.length; i < len; i++) { | |
| fileList.push(files[i]) | |
| } | |
| return fileList; | |
| } | |
| let command = process.argv[2] | |
| let todo = process.argv[3] | |
| Commands[command](todo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment