diff --git a/migrations/1509439657189-add_machine_name_to_devices.js b/migrations/1509439657189-add_machine_name_to_devices.js index 5fc75339..27943eb9 100644 --- a/migrations/1509439657189-add_machine_name_to_devices.js +++ b/migrations/1509439657189-add_machine_name_to_devices.js @@ -1,12 +1,20 @@ const db = require('./db') +const migrateTools = require('./migrate-tools') exports.up = function (next) { - const sql = [ - 'alter table devices add column name text not null' - ] - db.multi(sql, next) + return migrateTools.migrateNames() + .then(updateSql => { + const sql = [ + 'alter table devices add column name text', + updateSql, + 'alter table devices alter column name set not null' + ] + + return db.multi(sql, next) + }) } exports.down = function (next) { - next() + const sql = ['alter table devices drop column name'] + db.multi(sql, next) } diff --git a/migrations/migrate-tools.js b/migrations/migrate-tools.js new file mode 100644 index 00000000..8a084ede --- /dev/null +++ b/migrations/migrate-tools.js @@ -0,0 +1,16 @@ +const pgp = require('pg-promise')() +const _ = require('lodash/fp') + +const settingsLoader = require('../lib/settings-loader') +const machineLoader = require('../lib/machine-loader') + +module.exports = {migrateNames} + +function migrateNames () { + const cs = new pgp.helpers.ColumnSet(['device_id', 'name'], {table: 'devices'}) + + return settingsLoader.loadLatest() + .then(r => machineLoader.getMachineNames(r.config)) + .then(_.map(r => ({device_id: r.deviceId, name: r.name}))) + .then(data => pgp.helpers.update(data, cs)) +}