builder.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _keys = require('babel-runtime/core-js/object/keys');
  4. var _keys2 = _interopRequireDefault(_keys);
  5. var _toArray2 = require('lodash/toArray');
  6. var _toArray3 = _interopRequireDefault(_toArray2);
  7. var _tail2 = require('lodash/tail');
  8. var _tail3 = _interopRequireDefault(_tail2);
  9. var _isUndefined2 = require('lodash/isUndefined');
  10. var _isUndefined3 = _interopRequireDefault(_isUndefined2);
  11. var _isString2 = require('lodash/isString');
  12. var _isString3 = _interopRequireDefault(_isString2);
  13. var _isObject2 = require('lodash/isObject');
  14. var _isObject3 = _interopRequireDefault(_isObject2);
  15. var _isNumber2 = require('lodash/isNumber');
  16. var _isNumber3 = _interopRequireDefault(_isNumber2);
  17. var _isFunction2 = require('lodash/isFunction');
  18. var _isFunction3 = _interopRequireDefault(_isFunction2);
  19. var _isEmpty2 = require('lodash/isEmpty');
  20. var _isEmpty3 = _interopRequireDefault(_isEmpty2);
  21. var _isBoolean2 = require('lodash/isBoolean');
  22. var _isBoolean3 = _interopRequireDefault(_isBoolean2);
  23. var _each2 = require('lodash/each');
  24. var _each3 = _interopRequireDefault(_each2);
  25. var _clone2 = require('lodash/clone');
  26. var _clone3 = _interopRequireDefault(_clone2);
  27. var _assign2 = require('lodash/assign');
  28. var _assign3 = _interopRequireDefault(_assign2);
  29. var _assert = require('assert');
  30. var _assert2 = _interopRequireDefault(_assert);
  31. var _inherits = require('inherits');
  32. var _inherits2 = _interopRequireDefault(_inherits);
  33. var _events = require('events');
  34. var _raw = require('../raw');
  35. var _raw2 = _interopRequireDefault(_raw);
  36. var _helpers = require('../helpers');
  37. var helpers = _interopRequireWildcard(_helpers);
  38. var _joinclause = require('./joinclause');
  39. var _joinclause2 = _interopRequireDefault(_joinclause);
  40. 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; } }
  41. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  42. // Typically called from `knex.builder`,
  43. // start a new query building chain.
  44. // Builder
  45. // -------
  46. function Builder(client) {
  47. this.client = client;
  48. this.and = this;
  49. this._single = {};
  50. this._statements = [];
  51. this._method = 'select';
  52. this._debug = client.config && client.config.debug;
  53. // Internal flags used in the builder.
  54. this._joinFlag = 'inner';
  55. this._boolFlag = 'and';
  56. this._notFlag = false;
  57. }
  58. (0, _inherits2.default)(Builder, _events.EventEmitter);
  59. (0, _assign3.default)(Builder.prototype, {
  60. toString: function toString() {
  61. return this.toQuery();
  62. },
  63. // Convert the current query "toSQL"
  64. toSQL: function toSQL(method, tz) {
  65. return this.client.queryCompiler(this).toSQL(method || this._method, tz);
  66. },
  67. // Create a shallow clone of the current query builder.
  68. clone: function clone() {
  69. var cloned = new this.constructor(this.client);
  70. cloned._method = this._method;
  71. cloned._single = (0, _clone3.default)(this._single);
  72. cloned._statements = (0, _clone3.default)(this._statements);
  73. cloned._debug = this._debug;
  74. // `_option` is assigned by the `Interface` mixin.
  75. if (!(0, _isUndefined3.default)(this._options)) {
  76. cloned._options = (0, _clone3.default)(this._options);
  77. }
  78. return cloned;
  79. },
  80. timeout: function timeout(ms) {
  81. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  82. cancel = _ref.cancel;
  83. if ((0, _isNumber3.default)(ms) && ms > 0) {
  84. this._timeout = ms;
  85. if (cancel) {
  86. this.client.assertCanCancelQuery();
  87. this._cancelOnTimeout = true;
  88. }
  89. }
  90. return this;
  91. },
  92. // With
  93. // ------
  94. with: function _with(alias, statement, bindings) {
  95. if (typeof alias !== 'string') {
  96. throw new Error('with() first argument must be a string');
  97. }
  98. if (typeof statement === 'function') {
  99. return this.withWrapped(alias, statement);
  100. }
  101. // Allow a raw statement to be passed along to the query.
  102. if (statement instanceof _raw2.default && arguments.length >= 2) {
  103. return this.withRaw(alias, statement, bindings);
  104. }
  105. throw new Error('with() second argument must be a function or a raw');
  106. },
  107. // Adds a raw `with` clause to the query.
  108. withRaw: function withRaw(alias, sql, bindings) {
  109. var raw = sql instanceof _raw2.default ? sql : this.client.raw(sql, bindings);
  110. this._statements.push({
  111. grouping: 'with',
  112. type: 'withRaw',
  113. alias: alias,
  114. value: raw
  115. });
  116. return this;
  117. },
  118. // Helper for compiling any advanced `with` queries.
  119. withWrapped: function withWrapped(alias, callback) {
  120. this._statements.push({
  121. grouping: 'with',
  122. type: 'withWrapped',
  123. alias: alias,
  124. value: callback
  125. });
  126. return this;
  127. },
  128. // Select
  129. // ------
  130. // Adds a column or columns to the list of "columns"
  131. // being selected on the query.
  132. columns: function columns(column) {
  133. if (!column) return this;
  134. this._statements.push({
  135. grouping: 'columns',
  136. value: helpers.normalizeArr.apply(null, arguments)
  137. });
  138. return this;
  139. },
  140. // Allow for a sub-select to be explicitly aliased as a column,
  141. // without needing to compile the query in a where.
  142. as: function as(column) {
  143. this._single.as = column;
  144. return this;
  145. },
  146. // Prepends the `schemaName` on `tableName` defined by `.table` and `.join`.
  147. withSchema: function withSchema(schemaName) {
  148. this._single.schema = schemaName;
  149. return this;
  150. },
  151. // Sets the `tableName` on the query.
  152. // Alias to "from" for select and "into" for insert statements
  153. // e.g. builder.insert({a: value}).into('tableName')
  154. // `options`: options object containing keys:
  155. // - `only`: whether the query should use SQL's ONLY to not return
  156. // inheriting table data. Defaults to false.
  157. table: function table(tableName) {
  158. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  159. this._single.table = tableName;
  160. this._single.only = options.only === true;
  161. return this;
  162. },
  163. // Adds a `distinct` clause to the query.
  164. distinct: function distinct() {
  165. this._statements.push({
  166. grouping: 'columns',
  167. value: helpers.normalizeArr.apply(null, arguments),
  168. distinct: true
  169. });
  170. return this;
  171. },
  172. // Adds a join clause to the query, allowing for advanced joins
  173. // with an anonymous function as the second argument.
  174. // function(table, first, operator, second)
  175. join: function join(table, first) {
  176. var join = void 0;
  177. var schema = this._single.schema;
  178. var joinType = this._joinType();
  179. if (typeof first === 'function') {
  180. join = new _joinclause2.default(table, joinType, schema);
  181. first.call(join, join);
  182. } else if (joinType === 'raw') {
  183. join = new _joinclause2.default(this.client.raw(table, first), 'raw');
  184. } else {
  185. join = new _joinclause2.default(table, joinType, schema);
  186. if (arguments.length > 1) {
  187. join.on.apply(join, (0, _toArray3.default)(arguments).slice(1));
  188. }
  189. }
  190. this._statements.push(join);
  191. return this;
  192. },
  193. // JOIN blocks:
  194. innerJoin: function innerJoin() {
  195. return this._joinType('inner').join.apply(this, arguments);
  196. },
  197. leftJoin: function leftJoin() {
  198. return this._joinType('left').join.apply(this, arguments);
  199. },
  200. leftOuterJoin: function leftOuterJoin() {
  201. return this._joinType('left outer').join.apply(this, arguments);
  202. },
  203. rightJoin: function rightJoin() {
  204. return this._joinType('right').join.apply(this, arguments);
  205. },
  206. rightOuterJoin: function rightOuterJoin() {
  207. return this._joinType('right outer').join.apply(this, arguments);
  208. },
  209. outerJoin: function outerJoin() {
  210. return this._joinType('outer').join.apply(this, arguments);
  211. },
  212. fullOuterJoin: function fullOuterJoin() {
  213. return this._joinType('full outer').join.apply(this, arguments);
  214. },
  215. crossJoin: function crossJoin() {
  216. return this._joinType('cross').join.apply(this, arguments);
  217. },
  218. joinRaw: function joinRaw() {
  219. return this._joinType('raw').join.apply(this, arguments);
  220. },
  221. // The where function can be used in several ways:
  222. // The most basic is `where(key, value)`, which expands to
  223. // where key = value.
  224. where: function where(column, operator, value) {
  225. // Support "where true || where false"
  226. if (column === false || column === true) {
  227. return this.where(1, '=', column ? 1 : 0);
  228. }
  229. // Check if the column is a function, in which case it's
  230. // a where statement wrapped in parens.
  231. if (typeof column === 'function') {
  232. return this.whereWrapped(column);
  233. }
  234. // Allow a raw statement to be passed along to the query.
  235. if (column instanceof _raw2.default && arguments.length === 1) return this.whereRaw(column);
  236. // Allows `where({id: 2})` syntax.
  237. if ((0, _isObject3.default)(column) && !(column instanceof _raw2.default)) return this._objectWhere(column);
  238. // Enable the where('key', value) syntax, only when there
  239. // are explicitly two arguments passed, so it's not possible to
  240. // do where('key', '!=') and have that turn into where key != null
  241. if (arguments.length === 2) {
  242. value = operator;
  243. operator = '=';
  244. // If the value is null, and it's a two argument query,
  245. // we assume we're going for a `whereNull`.
  246. if (value === null) {
  247. return this.whereNull(column);
  248. }
  249. }
  250. // lower case the operator for comparison purposes
  251. var checkOperator = ('' + operator).toLowerCase().trim();
  252. // If there are 3 arguments, check whether 'in' is one of them.
  253. if (arguments.length === 3) {
  254. if (checkOperator === 'in' || checkOperator === 'not in') {
  255. return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
  256. }
  257. if (checkOperator === 'between' || checkOperator === 'not between') {
  258. return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
  259. }
  260. }
  261. // If the value is still null, check whether they're meaning
  262. // where value is null
  263. if (value === null) {
  264. // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
  265. if (checkOperator === 'is' || checkOperator === 'is not') {
  266. return this._not(checkOperator === 'is not').whereNull(column);
  267. }
  268. }
  269. // Push onto the where statement stack.
  270. this._statements.push({
  271. grouping: 'where',
  272. type: 'whereBasic',
  273. column: column,
  274. operator: operator,
  275. value: value,
  276. not: this._not(),
  277. bool: this._bool()
  278. });
  279. return this;
  280. },
  281. // Adds an `or where` clause to the query.
  282. orWhere: function orWhere() {
  283. this._bool('or');
  284. var obj = arguments[0];
  285. if ((0, _isObject3.default)(obj) && !(0, _isFunction3.default)(obj) && !(obj instanceof _raw2.default)) {
  286. return this.whereWrapped(function () {
  287. for (var key in obj) {
  288. this.andWhere(key, obj[key]);
  289. }
  290. });
  291. }
  292. return this.where.apply(this, arguments);
  293. },
  294. // Adds an `not where` clause to the query.
  295. whereNot: function whereNot() {
  296. return this._not(true).where.apply(this, arguments);
  297. },
  298. // Adds an `or not where` clause to the query.
  299. orWhereNot: function orWhereNot() {
  300. return this._bool('or').whereNot.apply(this, arguments);
  301. },
  302. // Processes an object literal provided in a "where" clause.
  303. _objectWhere: function _objectWhere(obj) {
  304. var boolVal = this._bool();
  305. var notVal = this._not() ? 'Not' : '';
  306. for (var key in obj) {
  307. this[boolVal + 'Where' + notVal](key, obj[key]);
  308. }
  309. return this;
  310. },
  311. // Adds a raw `where` clause to the query.
  312. whereRaw: function whereRaw(sql, bindings) {
  313. var raw = sql instanceof _raw2.default ? sql : this.client.raw(sql, bindings);
  314. this._statements.push({
  315. grouping: 'where',
  316. type: 'whereRaw',
  317. value: raw,
  318. not: this._not(),
  319. bool: this._bool()
  320. });
  321. return this;
  322. },
  323. orWhereRaw: function orWhereRaw(sql, bindings) {
  324. return this._bool('or').whereRaw(sql, bindings);
  325. },
  326. // Helper for compiling any advanced `where` queries.
  327. whereWrapped: function whereWrapped(callback) {
  328. this._statements.push({
  329. grouping: 'where',
  330. type: 'whereWrapped',
  331. value: callback,
  332. not: this._not(),
  333. bool: this._bool()
  334. });
  335. return this;
  336. },
  337. // Adds a `where exists` clause to the query.
  338. whereExists: function whereExists(callback) {
  339. this._statements.push({
  340. grouping: 'where',
  341. type: 'whereExists',
  342. value: callback,
  343. not: this._not(),
  344. bool: this._bool()
  345. });
  346. return this;
  347. },
  348. // Adds an `or where exists` clause to the query.
  349. orWhereExists: function orWhereExists(callback) {
  350. return this._bool('or').whereExists(callback);
  351. },
  352. // Adds a `where not exists` clause to the query.
  353. whereNotExists: function whereNotExists(callback) {
  354. return this._not(true).whereExists(callback);
  355. },
  356. // Adds a `or where not exists` clause to the query.
  357. orWhereNotExists: function orWhereNotExists(callback) {
  358. return this._bool('or').whereNotExists(callback);
  359. },
  360. // Adds a `where in` clause to the query.
  361. whereIn: function whereIn(column, values) {
  362. if (Array.isArray(values) && (0, _isEmpty3.default)(values)) return this.where(this._not());
  363. this._statements.push({
  364. grouping: 'where',
  365. type: 'whereIn',
  366. column: column,
  367. value: values,
  368. not: this._not(),
  369. bool: this._bool()
  370. });
  371. return this;
  372. },
  373. // Adds a `or where in` clause to the query.
  374. orWhereIn: function orWhereIn(column, values) {
  375. return this._bool('or').whereIn(column, values);
  376. },
  377. // Adds a `where not in` clause to the query.
  378. whereNotIn: function whereNotIn(column, values) {
  379. return this._not(true).whereIn(column, values);
  380. },
  381. // Adds a `or where not in` clause to the query.
  382. orWhereNotIn: function orWhereNotIn(column, values) {
  383. return this._bool('or')._not(true).whereIn(column, values);
  384. },
  385. // Adds a `where null` clause to the query.
  386. whereNull: function whereNull(column) {
  387. this._statements.push({
  388. grouping: 'where',
  389. type: 'whereNull',
  390. column: column,
  391. not: this._not(),
  392. bool: this._bool()
  393. });
  394. return this;
  395. },
  396. // Adds a `or where null` clause to the query.
  397. orWhereNull: function orWhereNull(column) {
  398. return this._bool('or').whereNull(column);
  399. },
  400. // Adds a `where not null` clause to the query.
  401. whereNotNull: function whereNotNull(column) {
  402. return this._not(true).whereNull(column);
  403. },
  404. // Adds a `or where not null` clause to the query.
  405. orWhereNotNull: function orWhereNotNull(column) {
  406. return this._bool('or').whereNotNull(column);
  407. },
  408. // Adds a `where between` clause to the query.
  409. whereBetween: function whereBetween(column, values) {
  410. (0, _assert2.default)(Array.isArray(values), 'The second argument to whereBetween must be an array.');
  411. (0, _assert2.default)(values.length === 2, 'You must specify 2 values for the whereBetween clause');
  412. this._statements.push({
  413. grouping: 'where',
  414. type: 'whereBetween',
  415. column: column,
  416. value: values,
  417. not: this._not(),
  418. bool: this._bool()
  419. });
  420. return this;
  421. },
  422. // Adds a `where not between` clause to the query.
  423. whereNotBetween: function whereNotBetween(column, values) {
  424. return this._not(true).whereBetween(column, values);
  425. },
  426. // Adds a `or where between` clause to the query.
  427. orWhereBetween: function orWhereBetween(column, values) {
  428. return this._bool('or').whereBetween(column, values);
  429. },
  430. // Adds a `or where not between` clause to the query.
  431. orWhereNotBetween: function orWhereNotBetween(column, values) {
  432. return this._bool('or').whereNotBetween(column, values);
  433. },
  434. // Adds a `group by` clause to the query.
  435. groupBy: function groupBy(item) {
  436. if (item instanceof _raw2.default) {
  437. return this.groupByRaw.apply(this, arguments);
  438. }
  439. this._statements.push({
  440. grouping: 'group',
  441. type: 'groupByBasic',
  442. value: helpers.normalizeArr.apply(null, arguments)
  443. });
  444. return this;
  445. },
  446. // Adds a raw `group by` clause to the query.
  447. groupByRaw: function groupByRaw(sql, bindings) {
  448. var raw = sql instanceof _raw2.default ? sql : this.client.raw(sql, bindings);
  449. this._statements.push({
  450. grouping: 'group',
  451. type: 'groupByRaw',
  452. value: raw
  453. });
  454. return this;
  455. },
  456. // Adds a `order by` clause to the query.
  457. orderBy: function orderBy(column, direction) {
  458. this._statements.push({
  459. grouping: 'order',
  460. type: 'orderByBasic',
  461. value: column,
  462. direction: direction
  463. });
  464. return this;
  465. },
  466. // Add a raw `order by` clause to the query.
  467. orderByRaw: function orderByRaw(sql, bindings) {
  468. var raw = sql instanceof _raw2.default ? sql : this.client.raw(sql, bindings);
  469. this._statements.push({
  470. grouping: 'order',
  471. type: 'orderByRaw',
  472. value: raw
  473. });
  474. return this;
  475. },
  476. // Add a union statement to the query.
  477. union: function union(callbacks, wrap) {
  478. if (arguments.length === 1 || arguments.length === 2 && (0, _isBoolean3.default)(wrap)) {
  479. if (!Array.isArray(callbacks)) {
  480. callbacks = [callbacks];
  481. }
  482. for (var i = 0, l = callbacks.length; i < l; i++) {
  483. this._statements.push({
  484. grouping: 'union',
  485. clause: 'union',
  486. value: callbacks[i],
  487. wrap: wrap || false
  488. });
  489. }
  490. } else {
  491. callbacks = (0, _toArray3.default)(arguments).slice(0, arguments.length - 1);
  492. wrap = arguments[arguments.length - 1];
  493. if (!(0, _isBoolean3.default)(wrap)) {
  494. callbacks.push(wrap);
  495. wrap = false;
  496. }
  497. this.union(callbacks, wrap);
  498. }
  499. return this;
  500. },
  501. // Adds a union all statement to the query.
  502. unionAll: function unionAll(callback, wrap) {
  503. this._statements.push({
  504. grouping: 'union',
  505. clause: 'union all',
  506. value: callback,
  507. wrap: wrap || false
  508. });
  509. return this;
  510. },
  511. // Adds a `having` clause to the query.
  512. having: function having(column, operator, value) {
  513. if (column instanceof _raw2.default && arguments.length === 1) {
  514. return this.havingRaw(column);
  515. }
  516. // Check if the column is a function, in which case it's
  517. // a having statement wrapped in parens.
  518. if (typeof column === 'function') {
  519. return this.havingWrapped(column);
  520. }
  521. this._statements.push({
  522. grouping: 'having',
  523. type: 'havingBasic',
  524. column: column,
  525. operator: operator,
  526. value: value,
  527. bool: this._bool(),
  528. not: this._not()
  529. });
  530. return this;
  531. },
  532. orHaving: function orHaving() {
  533. this._bool('or');
  534. var obj = arguments[0];
  535. if ((0, _isObject3.default)(obj) && !(0, _isFunction3.default)(obj) && !(obj instanceof _raw2.default)) {
  536. return this.havingWrapped(function () {
  537. for (var key in obj) {
  538. this.andHaving(key, obj[key]);
  539. }
  540. });
  541. }
  542. return this.having.apply(this, arguments);
  543. },
  544. // Helper for compiling any advanced `having` queries.
  545. havingWrapped: function havingWrapped(callback) {
  546. this._statements.push({
  547. grouping: 'having',
  548. type: 'havingWrapped',
  549. value: callback,
  550. bool: this._bool(),
  551. not: this._not()
  552. });
  553. return this;
  554. },
  555. havingNull: function havingNull(column) {
  556. this._statements.push({
  557. grouping: 'having',
  558. type: 'havingNull',
  559. column: column,
  560. not: this._not(),
  561. bool: this._bool()
  562. });
  563. return this;
  564. },
  565. orHavingNull: function orHavingNull(callback) {
  566. return this._bool('or').havingNull(callback);
  567. },
  568. havingNotNull: function havingNotNull(callback) {
  569. return this._not(true).havingNull(callback);
  570. },
  571. orHavingNotNull: function orHavingNotNull(callback) {
  572. return this._not(true)._bool('or').havingNull(callback);
  573. },
  574. havingExists: function havingExists(callback) {
  575. this._statements.push({
  576. grouping: 'having',
  577. type: 'havingExists',
  578. value: callback,
  579. not: this._not(),
  580. bool: this._bool()
  581. });
  582. return this;
  583. },
  584. orHavingExists: function orHavingExists(callback) {
  585. return this._bool('or').havingExists(callback);
  586. },
  587. havingNotExists: function havingNotExists(callback) {
  588. return this._not(true).havingExists(callback);
  589. },
  590. orHavingNotExists: function orHavingNotExists(callback) {
  591. return this._not(true)._bool('or').havingExists(callback);
  592. },
  593. havingBetween: function havingBetween(column, values) {
  594. (0, _assert2.default)(Array.isArray(values), 'The second argument to havingBetween must be an array.');
  595. (0, _assert2.default)(values.length === 2, 'You must specify 2 values for the havingBetween clause');
  596. this._statements.push({
  597. grouping: 'having',
  598. type: 'havingBetween',
  599. column: column,
  600. value: values,
  601. not: this._not(),
  602. bool: this._bool()
  603. });
  604. return this;
  605. },
  606. orHavingBetween: function orHavingBetween(column, values) {
  607. return this._bool('or').havingBetween(column, values);
  608. },
  609. havingNotBetween: function havingNotBetween(column, values) {
  610. return this._not(true).havingBetween(column, values);
  611. },
  612. orHavingNotBetween: function orHavingNotBetween(column, values) {
  613. return this._not(true)._bool('or').havingBetween(column, values);
  614. },
  615. havingIn: function havingIn(column, values) {
  616. if (Array.isArray(values) && (0, _isEmpty3.default)(values)) return this.where(this._not());
  617. this._statements.push({
  618. grouping: 'having',
  619. type: 'havingIn',
  620. column: column,
  621. value: values,
  622. not: this._not(),
  623. bool: this._bool()
  624. });
  625. return this;
  626. },
  627. // Adds a `or where in` clause to the query.
  628. orHavingIn: function orHavingIn(column, values) {
  629. return this._bool('or').havingIn(column, values);
  630. },
  631. // Adds a `where not in` clause to the query.
  632. havingNotIn: function havingNotIn(column, values) {
  633. return this._not(true).havingIn(column, values);
  634. },
  635. // Adds a `or where not in` clause to the query.
  636. orHavingNotIn: function orHavingNotIn(column, values) {
  637. return this._bool('or')._not(true).havingIn(column, values);
  638. },
  639. // Adds a raw `having` clause to the query.
  640. havingRaw: function havingRaw(sql, bindings) {
  641. var raw = sql instanceof _raw2.default ? sql : this.client.raw(sql, bindings);
  642. this._statements.push({
  643. grouping: 'having',
  644. type: 'havingRaw',
  645. value: raw,
  646. bool: this._bool(),
  647. not: this._not()
  648. });
  649. return this;
  650. },
  651. orHavingRaw: function orHavingRaw(sql, bindings) {
  652. return this._bool('or').havingRaw(sql, bindings);
  653. },
  654. // Only allow a single "offset" to be set for the current query.
  655. offset: function offset(value) {
  656. this._single.offset = value;
  657. return this;
  658. },
  659. // Only allow a single "limit" to be set for the current query.
  660. limit: function limit(value) {
  661. var val = parseInt(value, 10);
  662. if (isNaN(val)) {
  663. helpers.warn('A valid integer must be provided to limit');
  664. } else {
  665. this._single.limit = val;
  666. }
  667. return this;
  668. },
  669. // Retrieve the "count" result of the query.
  670. count: function count(column) {
  671. return this._aggregate('count', column || '*');
  672. },
  673. // Retrieve the minimum value of a given column.
  674. min: function min(column) {
  675. return this._aggregate('min', column);
  676. },
  677. // Retrieve the maximum value of a given column.
  678. max: function max(column) {
  679. return this._aggregate('max', column);
  680. },
  681. // Retrieve the sum of the values of a given column.
  682. sum: function sum(column) {
  683. return this._aggregate('sum', column);
  684. },
  685. // Retrieve the average of the values of a given column.
  686. avg: function avg(column) {
  687. return this._aggregate('avg', column);
  688. },
  689. // Retrieve the "count" of the distinct results of the query.
  690. countDistinct: function countDistinct(column) {
  691. return this._aggregate('count', column || '*', true);
  692. },
  693. // Retrieve the sum of the distinct values of a given column.
  694. sumDistinct: function sumDistinct(column) {
  695. return this._aggregate('sum', column, true);
  696. },
  697. // Retrieve the vg of the distinct results of the query.
  698. avgDistinct: function avgDistinct(column) {
  699. return this._aggregate('avg', column, true);
  700. },
  701. // Increments a column's value by the specified amount.
  702. increment: function increment(column, amount) {
  703. return this._counter(column, amount);
  704. },
  705. // Decrements a column's value by the specified amount.
  706. decrement: function decrement(column, amount) {
  707. return this._counter(column, amount, '-');
  708. },
  709. // Sets the values for a `select` query, informing that only the first
  710. // row should be returned (limit 1).
  711. first: function first() {
  712. var args = new Array(arguments.length);
  713. for (var i = 0; i < args.length; i++) {
  714. args[i] = arguments[i];
  715. }
  716. this.select.apply(this, args);
  717. this._method = 'first';
  718. this.limit(1);
  719. return this;
  720. },
  721. // Pluck a column from a query.
  722. pluck: function pluck(column) {
  723. this._method = 'pluck';
  724. this._single.pluck = column;
  725. this._statements.push({
  726. grouping: 'columns',
  727. type: 'pluck',
  728. value: column
  729. });
  730. return this;
  731. },
  732. // Insert & Update
  733. // ------
  734. // Sets the values for an `insert` query.
  735. insert: function insert(values, returning) {
  736. this._method = 'insert';
  737. if (!(0, _isEmpty3.default)(returning)) this.returning(returning);
  738. this._single.insert = values;
  739. return this;
  740. },
  741. // Sets the values for an `update`, allowing for both
  742. // `.update(key, value, [returning])` and `.update(obj, [returning])` syntaxes.
  743. update: function update(values, returning) {
  744. var ret = void 0;
  745. var obj = this._single.update || {};
  746. this._method = 'update';
  747. if ((0, _isString3.default)(values)) {
  748. obj[values] = returning;
  749. if (arguments.length > 2) {
  750. ret = arguments[2];
  751. }
  752. } else {
  753. var keys = (0, _keys2.default)(values);
  754. if (this._single.update) {
  755. helpers.warn('Update called multiple times with objects.');
  756. }
  757. var i = -1;
  758. while (++i < keys.length) {
  759. obj[keys[i]] = values[keys[i]];
  760. }
  761. ret = arguments[1];
  762. }
  763. if (!(0, _isEmpty3.default)(ret)) this.returning(ret);
  764. this._single.update = obj;
  765. return this;
  766. },
  767. // Sets the returning value for the query.
  768. returning: function returning(_returning) {
  769. this._single.returning = _returning;
  770. return this;
  771. },
  772. // Delete
  773. // ------
  774. // Executes a delete statement on the query;
  775. delete: function _delete(ret) {
  776. this._method = 'del';
  777. if (!(0, _isEmpty3.default)(ret)) this.returning(ret);
  778. return this;
  779. },
  780. // Truncates a table, ends the query chain.
  781. truncate: function truncate(tableName) {
  782. this._method = 'truncate';
  783. if (tableName) {
  784. this._single.table = tableName;
  785. }
  786. return this;
  787. },
  788. // Retrieves columns for the table specified by `knex(tableName)`
  789. columnInfo: function columnInfo(column) {
  790. this._method = 'columnInfo';
  791. this._single.columnInfo = column;
  792. return this;
  793. },
  794. // Set a lock for update constraint.
  795. forUpdate: function forUpdate() {
  796. this._single.lock = 'forUpdate';
  797. return this;
  798. },
  799. // Set a lock for share constraint.
  800. forShare: function forShare() {
  801. this._single.lock = 'forShare';
  802. return this;
  803. },
  804. // Takes a JS object of methods to call and calls them
  805. fromJS: function fromJS(obj) {
  806. var _this = this;
  807. (0, _each3.default)(obj, function (val, key) {
  808. if (typeof _this[key] !== 'function') {
  809. helpers.warn('Knex Error: unknown key ' + key);
  810. }
  811. if (Array.isArray(val)) {
  812. _this[key].apply(_this, val);
  813. } else {
  814. _this[key](val);
  815. }
  816. });
  817. return this;
  818. },
  819. // Passes query to provided callback function, useful for e.g. composing
  820. // domain-specific helpers
  821. modify: function modify(callback) {
  822. callback.apply(this, [this].concat((0, _tail3.default)(arguments)));
  823. return this;
  824. },
  825. // ----------------------------------------------------------------------
  826. // Helper for the incrementing/decrementing queries.
  827. _counter: function _counter(column, amount, symbol) {
  828. var amt = parseInt(amount, 10);
  829. if (isNaN(amt)) amt = 1;
  830. this._method = 'counter';
  831. this._single.counter = {
  832. column: column,
  833. amount: amt,
  834. symbol: symbol || '+'
  835. };
  836. return this;
  837. },
  838. // Helper to get or set the "boolFlag" value.
  839. _bool: function _bool(val) {
  840. if (arguments.length === 1) {
  841. this._boolFlag = val;
  842. return this;
  843. }
  844. var ret = this._boolFlag;
  845. this._boolFlag = 'and';
  846. return ret;
  847. },
  848. // Helper to get or set the "notFlag" value.
  849. _not: function _not(val) {
  850. if (arguments.length === 1) {
  851. this._notFlag = val;
  852. return this;
  853. }
  854. var ret = this._notFlag;
  855. this._notFlag = false;
  856. return ret;
  857. },
  858. // Helper to get or set the "joinFlag" value.
  859. _joinType: function _joinType(val) {
  860. if (arguments.length === 1) {
  861. this._joinFlag = val;
  862. return this;
  863. }
  864. var ret = this._joinFlag || 'inner';
  865. this._joinFlag = 'inner';
  866. return ret;
  867. },
  868. // Helper for compiling any aggregate queries.
  869. _aggregate: function _aggregate(method, column, aggregateDistinct) {
  870. this._statements.push({
  871. grouping: 'columns',
  872. type: 'aggregate',
  873. method: method,
  874. value: column,
  875. aggregateDistinct: aggregateDistinct || false
  876. });
  877. return this;
  878. }
  879. });
  880. Object.defineProperty(Builder.prototype, 'or', {
  881. get: function get() {
  882. return this._bool('or');
  883. }
  884. });
  885. Object.defineProperty(Builder.prototype, 'not', {
  886. get: function get() {
  887. return this._not(true);
  888. }
  889. });
  890. Builder.prototype.select = Builder.prototype.columns;
  891. Builder.prototype.column = Builder.prototype.columns;
  892. Builder.prototype.andWhereNot = Builder.prototype.whereNot;
  893. Builder.prototype.andWhere = Builder.prototype.where;
  894. Builder.prototype.andWhereRaw = Builder.prototype.whereRaw;
  895. Builder.prototype.andWhereBetween = Builder.prototype.whereBetween;
  896. Builder.prototype.andWhereNotBetween = Builder.prototype.whereNotBetween;
  897. Builder.prototype.andHaving = Builder.prototype.having;
  898. Builder.prototype.andHavingIn = Builder.prototype.havingIn;
  899. Builder.prototype.andHavingNotIn = Builder.prototype.havingNotIn;
  900. Builder.prototype.andHavingNull = Builder.prototype.havingNull;
  901. Builder.prototype.andHavingNotNull = Builder.prototype.havingNotNull;
  902. Builder.prototype.andHavingExists = Builder.prototype.havingExists;
  903. Builder.prototype.andHavingNotExists = Builder.prototype.havingNotExists;
  904. Builder.prototype.andHavingBetween = Builder.prototype.havingBetween;
  905. Builder.prototype.andHavingNotBetween = Builder.prototype.havingNotBetween;
  906. Builder.prototype.from = Builder.prototype.table;
  907. Builder.prototype.into = Builder.prototype.table;
  908. Builder.prototype.del = Builder.prototype.delete;
  909. // Attach all of the top level promise methods that should be chainable.
  910. require('../interface')(Builder);
  911. exports.default = Builder;
  912. module.exports = exports['default'];