compiler.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _assign2 = require('lodash/assign');
  4. var _assign3 = _interopRequireDefault(_assign2);
  5. var _helpers = require('./helpers');
  6. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7. // The "SchemaCompiler" takes all of the query statements which have been
  8. // gathered in the "SchemaBuilder" and turns them into an array of
  9. // properly formatted / bound query strings.
  10. function SchemaCompiler(client, builder) {
  11. this.builder = builder;
  12. this.client = client;
  13. this.schema = builder._schema;
  14. this.formatter = client.formatter();
  15. this.sequence = [];
  16. }
  17. (0, _assign3.default)(SchemaCompiler.prototype, {
  18. pushQuery: _helpers.pushQuery,
  19. pushAdditional: _helpers.pushAdditional,
  20. createTable: buildTable('create'),
  21. createTableIfNotExists: buildTable('createIfNot'),
  22. alterTable: buildTable('alter'),
  23. dropTablePrefix: 'drop table ',
  24. dropTable: function dropTable(tableName) {
  25. this.pushQuery(this.dropTablePrefix + this.formatter.wrap(prefixedTableName(this.schema, tableName)));
  26. },
  27. dropTableIfExists: function dropTableIfExists(tableName) {
  28. this.pushQuery(this.dropTablePrefix + 'if exists ' + this.formatter.wrap(prefixedTableName(this.schema, tableName)));
  29. },
  30. raw: function raw(sql, bindings) {
  31. this.sequence.push(this.client.raw(sql, bindings).toSQL());
  32. },
  33. toSQL: function toSQL() {
  34. var sequence = this.builder._sequence;
  35. for (var i = 0, l = sequence.length; i < l; i++) {
  36. var query = sequence[i];
  37. this[query.method].apply(this, query.args);
  38. }
  39. return this.sequence;
  40. }
  41. });
  42. function buildTable(type) {
  43. return function (tableName, fn) {
  44. var builder = this.client.tableBuilder(type, tableName, fn);
  45. builder.setSchema(this.schema);
  46. var sql = builder.toSQL();
  47. for (var i = 0, l = sql.length; i < l; i++) {
  48. this.sequence.push(sql[i]);
  49. }
  50. };
  51. }
  52. function prefixedTableName(prefix, table) {
  53. return prefix ? prefix + '.' + table : table;
  54. }
  55. exports.default = SchemaCompiler;
  56. module.exports = exports['default'];