run-drop-strategy.js 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // ██████╗ ██████╗ ██████╗ ██████╗
  2. // ██╔══██╗██╔══██╗██╔═══██╗██╔══██╗
  3. // ██║ ██║██████╔╝██║ ██║██████╔╝
  4. // ██║ ██║██╔══██╗██║ ██║██╔═══╝
  5. // ██████╔╝██║ ██║╚██████╔╝██║
  6. // ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝
  7. //
  8. // Drops each table in the database and rebuilds it with the new model definition/
  9. var _ = require('@sailshq/lodash');
  10. var async = require('async');
  11. module.exports = function dropStrategy(orm, cb) {
  12. // Refuse to run this migration strategy in production.
  13. if (process.env.NODE_ENV === 'production' && !process.env.ALLOW_UNSAFE_MIGRATIONS) {
  14. return cb(new Error('`migrate: \'drop\'` strategy is not supported in production, please change to `migrate: \'safe\'`.'));
  15. }
  16. async.each(_.keys(orm.collections), function simultaneouslyMigrateEachModel(modelIdentity, next) {
  17. var WLModel = orm.collections[modelIdentity];
  18. // Grab the adapter to perform the query on
  19. var datastoreName = WLModel.datastore;
  20. var WLAdapter = orm.datastores[datastoreName].adapter;
  21. // Set a tableName to use
  22. var tableName = WLModel.tableName;
  23. // Build a dictionary to represent the underlying physical database structure
  24. var tableDDLSpec = {};
  25. _.each(WLModel.schema, function parseAttribute(wlsAttrDef) {
  26. // If this is a plural association, then skip it.
  27. // (it is impossible for a key from this error to match up with one of these-- they don't even have column names)
  28. if (wlsAttrDef.collection) {
  29. return;
  30. }
  31. var columnName = wlsAttrDef.columnName;
  32. // If the attribute doesn't have an `autoMigrations` key on it, ignore it.
  33. if (!_.has(wlsAttrDef, 'autoMigrations')) {
  34. return;
  35. }
  36. tableDDLSpec[columnName] = wlsAttrDef.autoMigrations;
  37. });
  38. // Set Primary Key flag on the primary key attribute
  39. var primaryKeyAttrName = WLModel.primaryKey;
  40. var primaryKey = WLModel.schema[primaryKeyAttrName];
  41. if (primaryKey) {
  42. var pkColumnName = primaryKey.columnName;
  43. tableDDLSpec[pkColumnName].primaryKey = true;
  44. }
  45. // ╔╦╗╦═╗╔═╗╔═╗ ┌┬┐┌─┐┌┐ ┬ ┌─┐
  46. // ║║╠╦╝║ ║╠═╝ │ ├─┤├┴┐│ ├┤
  47. // ═╩╝╩╚═╚═╝╩ ┴ ┴ ┴└─┘┴─┘└─┘
  48. WLAdapter.drop(datastoreName, tableName, undefined, function dropCallback(err) {
  49. if (err) {
  50. return next(err);
  51. }
  52. // ╔╦╗╔═╗╔═╗╦╔╗╔╔═╗ ┌┬┐┌─┐┌┐ ┬ ┌─┐
  53. // ║║║╣ ╠╣ ║║║║║╣ │ ├─┤├┴┐│ ├┤
  54. // ═╩╝╚═╝╚ ╩╝╚╝╚═╝ ┴ ┴ ┴└─┘┴─┘└─┘
  55. WLAdapter.define(datastoreName, tableName, tableDDLSpec, function defineCallback(err) {
  56. if (err) {
  57. return next(err);
  58. }
  59. return next();
  60. });
  61. });
  62. }, function afterMigrate(err) {
  63. if (err) {
  64. return cb(err);
  65. }
  66. return cb();
  67. });
  68. };