formatter.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _typeof2 = require('babel-runtime/helpers/typeof');
  4. var _typeof3 = _interopRequireDefault(_typeof2);
  5. var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
  6. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  7. var _transform2 = require('lodash/transform');
  8. var _transform3 = _interopRequireDefault(_transform2);
  9. var _builder = require('./query/builder');
  10. var _builder2 = _interopRequireDefault(_builder);
  11. var _raw = require('./raw');
  12. var _raw2 = _interopRequireDefault(_raw);
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. // Valid values for the `order by` clause generation.
  15. var orderBys = ['asc', 'desc'];
  16. // Turn this into a lookup map
  17. var operators = (0, _transform3.default)(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'not between', 'ilike', 'not ilike', 'exists', 'not exist', 'rlike', 'not rlike', 'regexp', 'not regexp', '&', '|', '^', '<<', '>>', '~', '~*', '!~', '!~*', '#', '&&', '@>', '<@', '||', '&<', '&>', '-|-', '@@', '!!', ['?', '\\?'], ['?|', '\\?|'], ['?&', '\\?&']], function (result, key) {
  18. if (Array.isArray(key)) {
  19. result[key[0]] = key[1];
  20. } else {
  21. result[key] = key;
  22. }
  23. }, {});
  24. var Formatter = function () {
  25. function Formatter(client, builder) {
  26. (0, _classCallCheck3.default)(this, Formatter);
  27. this.client = client;
  28. this.builder = builder;
  29. this.bindings = [];
  30. }
  31. // Accepts a string or array of columns to wrap as appropriate.
  32. Formatter.prototype.columnize = function columnize(target) {
  33. var columns = Array.isArray(target) ? target : [target];
  34. var str = '',
  35. i = -1;
  36. while (++i < columns.length) {
  37. if (i > 0) str += ', ';
  38. str += this.wrap(columns[i]);
  39. }
  40. return str;
  41. };
  42. // Turns a list of values into a list of ?'s, joining them with commas unless
  43. // a "joining" value is specified (e.g. ' and ')
  44. Formatter.prototype.parameterize = function parameterize(values, notSetValue) {
  45. if (typeof values === 'function') return this.parameter(values);
  46. values = Array.isArray(values) ? values : [values];
  47. var str = '',
  48. i = -1;
  49. while (++i < values.length) {
  50. if (i > 0) str += ', ';
  51. str += this.parameter(values[i] === undefined ? notSetValue : values[i]);
  52. }
  53. return str;
  54. };
  55. // Formats `values` into a parenthesized list of parameters for a `VALUES`
  56. // clause.
  57. //
  58. // [1, 2] -> '(?, ?)'
  59. // [[1, 2], [3, 4]] -> '((?, ?), (?, ?))'
  60. // knex('table') -> '(select * from "table")'
  61. // knex.raw('select ?', 1) -> '(select ?)'
  62. //
  63. Formatter.prototype.values = function values(_values) {
  64. var _this = this;
  65. if (Array.isArray(_values)) {
  66. if (Array.isArray(_values[0])) {
  67. return '(' + _values.map(function (value) {
  68. return '(' + _this.parameterize(value) + ')';
  69. }).join(', ') + ')';
  70. }
  71. return '(' + this.parameterize(_values) + ')';
  72. }
  73. if (_values instanceof _raw2.default) {
  74. return '(' + this.parameter(_values) + ')';
  75. }
  76. return this.parameter(_values);
  77. };
  78. // Checks whether a value is a function... if it is, we compile it
  79. // otherwise we check whether it's a raw
  80. Formatter.prototype.parameter = function parameter(value) {
  81. if (typeof value === 'function') {
  82. return this.outputQuery(this.compileCallback(value), true);
  83. }
  84. return this.unwrapRaw(value, true) || '?';
  85. };
  86. Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
  87. var query = void 0;
  88. if (value instanceof _builder2.default) {
  89. query = this.client.queryCompiler(value).toSQL();
  90. if (query.bindings) {
  91. this.bindings = this.bindings.concat(query.bindings);
  92. }
  93. return this.outputQuery(query, isParameter);
  94. }
  95. if (value instanceof _raw2.default) {
  96. value.client = this.client;
  97. query = value.toSQL();
  98. if (query.bindings) {
  99. this.bindings = this.bindings.concat(query.bindings);
  100. }
  101. return query.sql;
  102. }
  103. if (isParameter) {
  104. this.bindings.push(value);
  105. }
  106. };
  107. /**
  108. * Creates SQL for a parameter, which might be passed to where() or .with() or
  109. * pretty much anywhere in API.
  110. *
  111. * @param query Callback (for where or complete builder), Raw or QueryBuilder
  112. * @param method Optional at least 'select' or 'update' are valid
  113. */
  114. Formatter.prototype.rawOrFn = function rawOrFn(value, method) {
  115. if (typeof value === 'function') {
  116. return this.outputQuery(this.compileCallback(value, method));
  117. }
  118. return this.unwrapRaw(value) || '';
  119. };
  120. // Puts the appropriate wrapper around a value depending on the database
  121. // engine, unless it's a knex.raw value, in which case it's left alone.
  122. Formatter.prototype.wrap = function wrap(value) {
  123. var raw = this.unwrapRaw(value);
  124. if (raw) return raw;
  125. switch (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) {
  126. case 'function':
  127. return this.outputQuery(this.compileCallback(value), true);
  128. case 'object':
  129. return this.parseObject(value);
  130. case 'number':
  131. return value;
  132. default:
  133. return this.wrapString(value + '');
  134. }
  135. };
  136. Formatter.prototype.wrapAsIdentifier = function wrapAsIdentifier(value) {
  137. var queryContext = this.builder.queryContext();
  138. return this.client.wrapIdentifier((value || '').trim(), queryContext);
  139. };
  140. Formatter.prototype.alias = function alias(first, second) {
  141. return first + ' as ' + second;
  142. };
  143. Formatter.prototype.operator = function operator(value) {
  144. var raw = this.unwrapRaw(value);
  145. if (raw) return raw;
  146. var operator = operators[(value || '').toLowerCase()];
  147. if (!operator) {
  148. throw new TypeError('The operator "' + value + '" is not permitted');
  149. }
  150. return operator;
  151. };
  152. // Specify the direction of the ordering.
  153. Formatter.prototype.direction = function direction(value) {
  154. var raw = this.unwrapRaw(value);
  155. if (raw) return raw;
  156. return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc';
  157. };
  158. // Compiles a callback using the query builder.
  159. Formatter.prototype.compileCallback = function compileCallback(callback, method) {
  160. var client = this.client;
  161. // Build the callback
  162. var builder = client.queryBuilder();
  163. callback.call(builder, builder);
  164. // Compile the callback, using the current formatter (to track all bindings).
  165. var compiler = client.queryCompiler(builder);
  166. compiler.formatter = this;
  167. // Return the compiled & parameterized sql.
  168. return compiler.toSQL(method || builder._method || 'select');
  169. };
  170. // Ensures the query is aliased if necessary.
  171. Formatter.prototype.outputQuery = function outputQuery(compiled, isParameter) {
  172. var sql = compiled.sql || '';
  173. if (sql) {
  174. if ((compiled.method === 'select' || compiled.method === 'first') && (isParameter || compiled.as)) {
  175. sql = '(' + sql + ')';
  176. if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
  177. }
  178. }
  179. return sql;
  180. };
  181. // Key-value notation for alias
  182. Formatter.prototype.parseObject = function parseObject(obj) {
  183. var ret = [];
  184. for (var alias in obj) {
  185. var queryOrIdentifier = obj[alias];
  186. // Avoids double aliasing for subqueries
  187. if (typeof queryOrIdentifier === 'function') {
  188. var compiled = this.compileCallback(queryOrIdentifier);
  189. compiled.as = alias; // enforces the object's alias
  190. ret.push(this.outputQuery(compiled, true));
  191. } else if (queryOrIdentifier instanceof _builder2.default) {
  192. ret.push(this.alias('(' + this.wrap(queryOrIdentifier) + ')', this.wrapAsIdentifier(alias)));
  193. } else {
  194. ret.push(this.alias(this.wrap(queryOrIdentifier), this.wrapAsIdentifier(alias)));
  195. }
  196. }
  197. return ret.join(', ');
  198. };
  199. // Coerce to string to prevent strange errors when it's not a string.
  200. Formatter.prototype.wrapString = function wrapString(value) {
  201. var asIndex = value.toLowerCase().indexOf(' as ');
  202. if (asIndex !== -1) {
  203. var first = value.slice(0, asIndex);
  204. var second = value.slice(asIndex + 4);
  205. return this.alias(this.wrap(first), this.wrapAsIdentifier(second));
  206. }
  207. var wrapped = [];
  208. var i = -1;
  209. var segments = value.split('.');
  210. while (++i < segments.length) {
  211. value = segments[i];
  212. if (i === 0 && segments.length > 1) {
  213. wrapped.push(this.wrap((value || '').trim()));
  214. } else {
  215. wrapped.push(this.wrapAsIdentifier(value));
  216. }
  217. }
  218. return wrapped.join('.');
  219. };
  220. return Formatter;
  221. }();
  222. exports.default = Formatter;
  223. module.exports = exports['default'];