tablecompiler.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _getIterator2 = require('babel-runtime/core-js/get-iterator');
  4. var _getIterator3 = _interopRequireDefault(_getIterator2);
  5. var _isArray3 = require('lodash/isArray');
  6. var _isArray4 = _interopRequireDefault(_isArray3);
  7. var _indexOf2 = require('lodash/indexOf');
  8. var _indexOf3 = _interopRequireDefault(_indexOf2);
  9. var _isEmpty2 = require('lodash/isEmpty');
  10. var _isEmpty3 = _interopRequireDefault(_isEmpty2);
  11. var _tail2 = require('lodash/tail');
  12. var _tail3 = _interopRequireDefault(_tail2);
  13. var _first2 = require('lodash/first');
  14. var _first3 = _interopRequireDefault(_first2);
  15. var _map2 = require('lodash/map');
  16. var _map3 = _interopRequireDefault(_map2);
  17. var _reduce2 = require('lodash/reduce');
  18. var _reduce3 = _interopRequireDefault(_reduce2);
  19. var _groupBy2 = require('lodash/groupBy');
  20. var _groupBy3 = _interopRequireDefault(_groupBy2);
  21. var _helpers = require('./helpers');
  22. var _helpers2 = require('../helpers');
  23. var helpers = _interopRequireWildcard(_helpers2);
  24. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  25. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26. /* eslint max-len:0 */
  27. // Table Compiler
  28. // -------
  29. function TableCompiler(client, tableBuilder) {
  30. this.client = client;
  31. this.method = tableBuilder._method;
  32. this.schemaNameRaw = tableBuilder._schemaName;
  33. this.tableNameRaw = tableBuilder._tableName;
  34. this.single = tableBuilder._single;
  35. this.grouped = (0, _groupBy3.default)(tableBuilder._statements, 'grouping');
  36. this.formatter = client.formatter();
  37. this.sequence = [];
  38. this._formatting = client.config && client.config.formatting;
  39. }
  40. TableCompiler.prototype.pushQuery = _helpers.pushQuery;
  41. TableCompiler.prototype.pushAdditional = _helpers.pushAdditional;
  42. // Convert the tableCompiler toSQL
  43. TableCompiler.prototype.toSQL = function () {
  44. this[this.method]();
  45. return this.sequence;
  46. };
  47. TableCompiler.prototype.lowerCase = true;
  48. // Column Compilation
  49. // -------
  50. // If this is a table "creation", we need to first run through all
  51. // of the columns to build them into a single string,
  52. // and then run through anything else and push it to the query sequence.
  53. TableCompiler.prototype.createAlterTableMethods = null;
  54. TableCompiler.prototype.create = function (ifNot) {
  55. var columnBuilders = this.getColumns();
  56. var columns = columnBuilders.map(function (col) {
  57. return col.toSQL();
  58. });
  59. var columnTypes = this.getColumnTypes(columns);
  60. if (this.createAlterTableMethods) {
  61. this.alterTableForCreate(columnTypes);
  62. }
  63. this.createQuery(columnTypes, ifNot);
  64. this.columnQueries(columns);
  65. delete this.single.comment;
  66. this.alterTable();
  67. };
  68. // Only create the table if it doesn't exist.
  69. TableCompiler.prototype.createIfNot = function () {
  70. this.create(true);
  71. };
  72. // If we're altering the table, we need to one-by-one
  73. // go through and handle each of the queries associated
  74. // with altering the table's schema.
  75. TableCompiler.prototype.alter = function () {
  76. var addColBuilders = this.getColumns();
  77. var addColumns = addColBuilders.map(function (col) {
  78. return col.toSQL();
  79. });
  80. var alterColBuilders = this.getColumns('alter');
  81. var alterColumns = alterColBuilders.map(function (col) {
  82. return col.toSQL();
  83. });
  84. var addColumnTypes = this.getColumnTypes(addColumns);
  85. var alterColumnTypes = this.getColumnTypes(alterColumns);
  86. this.addColumns(addColumnTypes);
  87. this.alterColumns(alterColumnTypes, alterColBuilders);
  88. this.columnQueries(addColumns);
  89. this.columnQueries(alterColumns);
  90. this.alterTable();
  91. };
  92. TableCompiler.prototype.foreign = function (foreignData) {
  93. if (foreignData.inTable && foreignData.references) {
  94. var keyName = foreignData.keyName ? this.formatter.wrap(foreignData.keyName) : this._indexCommand('foreign', this.tableNameRaw, foreignData.column);
  95. var column = this.formatter.columnize(foreignData.column);
  96. var references = this.formatter.columnize(foreignData.references);
  97. var inTable = this.formatter.wrap(foreignData.inTable);
  98. var onUpdate = foreignData.onUpdate ? (this.lowerCase ? ' on update ' : ' ON UPDATE ') + foreignData.onUpdate : '';
  99. var onDelete = foreignData.onDelete ? (this.lowerCase ? ' on delete ' : ' ON DELETE ') + foreignData.onDelete : '';
  100. if (this.lowerCase) {
  101. this.pushQuery((!this.forCreate ? 'alter table ' + this.tableName() + ' add ' : '') + 'constraint ' + keyName + ' ' + 'foreign key (' + column + ') references ' + inTable + ' (' + references + ')' + onUpdate + onDelete);
  102. } else {
  103. this.pushQuery((!this.forCreate ? 'ALTER TABLE ' + this.tableName() + ' ADD ' : '') + 'CONSTRAINT ' + keyName + ' ' + 'FOREIGN KEY (' + column + ') REFERENCES ' + inTable + ' (' + references + ')' + onUpdate + onDelete);
  104. }
  105. }
  106. };
  107. // Get all of the column sql & bindings individually for building the table queries.
  108. TableCompiler.prototype.getColumnTypes = function (columns) {
  109. return (0, _reduce3.default)((0, _map3.default)(columns, _first3.default), function (memo, column) {
  110. memo.sql.push(column.sql);
  111. memo.bindings.concat(column.bindings);
  112. return memo;
  113. }, { sql: [], bindings: [] });
  114. };
  115. // Adds all of the additional queries from the "column"
  116. TableCompiler.prototype.columnQueries = function (columns) {
  117. var queries = (0, _reduce3.default)((0, _map3.default)(columns, _tail3.default), function (memo, column) {
  118. if (!(0, _isEmpty3.default)(column)) return memo.concat(column);
  119. return memo;
  120. }, []);
  121. for (var _iterator = queries, _isArray2 = Array.isArray(_iterator), _i = 0, _iterator = _isArray2 ? _iterator : (0, _getIterator3.default)(_iterator);;) {
  122. var _ref;
  123. if (_isArray2) {
  124. if (_i >= _iterator.length) break;
  125. _ref = _iterator[_i++];
  126. } else {
  127. _i = _iterator.next();
  128. if (_i.done) break;
  129. _ref = _i.value;
  130. }
  131. var q = _ref;
  132. this.pushQuery(q);
  133. }
  134. };
  135. // Add a new column.
  136. TableCompiler.prototype.addColumnsPrefix = 'add column ';
  137. // All of the columns to "add" for the query
  138. TableCompiler.prototype.addColumns = function (columns, prefix) {
  139. prefix = prefix || this.addColumnsPrefix;
  140. if (columns.sql.length > 0) {
  141. var columnSql = (0, _map3.default)(columns.sql, function (column) {
  142. return prefix + column;
  143. });
  144. this.pushQuery({
  145. sql: (this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + columnSql.join(', '),
  146. bindings: columns.bindings
  147. });
  148. }
  149. };
  150. // Alter column
  151. TableCompiler.prototype.alterColumnsPrefix = 'alter column ';
  152. TableCompiler.prototype.alterColumns = function (columns, colBuilders) {
  153. if (columns.sql.length > 0) {
  154. this.addColumns(columns, this.alterColumnsPrefix, colBuilders);
  155. }
  156. };
  157. // Compile the columns as needed for the current create or alter table
  158. TableCompiler.prototype.getColumns = function (method) {
  159. var _this = this;
  160. var columns = this.grouped.columns || [];
  161. method = method || 'add';
  162. return columns.filter(function (column) {
  163. return column.builder._method === method;
  164. }).map(function (column) {
  165. return _this.client.columnCompiler(_this, column.builder);
  166. });
  167. };
  168. TableCompiler.prototype.tableName = function () {
  169. var name = this.schemaNameRaw ? this.schemaNameRaw + '.' + this.tableNameRaw : this.tableNameRaw;
  170. return this.formatter.wrap(name);
  171. };
  172. // Generate all of the alter column statements necessary for the query.
  173. TableCompiler.prototype.alterTable = function () {
  174. var alterTable = this.grouped.alterTable || [];
  175. for (var i = 0, l = alterTable.length; i < l; i++) {
  176. var statement = alterTable[i];
  177. if (this[statement.method]) {
  178. this[statement.method].apply(this, statement.args);
  179. } else {
  180. helpers.error('Debug: ' + statement.method + ' does not exist');
  181. }
  182. }
  183. for (var item in this.single) {
  184. if (typeof this[item] === 'function') this[item](this.single[item]);
  185. }
  186. };
  187. TableCompiler.prototype.alterTableForCreate = function (columnTypes) {
  188. this.forCreate = true;
  189. var savedSequence = this.sequence;
  190. var alterTable = this.grouped.alterTable || [];
  191. this.grouped.alterTable = [];
  192. for (var i = 0, l = alterTable.length; i < l; i++) {
  193. var statement = alterTable[i];
  194. if ((0, _indexOf3.default)(this.createAlterTableMethods, statement.method) < 0) {
  195. this.grouped.alterTable.push(statement);
  196. continue;
  197. }
  198. if (this[statement.method]) {
  199. this.sequence = [];
  200. this[statement.method].apply(this, statement.args);
  201. columnTypes.sql.push(this.sequence[0].sql);
  202. } else {
  203. helpers.error('Debug: ' + statement.method + ' does not exist');
  204. }
  205. }
  206. this.sequence = savedSequence;
  207. this.forCreate = false;
  208. };
  209. // Drop the index on the current table.
  210. TableCompiler.prototype.dropIndex = function (value) {
  211. this.pushQuery('drop index' + value);
  212. };
  213. // Drop the unique
  214. TableCompiler.prototype.dropUnique = TableCompiler.prototype.dropForeign = function () {
  215. throw new Error('Method implemented in the dialect driver');
  216. };
  217. TableCompiler.prototype.dropColumnPrefix = 'drop column ';
  218. TableCompiler.prototype.dropColumn = function () {
  219. var _this2 = this;
  220. var columns = helpers.normalizeArr.apply(null, arguments);
  221. var drops = (0, _map3.default)((0, _isArray4.default)(columns) ? columns : [columns], function (column) {
  222. return _this2.dropColumnPrefix + _this2.formatter.wrap(column);
  223. });
  224. this.pushQuery((this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + drops.join(', '));
  225. };
  226. // If no name was specified for this index, we will create one using a basic
  227. // convention of the table name, followed by the columns, followed by an
  228. // index type, such as primary or index, which makes the index unique.
  229. TableCompiler.prototype._indexCommand = function (type, tableName, columns) {
  230. if (!(0, _isArray4.default)(columns)) columns = columns ? [columns] : [];
  231. var table = tableName.replace(/\.|-/g, '_');
  232. var indexName = (table + '_' + columns.join('_') + '_' + type).toLowerCase();
  233. return this.formatter.wrap(indexName);
  234. };
  235. exports.default = TableCompiler;
  236. module.exports = exports['default'];