build-indexes.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // ██████╗ ██╗ ██╗██╗██╗ ██████╗ ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗███████╗███████╗
  2. // ██╔══██╗██║ ██║██║██║ ██╔══██╗ ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝██╔════╝██╔════╝
  3. // ██████╔╝██║ ██║██║██║ ██║ ██║ ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ █████╗ ███████╗
  4. // ██╔══██╗██║ ██║██║██║ ██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ ██╔══╝ ╚════██║
  5. // ██████╔╝╚██████╔╝██║███████╗██████╔╝ ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗███████╗███████║
  6. // ╚═════╝ ╚═════╝ ╚═╝╚══════╝╚═════╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝
  7. //
  8. // Build database indexes as needed.
  9. var _ = require('@sailshq/lodash');
  10. var async = require('async');
  11. var escapeTableName = require('./escape-table-name');
  12. var runNativeQuery = require('../query/run-native-query');
  13. module.exports = function buildIndexes(options, cb) {
  14. // ╦ ╦╔═╗╦ ╦╔╦╗╔═╗╔╦╗╔═╗ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐
  15. // ╚╗╔╝╠═╣║ ║ ║║╠═╣ ║ ║╣ │ │├─┘ │ ││ ││││└─┐
  16. // ╚╝ ╩ ╩╩═╝╩═╩╝╩ ╩ ╩ ╚═╝ └─┘┴ ┴ ┴└─┘┘└┘└─┘
  17. if (_.isUndefined(options) || !_.isPlainObject(options)) {
  18. throw new Error('Invalid options argument. Options must contain: connection, definition, and tableName.');
  19. }
  20. if (!_.has(options, 'connection') || !_.isObject(options.connection)) {
  21. throw new Error('Invalid option used in options argument. Missing or invalid connection.');
  22. }
  23. if (!_.has(options, 'definition') || !_.isPlainObject(options.definition)) {
  24. throw new Error('Invalid option used in options argument. Missing or invalid definition.');
  25. }
  26. if (!_.has(options, 'tableName') || !_.isString(options.tableName)) {
  27. throw new Error('Invalid option used in options argument. Missing or invalid tableName.');
  28. }
  29. // ╔═╗╦╔╗╔╔╦╗ ┌─┐┌┐┌┬ ┬ ┬┌┐┌┌┬┐┌─┐─┐ ┬┌─┐┌─┐
  30. // ╠╣ ║║║║ ║║ ├─┤│││└┬┘ ││││ ││├┤ ┌┴┬┘├┤ └─┐
  31. // ╚ ╩╝╚╝═╩╝ ┴ ┴┘└┘ ┴ ┴┘└┘─┴┘└─┘┴ └─└─┘└─┘
  32. var indexes = _.reduce(options.definition, function reduce(meta, val, key) {
  33. if (_.has(val, 'index')) {
  34. meta.push(key);
  35. }
  36. return meta;
  37. }, []);
  38. // ╔╗ ╦ ╦╦╦ ╔╦╗ ┬┌┐┌┌┬┐┌─┐─┐ ┬┌─┐┌─┐
  39. // ╠╩╗║ ║║║ ║║ ││││ ││├┤ ┌┴┬┘├┤ └─┐
  40. // ╚═╝╚═╝╩╩═╝═╩╝ ┴┘└┘─┴┘└─┘┴ └─└─┘└─┘
  41. // Build indexes in series
  42. async.eachSeries(indexes, function build(name, nextIndex) {
  43. // Strip slashes from table name, used to namespace index
  44. var cleanTable = options.tableName.replace(/['"]/g, '');
  45. // Build a query to create a namespaced index tableName_key
  46. var query = 'CREATE INDEX ' + escapeTableName(cleanTable + '_' + name) + ' on ' + options.tableName + ' (' + escapeTableName(name) + ');';
  47. // Run the native query
  48. runNativeQuery(options.connection, query, [], undefined, nextIndex);
  49. }, cb);
  50. };