builder.js 32 KB

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