Socket
Socket
Sign inDemoInstall

sql-migrations

Package Overview
Dependencies
48
Maintainers
2
Versions
11
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.2 to 1.0.3

migration-provider.js

110

adapters/pg.js

@@ -1,66 +0,56 @@

var pg = require('pg'),
cfg = require('../config.js'),
utils = require('../utils.js'),
ENSURE_SQL = 'create table if not exists "__migrations__" (id bigint NOT NULL)';
var pg = require('pg');
module.exports = function (config) {
var pool = new pg.Pool({
host: config.host,
port: config.port,
database: config.db,
user: config.user,
password: config.password
});
function exec(query, values) {
return pool.query(query, values).catch(function (err) {
//add the sql line number to the error output if available
if (err && err.position) {
err.sql_line = (query.substring(0, err.position).match(/\n/g) || []).length + 1;
}
throw err;
});
}
module.exports = {
exec: function(query, values, cb) {
cb || (cb = values);
var client = new pg.Client(cfg.conn);
client.connect(function(err) {
err && utils.panic(err);
client.query(query, values, function(err, result) {
//call `end()` to release the client back to the pool
client.end()
//add the sql line number to the error output if available
if (err && err.position) {
err.sql_line = (query.substring(0, err.position).match(/\n/g) || []).length + 1;
}
err && utils.panic(err);
cb(result);
function ensureMigrationTableExists() {
return exec('create table if not exists "__migrations__" (id bigint NOT NULL)');
}
return {
appliedMigrations: function appliedMigrations() {
return ensureMigrationTableExists().then(function () {
return exec('select * from __migrations__');
}).then(function (result) {
return result.rows.map(function (row) { return row.id; });
});
});
},
appliedMigrations: function(cb) {
this.ensureMigrationTableExists(function() {
this.exec('select * from __migrations__', function(result) {
cb(result.rows.map(function(row) {
return row.id;
}));
},
applyMigration: function applyMigration(migration, sql) {
return exec(sql).then(function (result) {
console.log('Applying ' + migration);
console.log(result)
console.log('===============================================');
var values = [migration.match(/^(\d)+/)[0]];
return exec('insert into __migrations__ (id) values ($1)', values);
});
}.bind(this));
},
applyMigration: function(migration, cb) {
var sql = utils.getSql(migration);
this.exec(sql, function(result) {
console.log('Applying ' + migration);
console.log(result)
console.log('===============================================');
var values = [migration.match(/^(\d)+/)[0]];
this.exec(
'insert into __migrations__ (id) values ($1)',
values,
cb
);
}.bind(this));
},
rollbackMigration: function(migration, cb) {
var sql = utils.getSql(migration);
this.exec(sql, function(result) {
console.log('Reverting ' + migration);
console.log(result)
console.log('===============================================');
var values = [migration.match(/^(\d)+/)[0]];
this.exec(
'delete from __migrations__ where id = $1',
values,
cb
);
}.bind(this));
},
ensureMigrationTableExists: function(cb) {
this.exec(ENSURE_SQL, cb)
}
},
rollbackMigration: function rollbackMigration(migration, sql) {
return exec(sql).then(function (result) {
console.log('Reverting ' + migration);
console.log(result)
console.log('===============================================');
var values = [migration.match(/^(\d)+/)[0]];
return exec('delete from __migrations__ where id = $1', values);
});
},
dispose: function dispose() {
return pool.end();
}
};
};

@@ -0,0 +0,0 @@ var fs = require('fs'),

@@ -1,37 +0,42 @@

var cfg = require('../config.js');
var adapter = require('../adapters/pg.js');
var utils = require('../utils.js');
var chalk = require('chalk');
module.exports = function() {
module.exports = function (migrationProvider, adapter) {
return adapter.appliedMigrations()
.then(function (appliedMigrationIds) {
var migrationsList = migrationProvider.getMigrationsList();
var pending = getPending(migrationsList, appliedMigrationIds);
cfg.conn = utils.makeConnString();
if (pending.length === 0) {
console.log('No pending migrations');
return;
}
adapter.appliedMigrations(function(ids) {
var migrationsList = utils.getMigrationsList(),
pending = utils.getPending(migrationsList, ids);
if (pending.length) {
console.log('Pending migrations:');
pending.forEach(function(m) {
pending.forEach(function (m) {
console.log(chalk.green('>>'), m);
});
} else {
console.log('No pending migrations');
process.exit();
}
function apply() {
// base case
if (!pending.length) {
console.log('done');
return process.exit();
var migration;
var migrationProgress = Promise.resolve();
while (migration = pending.shift()) {
(function (migration) {
migrationProgress = migrationProgress.then(function () {
var sql = migrationProvider.getSql(migration);
return adapter.applyMigration(migration, sql);
});
})(migration);
}
adapter.applyMigration(pending.shift(), function() {
// recur
apply();
});
return migrationProgress;
});
};
function getPending(migrationsList, appliedMigrationIds) {
var pending = [];
migrationsList.forEach(function (migration) {
var id = migration.match(/^(\d+)/)[0];
if (!~appliedMigrationIds.indexOf(id) && migration.match(/^\d+\_up.*$/)) {
pending.push(migration);
}
apply();
});
};
return pending;
}

@@ -1,29 +0,25 @@

var cfg = require('../config.js'),
adapter = require('../adapters/pg.js'),
utils = require('../utils.js');
module.exports = function (migrationProvider, adapter) {
return adapter.appliedMigrations().then(function (ids) {
var lastAppliedMigrationId = ids[ids.length - 1];
module.exports = function() {
adapter.appliedMigrations(function(ids) {
var id = ids[ids.length - 1],
migration;
console.log(id, ids);
if (id) {
utils.getMigrationsList().forEach(function(m) {
var match = m.match(/^(\d+)_down/);
if (match && match[1] == id) {
migration = m;
}
});
if (!migration) {
utils.panic(new Error('can\'t find migration with id ', id));
}
adapter.rollbackMigration(migration, function() {
console.log('done');
process.exit();
});
} else {
if (!lastAppliedMigrationId) {
console.log('Nothing to rollback');
process.exit();
return;
}
var migration = migrationProvider.getMigrationsList().find(function (migration) {
var baseName = migration.match(/^(\d+)_down/);
if (baseName && baseName[1] == lastAppliedMigrationId) {
return true
}
return false;
});
if (!migration) {
throw new Error('Can\'t find migration with id ', lastAppliedMigrationId);
}
var sql = migrationProvider.getSql(migration);
return adapter.rollbackMigration(migration, sql);
});
};

@@ -0,0 +0,0 @@ /**

@@ -1,1 +0,62 @@

module.exports.run = require('./run.js');
var MigrationProvider = require('./migration-provider');
var PgAdapter = require('./adapters/pg');
var migrateCommand = require('./cmds/migrate')
var rollbackCommand = require('./cmds/rollback');
function migrate(config) {
var migrationProvider = MigrationProvider(config.migrationsDir);
var adapter = PgAdapter(config);
return migrateCommand(migrationProvider, adapter).then(function () {
return adapter.dispose();
}, function (error) {
function rethrowOriginalError() {
throw error;
}
return adapter.dispose().then(rethrowOriginalError, rethrowOriginalError);
});
}
function rollback(config) {
var migrationProvider = MigrationProvider(config.migrationsDir);
var adapter = PgAdapter(config);
return rollbackCommand(migrationProvider, adapter).then(function () {
return adapter.dispose();
}, function (error) {
function rethrowOriginalError() {
throw error;
}
return adapter.dispose().then(rethrowOriginalError, rethrowOriginalError);
});
}
module.exports = {
migrate: migrate,
rollback: rollback,
run: function (config) {
var args = process.argv.slice(2);
switch (args[0]) {
case 'create':
require('./cmds/create_migration.js')(args[1]);
break;
case 'migrate':
migrate(config).then(onCliSuccess, onCliError);
break;
case 'rollback':
rollback(config).then(onCliSuccess, onCliError);
break;
default:
console.log('exit');
}
function onCliSuccess() {
console.log('done');
process.exit();
}
function onCliError(error) {
console.error('ERROR:', error);
process.exit(1);
}
}
};
var path = require('path');
require('./').run({
basedir: __dirname,
migrationsDir: path.resolve(__dirname, 'migrations'),

@@ -6,0 +5,0 @@ user: 'dabramov',

{
"name": "sql-migrations",
"version": "1.0.2",
"version": "1.0.3",
"description": "raw SQL migrations library for Node.js",

@@ -5,0 +5,0 @@ "main": "index.js",

@@ -14,3 +14,2 @@ node-sql-migrations

require('sql-migrations').run({
basedir: __dirname,
migrationsDir: path.resolve(__dirname, 'migrations'),

@@ -47,3 +46,31 @@ user: 'dabramov',

### Programmatic API
#### Migrate
In your project
```js
require('sql-migrations').migrate({
migrationsDir: path.resolve(__dirname, 'migrations'),
user: 'dabramov',
host: 'localhost',
password: 'password',
db: 'sql_migrations',
port: 5432
});
```
This returns a promise which resolves/rejects whenever the migration is complete.
#### Rollback
In your project
```js
require('sql-migrations').rollback({
migrationsDir: path.resolve(__dirname, 'migrations'),
user: 'dabramov',
host: 'localhost',
password: 'password',
db: 'sql_migrations',
port: 5432
});
```
This returns a promise which resolves/rejects whenever the rollback is complete.
### Migration files

@@ -50,0 +77,0 @@ write raw sql in your migrations

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc