squel-basic.js 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026
  1. ;(function(root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. define([], factory);
  4. } else if (typeof exports === 'object') {
  5. module.exports = factory();
  6. } else {
  7. root.squel = factory();
  8. }
  9. }(this, function() {
  10. 'use strict';
  11. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  12. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  14. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  15. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  16. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  17. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18. // append to string if non-empty
  19. function _pad(str, pad) {
  20. return str.length ? str + pad : str;
  21. }
  22. // Extend given object's with other objects' properties, overriding existing ones if necessary
  23. function _extend(dst) {
  24. for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  25. sources[_key - 1] = arguments[_key];
  26. }
  27. if (dst && sources) {
  28. var _iteratorNormalCompletion = true;
  29. var _didIteratorError = false;
  30. var _iteratorError = undefined;
  31. try {
  32. var _loop = function _loop() {
  33. var src = _step.value;
  34. if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) === 'object') {
  35. Object.getOwnPropertyNames(src).forEach(function (key) {
  36. dst[key] = src[key];
  37. });
  38. }
  39. };
  40. for (var _iterator = sources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  41. _loop();
  42. }
  43. } catch (err) {
  44. _didIteratorError = true;
  45. _iteratorError = err;
  46. } finally {
  47. try {
  48. if (!_iteratorNormalCompletion && _iterator.return) {
  49. _iterator.return();
  50. }
  51. } finally {
  52. if (_didIteratorError) {
  53. throw _iteratorError;
  54. }
  55. }
  56. }
  57. }
  58. return dst;
  59. };
  60. // get whether object is a plain object
  61. function _isPlainObject(obj) {
  62. return obj && obj.constructor.prototype === Object.prototype;
  63. };
  64. // get whether object is an array
  65. function _isArray(obj) {
  66. return obj && obj.constructor.prototype === Array.prototype;
  67. };
  68. // get class name of given object
  69. function _getObjectClassName(obj) {
  70. if (obj && obj.constructor && obj.constructor.toString) {
  71. var arr = obj.constructor.toString().match(/function\s*(\w+)/);
  72. if (arr && 2 === arr.length) {
  73. return arr[1];
  74. }
  75. }
  76. }
  77. // clone given item
  78. function _clone(src) {
  79. if (!src) {
  80. return src;
  81. }
  82. if (typeof src.clone === 'function') {
  83. return src.clone();
  84. } else if (_isPlainObject(src) || _isArray(src)) {
  85. var _ret2 = function () {
  86. var ret = new src.constructor();
  87. Object.getOwnPropertyNames(src).forEach(function (key) {
  88. if (typeof src[key] !== 'function') {
  89. ret[key] = _clone(src[key]);
  90. }
  91. });
  92. return {
  93. v: ret
  94. };
  95. }();
  96. if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
  97. } else {
  98. return JSON.parse(JSON.stringify(src));
  99. }
  100. };
  101. /**
  102. * Register a value type handler
  103. *
  104. * Note: this will override any existing handler registered for this value type.
  105. */
  106. function _registerValueHandler(handlers, type, handler) {
  107. var typeofType = typeof type === 'undefined' ? 'undefined' : _typeof(type);
  108. if (typeofType !== 'function' && typeofType !== 'string') {
  109. throw new Error("type must be a class constructor or string");
  110. }
  111. if (typeof handler !== 'function') {
  112. throw new Error("handler must be a function");
  113. }
  114. var _iteratorNormalCompletion2 = true;
  115. var _didIteratorError2 = false;
  116. var _iteratorError2 = undefined;
  117. try {
  118. for (var _iterator2 = handlers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  119. var typeHandler = _step2.value;
  120. if (typeHandler.type === type) {
  121. typeHandler.handler = handler;
  122. return;
  123. }
  124. }
  125. } catch (err) {
  126. _didIteratorError2 = true;
  127. _iteratorError2 = err;
  128. } finally {
  129. try {
  130. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  131. _iterator2.return();
  132. }
  133. } finally {
  134. if (_didIteratorError2) {
  135. throw _iteratorError2;
  136. }
  137. }
  138. }
  139. handlers.push({
  140. type: type,
  141. handler: handler
  142. });
  143. };
  144. /**
  145. * Get value type handler for given type
  146. */
  147. function getValueHandler(value) {
  148. for (var _len2 = arguments.length, handlerLists = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  149. handlerLists[_key2 - 1] = arguments[_key2];
  150. }
  151. var _iteratorNormalCompletion3 = true;
  152. var _didIteratorError3 = false;
  153. var _iteratorError3 = undefined;
  154. try {
  155. for (var _iterator3 = handlerLists[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  156. var handlers = _step3.value;
  157. var _iteratorNormalCompletion4 = true;
  158. var _didIteratorError4 = false;
  159. var _iteratorError4 = undefined;
  160. try {
  161. for (var _iterator4 = handlers[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  162. var typeHandler = _step4.value;
  163. // if type is a string then use `typeof` or else use `instanceof`
  164. if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === typeHandler.type || typeof typeHandler.type !== 'string' && value instanceof typeHandler.type) {
  165. return typeHandler.handler;
  166. }
  167. }
  168. } catch (err) {
  169. _didIteratorError4 = true;
  170. _iteratorError4 = err;
  171. } finally {
  172. try {
  173. if (!_iteratorNormalCompletion4 && _iterator4.return) {
  174. _iterator4.return();
  175. }
  176. } finally {
  177. if (_didIteratorError4) {
  178. throw _iteratorError4;
  179. }
  180. }
  181. }
  182. }
  183. } catch (err) {
  184. _didIteratorError3 = true;
  185. _iteratorError3 = err;
  186. } finally {
  187. try {
  188. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  189. _iterator3.return();
  190. }
  191. } finally {
  192. if (_didIteratorError3) {
  193. throw _iteratorError3;
  194. }
  195. }
  196. }
  197. };
  198. /**
  199. * Build base squel classes and methods
  200. */
  201. function _buildSquel() {
  202. var flavour = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
  203. var cls = {
  204. _getObjectClassName: _getObjectClassName
  205. };
  206. // default query builder options
  207. cls.DefaultQueryBuilderOptions = {
  208. // If true then table names will be rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
  209. autoQuoteTableNames: false,
  210. // If true then field names will rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
  211. autoQuoteFieldNames: false,
  212. // If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
  213. autoQuoteAliasNames: true,
  214. // If true then table alias names will rendered after AS keyword.
  215. useAsForTableAliasNames: false,
  216. // The quote character used for when quoting table and field names
  217. nameQuoteCharacter: '`',
  218. // The quote character used for when quoting table alias names
  219. tableAliasQuoteCharacter: '`',
  220. // The quote character used for when quoting table alias names
  221. fieldAliasQuoteCharacter: '"',
  222. // Custom value handlers where key is the value type and the value is the handler function
  223. valueHandlers: [],
  224. // Character used to represent a parameter value
  225. parameterCharacter: '?',
  226. // Numbered parameters returned from toParam() as $1, $2, etc.
  227. numberedParameters: false,
  228. // Numbered parameters prefix character(s)
  229. numberedParametersPrefix: '$',
  230. // Numbered parameters start at this number.
  231. numberedParametersStartAt: 1,
  232. // If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
  233. replaceSingleQuotes: false,
  234. // The string to replace single quotes with in query strings
  235. singleQuoteReplacement: '\'\'',
  236. // String used to join individual blocks in a query when it's stringified
  237. separator: ' ',
  238. // Function for formatting string values prior to insertion into query string
  239. stringFormatter: null
  240. };
  241. // Global custom value handlers for all instances of builder
  242. cls.globalValueHandlers = [];
  243. /*
  244. # ---------------------------------------------------------------------------------------------------------
  245. # ---------------------------------------------------------------------------------------------------------
  246. # Custom value types
  247. # ---------------------------------------------------------------------------------------------------------
  248. # ---------------------------------------------------------------------------------------------------------
  249. */
  250. // Register a new value handler
  251. cls.registerValueHandler = function (type, handler) {
  252. _registerValueHandler(cls.globalValueHandlers, type, handler);
  253. };
  254. /*
  255. # ---------------------------------------------------------------------------------------------------------
  256. # ---------------------------------------------------------------------------------------------------------
  257. # Base classes
  258. # ---------------------------------------------------------------------------------------------------------
  259. # ---------------------------------------------------------------------------------------------------------
  260. */
  261. // Base class for cloneable builders
  262. cls.Cloneable = function () {
  263. function _class() {
  264. _classCallCheck(this, _class);
  265. }
  266. _createClass(_class, [{
  267. key: 'clone',
  268. /**
  269. * Clone this builder
  270. */
  271. value: function clone() {
  272. var newInstance = new this.constructor();
  273. return _extend(newInstance, _clone(_extend({}, this)));
  274. }
  275. }]);
  276. return _class;
  277. }();
  278. // Base class for all builders
  279. cls.BaseBuilder = function (_cls$Cloneable) {
  280. _inherits(_class2, _cls$Cloneable);
  281. /**
  282. * Constructor.
  283. * this.param {Object} options Overriding one or more of `cls.DefaultQueryBuilderOptions`.
  284. */
  285. function _class2(options) {
  286. _classCallCheck(this, _class2);
  287. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class2).call(this));
  288. var defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions));
  289. _this.options = _extend({}, defaults, options);
  290. return _this;
  291. }
  292. /**
  293. * Register a custom value handler for this builder instance.
  294. *
  295. * Note: this will override any globally registered handler for this value type.
  296. */
  297. _createClass(_class2, [{
  298. key: 'registerValueHandler',
  299. value: function registerValueHandler(type, handler) {
  300. _registerValueHandler(this.options.valueHandlers, type, handler);
  301. return this;
  302. }
  303. /**
  304. * Sanitize given expression.
  305. */
  306. }, {
  307. key: '_sanitizeExpression',
  308. value: function _sanitizeExpression(expr) {
  309. // If it's not an Expression builder instance
  310. if (!(expr instanceof cls.Expression)) {
  311. // It must then be a string
  312. if (typeof expr !== "string") {
  313. throw new Error("expression must be a string or Expression instance");
  314. }
  315. }
  316. return expr;
  317. }
  318. /**
  319. * Sanitize the given name.
  320. *
  321. * The 'type' parameter is used to construct a meaningful error message in case validation fails.
  322. */
  323. }, {
  324. key: '_sanitizeName',
  325. value: function _sanitizeName(value, type) {
  326. if (typeof value !== "string") {
  327. throw new Error(type + ' must be a string');
  328. }
  329. return value;
  330. }
  331. }, {
  332. key: '_sanitizeField',
  333. value: function _sanitizeField(item) {
  334. if (!(item instanceof cls.BaseBuilder)) {
  335. item = this._sanitizeName(item, "field name");
  336. }
  337. return item;
  338. }
  339. }, {
  340. key: '_sanitizeBaseBuilder',
  341. value: function _sanitizeBaseBuilder(item) {
  342. if (item instanceof cls.BaseBuilder) {
  343. return item;
  344. }
  345. throw new Error("must be a BaseBuilder instance");
  346. }
  347. }, {
  348. key: '_sanitizeTable',
  349. value: function _sanitizeTable(item) {
  350. if (typeof item !== "string") {
  351. try {
  352. item = this._sanitizeBaseBuilder(item);
  353. } catch (e) {
  354. throw new Error("table name must be a string or a query builder");
  355. }
  356. } else {
  357. item = this._sanitizeName(item, 'table');
  358. }
  359. return item;
  360. }
  361. }, {
  362. key: '_sanitizeTableAlias',
  363. value: function _sanitizeTableAlias(item) {
  364. return this._sanitizeName(item, "table alias");
  365. }
  366. }, {
  367. key: '_sanitizeFieldAlias',
  368. value: function _sanitizeFieldAlias(item) {
  369. return this._sanitizeName(item, "field alias");
  370. }
  371. // Sanitize the given limit/offset value.
  372. }, {
  373. key: '_sanitizeLimitOffset',
  374. value: function _sanitizeLimitOffset(value) {
  375. value = parseInt(value);
  376. if (0 > value || isNaN(value)) {
  377. throw new Error("limit/offset must be >= 0");
  378. }
  379. return value;
  380. }
  381. // Santize the given field value
  382. }, {
  383. key: '_sanitizeValue',
  384. value: function _sanitizeValue(item) {
  385. var itemType = typeof item === 'undefined' ? 'undefined' : _typeof(item);
  386. if (null === item) {
  387. // null is allowed
  388. } else if ("string" === itemType || "number" === itemType || "boolean" === itemType) {
  389. // primitives are allowed
  390. } else if (item instanceof cls.BaseBuilder) {
  391. // Builders allowed
  392. } else {
  393. var typeIsValid = !!getValueHandler(item, this.options.valueHandlers, cls.globalValueHandlers);
  394. if (!typeIsValid) {
  395. throw new Error("field value must be a string, number, boolean, null or one of the registered custom value types");
  396. }
  397. }
  398. return item;
  399. }
  400. // Escape a string value, e.g. escape quotes and other characters within it.
  401. }, {
  402. key: '_escapeValue',
  403. value: function _escapeValue(value) {
  404. return !this.options.replaceSingleQuotes ? value : value.replace(/\'/g, this.options.singleQuoteReplacement);
  405. }
  406. }, {
  407. key: '_formatTableName',
  408. value: function _formatTableName(item) {
  409. if (this.options.autoQuoteTableNames) {
  410. var quoteChar = this.options.nameQuoteCharacter;
  411. item = '' + quoteChar + item + quoteChar;
  412. }
  413. return item;
  414. }
  415. }, {
  416. key: '_formatFieldAlias',
  417. value: function _formatFieldAlias(item) {
  418. if (this.options.autoQuoteAliasNames) {
  419. var quoteChar = this.options.fieldAliasQuoteCharacter;
  420. item = '' + quoteChar + item + quoteChar;
  421. }
  422. return item;
  423. }
  424. }, {
  425. key: '_formatTableAlias',
  426. value: function _formatTableAlias(item) {
  427. if (this.options.autoQuoteAliasNames) {
  428. var quoteChar = this.options.tableAliasQuoteCharacter;
  429. item = '' + quoteChar + item + quoteChar;
  430. }
  431. return this.options.useAsForTableAliasNames ? 'AS ' + item : item;
  432. }
  433. }, {
  434. key: '_formatFieldName',
  435. value: function _formatFieldName(item) {
  436. var _this2 = this;
  437. var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  438. if (this.options.autoQuoteFieldNames) {
  439. (function () {
  440. var quoteChar = _this2.options.nameQuoteCharacter;
  441. if (formattingOptions.ignorePeriodsForFieldNameQuotes) {
  442. // a.b.c -> `a.b.c`
  443. item = '' + quoteChar + item + quoteChar;
  444. } else {
  445. // a.b.c -> `a`.`b`.`c`
  446. item = item.split('.').map(function (v) {
  447. // treat '*' as special case (#79)
  448. return '*' === v ? v : '' + quoteChar + v + quoteChar;
  449. }).join('.');
  450. }
  451. })();
  452. }
  453. return item;
  454. }
  455. // Format the given custom value
  456. }, {
  457. key: '_formatCustomValue',
  458. value: function _formatCustomValue(value) {
  459. var asParam = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  460. // user defined custom handlers takes precedence
  461. var customHandler = getValueHandler(value, this.options.valueHandlers, cls.globalValueHandlers);
  462. // use the custom handler if available
  463. if (customHandler) {
  464. value = customHandler(value, asParam);
  465. }
  466. return value;
  467. }
  468. /**
  469. * Format given value for inclusion into parameter values array.
  470. */
  471. }, {
  472. key: '_formatValueForParamArray',
  473. value: function _formatValueForParamArray(value) {
  474. var _this3 = this;
  475. if (_isArray(value)) {
  476. return value.map(function (v) {
  477. return _this3._formatValueForParamArray(v);
  478. });
  479. } else {
  480. return this._formatCustomValue(value, true);
  481. }
  482. }
  483. /**
  484. * Format the given field value for inclusion into the query string
  485. */
  486. }, {
  487. key: '_formatValueForQueryString',
  488. value: function _formatValueForQueryString(value) {
  489. var _this4 = this;
  490. var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  491. var customFormattedValue = this._formatCustomValue(value);
  492. // if formatting took place then return it directly
  493. if (customFormattedValue !== value) {
  494. return this._applyNestingFormatting(customFormattedValue);
  495. }
  496. // if it's an array then format each element separately
  497. if (_isArray(value)) {
  498. value = value.map(function (v) {
  499. return _this4._formatValueForQueryString(v);
  500. });
  501. value = this._applyNestingFormatting(value.join(', '));
  502. } else {
  503. var typeofValue = typeof value === 'undefined' ? 'undefined' : _typeof(value);
  504. if (null === value) {
  505. value = "NULL";
  506. } else if (typeofValue === "boolean") {
  507. value = value ? "TRUE" : "FALSE";
  508. } else if (value instanceof cls.BaseBuilder) {
  509. value = this._applyNestingFormatting(value.toString());
  510. } else if (typeofValue !== "number") {
  511. // if it's a string and we have custom string formatting turned on then use that
  512. if ('string' === typeofValue && this.options.stringFormatter) {
  513. return this.options.stringFormatter(value);
  514. }
  515. if (formattingOptions.dontQuote) {
  516. value = '' + value;
  517. } else {
  518. var escapedValue = this._escapeValue(value);
  519. value = '\'' + escapedValue + '\'';
  520. }
  521. }
  522. }
  523. return value;
  524. }
  525. }, {
  526. key: '_applyNestingFormatting',
  527. value: function _applyNestingFormatting(str) {
  528. var nesting = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  529. if (str && typeof str === 'string' && nesting) {
  530. // don't want to apply twice
  531. if ('(' !== str.charAt(0) || ')' !== str.charAt(str.length - 1)) {
  532. return '(' + str + ')';
  533. }
  534. }
  535. return str;
  536. }
  537. /**
  538. * Build given string and its corresponding parameter values into
  539. * output.
  540. *
  541. * @param {String} str
  542. * @param {Array} values
  543. * @param {Object} [options] Additional options.
  544. * @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
  545. * @param {Boolean} [options.nested] Whether this expression is nested within another.
  546. * @param {Boolean} [options.formattingOptions] Formatting options for values in query string.
  547. * @return {Object}
  548. */
  549. }, {
  550. key: '_buildString',
  551. value: function _buildString(str, values) {
  552. var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  553. var nested = options.nested;
  554. var buildParameterized = options.buildParameterized;
  555. var formattingOptions = options.formattingOptions;
  556. values = values || [];
  557. str = str || '';
  558. var formattedStr = '',
  559. curValue = -1,
  560. formattedValues = [];
  561. var paramChar = this.options.parameterCharacter;
  562. var idx = 0;
  563. while (str.length > idx) {
  564. // param char?
  565. if (str.substr(idx, paramChar.length) === paramChar) {
  566. var value = values[++curValue];
  567. if (buildParameterized) {
  568. if (value instanceof cls.BaseBuilder) {
  569. var ret = value._toParamString({
  570. buildParameterized: buildParameterized,
  571. nested: true
  572. });
  573. formattedStr += ret.text;
  574. formattedValues.push.apply(formattedValues, _toConsumableArray(ret.values));
  575. } else {
  576. value = this._formatValueForParamArray(value);
  577. if (_isArray(value)) {
  578. // Array(6) -> "(??, ??, ??, ??, ??, ??)"
  579. var tmpStr = value.map(function () {
  580. return paramChar;
  581. }).join(', ');
  582. formattedStr += '(' + tmpStr + ')';
  583. formattedValues.push.apply(formattedValues, _toConsumableArray(value));
  584. } else {
  585. formattedStr += paramChar;
  586. formattedValues.push(value);
  587. }
  588. }
  589. } else {
  590. formattedStr += this._formatValueForQueryString(value, formattingOptions);
  591. }
  592. idx += paramChar.length;
  593. } else {
  594. formattedStr += str.charAt(idx);
  595. idx++;
  596. }
  597. }
  598. return {
  599. text: this._applyNestingFormatting(formattedStr, !!nested),
  600. values: formattedValues
  601. };
  602. }
  603. /**
  604. * Build all given strings and their corresponding parameter values into
  605. * output.
  606. *
  607. * @param {Array} strings
  608. * @param {Array} strValues array of value arrays corresponding to each string.
  609. * @param {Object} [options] Additional options.
  610. * @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
  611. * @param {Boolean} [options.nested] Whether this expression is nested within another.
  612. * @return {Object}
  613. */
  614. }, {
  615. key: '_buildManyStrings',
  616. value: function _buildManyStrings(strings, strValues) {
  617. var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  618. var totalStr = [],
  619. totalValues = [];
  620. for (var idx = 0; strings.length > idx; ++idx) {
  621. var inputString = strings[idx],
  622. inputValues = strValues[idx];
  623. var _buildString2 = this._buildString(inputString, inputValues, {
  624. buildParameterized: options.buildParameterized,
  625. nested: false
  626. });
  627. var text = _buildString2.text;
  628. var values = _buildString2.values;
  629. totalStr.push(text);
  630. totalValues.push.apply(totalValues, _toConsumableArray(values));
  631. }
  632. totalStr = totalStr.join(this.options.separator);
  633. return {
  634. text: totalStr.length ? this._applyNestingFormatting(totalStr, !!options.nested) : '',
  635. values: totalValues
  636. };
  637. }
  638. /**
  639. * Get parameterized representation of this instance.
  640. *
  641. * @param {Object} [options] Options.
  642. * @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
  643. * @param {Boolean} [options.nested] Whether this expression is nested within another.
  644. * @return {Object}
  645. */
  646. }, {
  647. key: '_toParamString',
  648. value: function _toParamString(options) {
  649. throw new Error('Not yet implemented');
  650. }
  651. /**
  652. * Get the expression string.
  653. * @return {String}
  654. */
  655. }, {
  656. key: 'toString',
  657. value: function toString() {
  658. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  659. return this._toParamString(options).text;
  660. }
  661. /**
  662. * Get the parameterized expression string.
  663. * @return {Object}
  664. */
  665. }, {
  666. key: 'toParam',
  667. value: function toParam() {
  668. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  669. return this._toParamString(_extend({}, options, {
  670. buildParameterized: true
  671. }));
  672. }
  673. }]);
  674. return _class2;
  675. }(cls.Cloneable);
  676. /*
  677. # ---------------------------------------------------------------------------------------------------------
  678. # ---------------------------------------------------------------------------------------------------------
  679. # cls.Expressions
  680. # ---------------------------------------------------------------------------------------------------------
  681. # ---------------------------------------------------------------------------------------------------------
  682. */
  683. /**
  684. * An SQL expression builder.
  685. *
  686. * SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
  687. *
  688. * Expressions can be nested. Nested expression contains can themselves
  689. * contain nested expressions. When rendered a nested expression will be
  690. * fully contained within brackets.
  691. *
  692. * All the build methods in this object return the object instance for chained method calling purposes.
  693. */
  694. cls.Expression = function (_cls$BaseBuilder) {
  695. _inherits(_class3, _cls$BaseBuilder);
  696. // Initialise the expression.
  697. function _class3(options) {
  698. _classCallCheck(this, _class3);
  699. var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class3).call(this, options));
  700. _this5._nodes = [];
  701. return _this5;
  702. }
  703. // Combine the current expression with the given expression using the intersection operator (AND).
  704. _createClass(_class3, [{
  705. key: 'and',
  706. value: function and(expr) {
  707. for (var _len3 = arguments.length, params = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  708. params[_key3 - 1] = arguments[_key3];
  709. }
  710. expr = this._sanitizeExpression(expr);
  711. this._nodes.push({
  712. type: 'AND',
  713. expr: expr,
  714. para: params
  715. });
  716. return this;
  717. }
  718. // Combine the current expression with the given expression using the union operator (OR).
  719. }, {
  720. key: 'or',
  721. value: function or(expr) {
  722. for (var _len4 = arguments.length, params = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  723. params[_key4 - 1] = arguments[_key4];
  724. }
  725. expr = this._sanitizeExpression(expr);
  726. this._nodes.push({
  727. type: 'OR',
  728. expr: expr,
  729. para: params
  730. });
  731. return this;
  732. }
  733. }, {
  734. key: '_toParamString',
  735. value: function _toParamString() {
  736. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  737. var totalStr = [],
  738. totalValues = [];
  739. var _iteratorNormalCompletion5 = true;
  740. var _didIteratorError5 = false;
  741. var _iteratorError5 = undefined;
  742. try {
  743. for (var _iterator5 = this._nodes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
  744. var node = _step5.value;
  745. var type = node.type;
  746. var expr = node.expr;
  747. var para = node.para;
  748. var _ref = expr instanceof cls.Expression ? expr._toParamString({
  749. buildParameterized: options.buildParameterized,
  750. nested: true
  751. }) : this._buildString(expr, para, {
  752. buildParameterized: options.buildParameterized
  753. });
  754. var text = _ref.text;
  755. var values = _ref.values;
  756. if (totalStr.length) {
  757. totalStr.push(type);
  758. }
  759. totalStr.push(text);
  760. totalValues.push.apply(totalValues, _toConsumableArray(values));
  761. }
  762. } catch (err) {
  763. _didIteratorError5 = true;
  764. _iteratorError5 = err;
  765. } finally {
  766. try {
  767. if (!_iteratorNormalCompletion5 && _iterator5.return) {
  768. _iterator5.return();
  769. }
  770. } finally {
  771. if (_didIteratorError5) {
  772. throw _iteratorError5;
  773. }
  774. }
  775. }
  776. totalStr = totalStr.join(' ');
  777. return {
  778. text: this._applyNestingFormatting(totalStr, !!options.nested),
  779. values: totalValues
  780. };
  781. }
  782. }]);
  783. return _class3;
  784. }(cls.BaseBuilder);
  785. /*
  786. # ---------------------------------------------------------------------------------------------------------
  787. # ---------------------------------------------------------------------------------------------------------
  788. # cls.Case
  789. # ---------------------------------------------------------------------------------------------------------
  790. # ---------------------------------------------------------------------------------------------------------
  791. */
  792. /**
  793. * An SQL CASE expression builder.
  794. *
  795. * SQL cases are used to select proper values based on specific criteria.
  796. */
  797. cls.Case = function (_cls$BaseBuilder2) {
  798. _inherits(_class4, _cls$BaseBuilder2);
  799. function _class4(fieldName) {
  800. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  801. _classCallCheck(this, _class4);
  802. var _this6 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class4).call(this, options));
  803. if (_isPlainObject(fieldName)) {
  804. options = fieldName;
  805. fieldName = null;
  806. }
  807. if (fieldName) {
  808. _this6._fieldName = _this6._sanitizeField(fieldName);
  809. }
  810. _this6.options = _extend({}, cls.DefaultQueryBuilderOptions, options);
  811. _this6._cases = [];
  812. _this6._elseValue = null;
  813. return _this6;
  814. }
  815. _createClass(_class4, [{
  816. key: 'when',
  817. value: function when(expression) {
  818. for (var _len5 = arguments.length, values = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  819. values[_key5 - 1] = arguments[_key5];
  820. }
  821. this._cases.unshift({
  822. expression: expression,
  823. values: values
  824. });
  825. return this;
  826. }
  827. }, {
  828. key: 'then',
  829. value: function then(result) {
  830. if (this._cases.length == 0) {
  831. throw new Error("when() needs to be called first");
  832. }
  833. this._cases[0].result = result;
  834. return this;
  835. }
  836. }, {
  837. key: 'else',
  838. value: function _else(elseValue) {
  839. this._elseValue = elseValue;
  840. return this;
  841. }
  842. }, {
  843. key: '_toParamString',
  844. value: function _toParamString() {
  845. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  846. var totalStr = '',
  847. totalValues = [];
  848. var _iteratorNormalCompletion6 = true;
  849. var _didIteratorError6 = false;
  850. var _iteratorError6 = undefined;
  851. try {
  852. for (var _iterator6 = this._cases[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
  853. var _step6$value = _step6.value;
  854. var expression = _step6$value.expression;
  855. var values = _step6$value.values;
  856. var result = _step6$value.result;
  857. totalStr = _pad(totalStr, ' ');
  858. var ret = this._buildString(expression, values, {
  859. buildParameterized: options.buildParameterized,
  860. nested: true
  861. });
  862. totalStr += 'WHEN ' + ret.text + ' THEN ' + this._formatValueForQueryString(result);
  863. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  864. }
  865. } catch (err) {
  866. _didIteratorError6 = true;
  867. _iteratorError6 = err;
  868. } finally {
  869. try {
  870. if (!_iteratorNormalCompletion6 && _iterator6.return) {
  871. _iterator6.return();
  872. }
  873. } finally {
  874. if (_didIteratorError6) {
  875. throw _iteratorError6;
  876. }
  877. }
  878. }
  879. if (totalStr.length) {
  880. totalStr += ' ELSE ' + this._formatValueForQueryString(this._elseValue) + ' END';
  881. if (this._fieldName) {
  882. totalStr = this._fieldName + ' ' + totalStr;
  883. }
  884. totalStr = 'CASE ' + totalStr;
  885. } else {
  886. totalStr = this._formatValueForQueryString(this._elseValue);
  887. }
  888. return {
  889. text: totalStr,
  890. values: totalValues
  891. };
  892. }
  893. }]);
  894. return _class4;
  895. }(cls.BaseBuilder);
  896. /*
  897. # ---------------------------------------------------------------------------------------------------------
  898. # ---------------------------------------------------------------------------------------------------------
  899. # Building blocks
  900. # ---------------------------------------------------------------------------------------------------------
  901. # ---------------------------------------------------------------------------------------------------------
  902. */
  903. /*
  904. # A building block represents a single build-step within a query building process.
  905. #
  906. # Query builders consist of one or more building blocks which get run in a particular order. Building blocks can
  907. # optionally specify methods to expose through the query builder interface. They can access all the input data for
  908. # the query builder and manipulate it as necessary, as well as append to the final query string output.
  909. #
  910. # If you wish to customize how queries get built or add proprietary query phrases and content then it is recommended
  911. # that you do so using one or more custom building blocks.
  912. #
  913. # Original idea posted in https://github.com/hiddentao/export/issues/10#issuecomment-15016427
  914. */
  915. cls.Block = function (_cls$BaseBuilder3) {
  916. _inherits(_class5, _cls$BaseBuilder3);
  917. function _class5(options) {
  918. _classCallCheck(this, _class5);
  919. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class5).call(this, options));
  920. }
  921. /**
  922. # Get input methods to expose within the query builder.
  923. #
  924. # By default all methods except the following get returned:
  925. # methods prefixed with _
  926. # constructor and toString()
  927. #
  928. # @return Object key -> function pairs
  929. */
  930. _createClass(_class5, [{
  931. key: 'exposedMethods',
  932. value: function exposedMethods() {
  933. var ret = {};
  934. var obj = this;
  935. while (obj) {
  936. Object.getOwnPropertyNames(obj).forEach(function (prop) {
  937. if ('constructor' !== prop && typeof obj[prop] === "function" && prop.charAt(0) !== '_' && !cls.Block.prototype[prop]) {
  938. ret[prop] = obj[prop];
  939. }
  940. });
  941. obj = Object.getPrototypeOf(obj);
  942. };
  943. return ret;
  944. }
  945. }]);
  946. return _class5;
  947. }(cls.BaseBuilder);
  948. // A fixed string which always gets output
  949. cls.StringBlock = function (_cls$Block) {
  950. _inherits(_class6, _cls$Block);
  951. function _class6(options, str) {
  952. _classCallCheck(this, _class6);
  953. var _this8 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class6).call(this, options));
  954. _this8._str = str;
  955. return _this8;
  956. }
  957. _createClass(_class6, [{
  958. key: '_toParamString',
  959. value: function _toParamString() {
  960. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  961. return {
  962. text: this._str,
  963. values: []
  964. };
  965. }
  966. }]);
  967. return _class6;
  968. }(cls.Block);
  969. // A function string block
  970. cls.FunctionBlock = function (_cls$Block2) {
  971. _inherits(_class7, _cls$Block2);
  972. function _class7(options) {
  973. _classCallCheck(this, _class7);
  974. var _this9 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class7).call(this, options));
  975. _this9._strings = [];
  976. _this9._values = [];
  977. return _this9;
  978. }
  979. _createClass(_class7, [{
  980. key: 'function',
  981. value: function _function(str) {
  982. this._strings.push(str);
  983. for (var _len6 = arguments.length, values = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
  984. values[_key6 - 1] = arguments[_key6];
  985. }
  986. this._values.push(values);
  987. }
  988. }, {
  989. key: '_toParamString',
  990. value: function _toParamString() {
  991. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  992. return this._buildManyStrings(this._strings, this._values, options);
  993. }
  994. }]);
  995. return _class7;
  996. }(cls.Block);
  997. // value handler for FunctionValueBlock objects
  998. cls.registerValueHandler(cls.FunctionBlock, function (value) {
  999. var asParam = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  1000. return asParam ? value.toParam() : value.toString();
  1001. });
  1002. /*
  1003. # Table specifier base class
  1004. */
  1005. cls.AbstractTableBlock = function (_cls$Block3) {
  1006. _inherits(_class8, _cls$Block3);
  1007. /**
  1008. * @param {Boolean} [options.singleTable] If true then only allow one table spec.
  1009. * @param {String} [options.prefix] String prefix for output.
  1010. */
  1011. function _class8(options, prefix) {
  1012. _classCallCheck(this, _class8);
  1013. var _this10 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class8).call(this, options));
  1014. _this10._tables = [];
  1015. return _this10;
  1016. }
  1017. /**
  1018. # Update given table.
  1019. #
  1020. # An alias may also be specified for the table.
  1021. #
  1022. # Concrete subclasses should provide a method which calls this
  1023. */
  1024. _createClass(_class8, [{
  1025. key: '_table',
  1026. value: function _table(table) {
  1027. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1028. alias = alias ? this._sanitizeTableAlias(alias) : alias;
  1029. table = this._sanitizeTable(table);
  1030. if (this.options.singleTable) {
  1031. this._tables = [];
  1032. }
  1033. this._tables.push({
  1034. table: table,
  1035. alias: alias
  1036. });
  1037. }
  1038. // get whether a table has been set
  1039. }, {
  1040. key: '_hasTable',
  1041. value: function _hasTable() {
  1042. return 0 < this._tables.length;
  1043. }
  1044. /**
  1045. * @override
  1046. */
  1047. }, {
  1048. key: '_toParamString',
  1049. value: function _toParamString() {
  1050. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1051. var totalStr = '',
  1052. totalValues = [];
  1053. if (this._hasTable()) {
  1054. // retrieve the parameterised queries
  1055. var _iteratorNormalCompletion7 = true;
  1056. var _didIteratorError7 = false;
  1057. var _iteratorError7 = undefined;
  1058. try {
  1059. for (var _iterator7 = this._tables[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
  1060. var _step7$value = _step7.value;
  1061. var table = _step7$value.table;
  1062. var alias = _step7$value.alias;
  1063. totalStr = _pad(totalStr, ', ');
  1064. var tableStr = void 0;
  1065. if (table instanceof cls.BaseBuilder) {
  1066. var _table$_toParamString = table._toParamString({
  1067. buildParameterized: options.buildParameterized,
  1068. nested: true
  1069. });
  1070. var text = _table$_toParamString.text;
  1071. var values = _table$_toParamString.values;
  1072. tableStr = text;
  1073. totalValues.push.apply(totalValues, _toConsumableArray(values));
  1074. } else {
  1075. tableStr = this._formatTableName(table);
  1076. }
  1077. if (alias) {
  1078. tableStr += ' ' + this._formatTableAlias(alias);
  1079. }
  1080. totalStr += tableStr;
  1081. }
  1082. } catch (err) {
  1083. _didIteratorError7 = true;
  1084. _iteratorError7 = err;
  1085. } finally {
  1086. try {
  1087. if (!_iteratorNormalCompletion7 && _iterator7.return) {
  1088. _iterator7.return();
  1089. }
  1090. } finally {
  1091. if (_didIteratorError7) {
  1092. throw _iteratorError7;
  1093. }
  1094. }
  1095. }
  1096. if (this.options.prefix) {
  1097. totalStr = this.options.prefix + ' ' + totalStr;
  1098. }
  1099. }
  1100. return {
  1101. text: totalStr,
  1102. values: totalValues
  1103. };
  1104. }
  1105. }]);
  1106. return _class8;
  1107. }(cls.Block);
  1108. // target table for DELETE queries, DELETE <??> FROM
  1109. cls.TargetTableBlock = function (_cls$AbstractTableBlo) {
  1110. _inherits(_class9, _cls$AbstractTableBlo);
  1111. function _class9() {
  1112. _classCallCheck(this, _class9);
  1113. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class9).apply(this, arguments));
  1114. }
  1115. _createClass(_class9, [{
  1116. key: 'target',
  1117. value: function target(table) {
  1118. this._table(table);
  1119. }
  1120. }]);
  1121. return _class9;
  1122. }(cls.AbstractTableBlock);
  1123. // Update Table
  1124. cls.UpdateTableBlock = function (_cls$AbstractTableBlo2) {
  1125. _inherits(_class10, _cls$AbstractTableBlo2);
  1126. function _class10() {
  1127. _classCallCheck(this, _class10);
  1128. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class10).apply(this, arguments));
  1129. }
  1130. _createClass(_class10, [{
  1131. key: 'table',
  1132. value: function table(_table2) {
  1133. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1134. this._table(_table2, alias);
  1135. }
  1136. }, {
  1137. key: '_toParamString',
  1138. value: function _toParamString() {
  1139. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1140. if (!this._hasTable()) {
  1141. throw new Error("table() needs to be called");
  1142. }
  1143. return _get(Object.getPrototypeOf(_class10.prototype), '_toParamString', this).call(this, options);
  1144. }
  1145. }]);
  1146. return _class10;
  1147. }(cls.AbstractTableBlock);
  1148. // FROM table
  1149. cls.FromTableBlock = function (_cls$AbstractTableBlo3) {
  1150. _inherits(_class11, _cls$AbstractTableBlo3);
  1151. function _class11(options) {
  1152. _classCallCheck(this, _class11);
  1153. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class11).call(this, _extend({}, options, {
  1154. prefix: 'FROM'
  1155. })));
  1156. }
  1157. _createClass(_class11, [{
  1158. key: 'from',
  1159. value: function from(table) {
  1160. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1161. this._table(table, alias);
  1162. }
  1163. }]);
  1164. return _class11;
  1165. }(cls.AbstractTableBlock);
  1166. // INTO table
  1167. cls.IntoTableBlock = function (_cls$AbstractTableBlo4) {
  1168. _inherits(_class12, _cls$AbstractTableBlo4);
  1169. function _class12(options) {
  1170. _classCallCheck(this, _class12);
  1171. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class12).call(this, _extend({}, options, {
  1172. prefix: 'INTO',
  1173. singleTable: true
  1174. })));
  1175. }
  1176. _createClass(_class12, [{
  1177. key: 'into',
  1178. value: function into(table) {
  1179. this._table(table);
  1180. }
  1181. }, {
  1182. key: '_toParamString',
  1183. value: function _toParamString() {
  1184. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1185. if (!this._hasTable()) {
  1186. throw new Error("into() needs to be called");
  1187. }
  1188. return _get(Object.getPrototypeOf(_class12.prototype), '_toParamString', this).call(this, options);
  1189. }
  1190. }]);
  1191. return _class12;
  1192. }(cls.AbstractTableBlock);
  1193. // (SELECT) Get field
  1194. cls.GetFieldBlock = function (_cls$Block4) {
  1195. _inherits(_class13, _cls$Block4);
  1196. function _class13(options) {
  1197. _classCallCheck(this, _class13);
  1198. var _this15 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class13).call(this, options));
  1199. _this15._fields = [];
  1200. return _this15;
  1201. }
  1202. /**
  1203. # Add the given fields to the final result set.
  1204. #
  1205. # The parameter is an Object containing field names (or database functions) as the keys and aliases for the fields
  1206. # as the values. If the value for a key is null then no alias is set for that field.
  1207. #
  1208. # Internally this method simply calls the field() method of this block to add each individual field.
  1209. #
  1210. # options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
  1211. */
  1212. _createClass(_class13, [{
  1213. key: 'fields',
  1214. value: function fields(_fields) {
  1215. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  1216. if (_isArray(_fields)) {
  1217. var _iteratorNormalCompletion8 = true;
  1218. var _didIteratorError8 = false;
  1219. var _iteratorError8 = undefined;
  1220. try {
  1221. for (var _iterator8 = _fields[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
  1222. var field = _step8.value;
  1223. this.field(field, null, options);
  1224. }
  1225. } catch (err) {
  1226. _didIteratorError8 = true;
  1227. _iteratorError8 = err;
  1228. } finally {
  1229. try {
  1230. if (!_iteratorNormalCompletion8 && _iterator8.return) {
  1231. _iterator8.return();
  1232. }
  1233. } finally {
  1234. if (_didIteratorError8) {
  1235. throw _iteratorError8;
  1236. }
  1237. }
  1238. }
  1239. } else {
  1240. for (var _field2 in _fields) {
  1241. var alias = _fields[_field2];
  1242. this.field(_field2, alias, options);
  1243. }
  1244. }
  1245. }
  1246. /**
  1247. # Add the given field to the final result set.
  1248. #
  1249. # The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
  1250. # e.g. DATE_FORMAT(a.started, "%H")
  1251. #
  1252. # An alias may also be specified for this field.
  1253. #
  1254. # options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
  1255. */
  1256. }, {
  1257. key: 'field',
  1258. value: function field(_field) {
  1259. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1260. var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  1261. alias = alias ? this._sanitizeFieldAlias(alias) : alias;
  1262. _field = this._sanitizeField(_field);
  1263. // if field-alias combo already present then don't add
  1264. var existingField = this._fields.filter(function (f) {
  1265. return f.name === _field && f.alias === alias;
  1266. });
  1267. if (existingField.length) {
  1268. return this;
  1269. }
  1270. this._fields.push({
  1271. name: _field,
  1272. alias: alias,
  1273. options: options
  1274. });
  1275. }
  1276. }, {
  1277. key: '_toParamString',
  1278. value: function _toParamString() {
  1279. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1280. var queryBuilder = options.queryBuilder;
  1281. var buildParameterized = options.buildParameterized;
  1282. var totalStr = '',
  1283. totalValues = [];
  1284. var _iteratorNormalCompletion9 = true;
  1285. var _didIteratorError9 = false;
  1286. var _iteratorError9 = undefined;
  1287. try {
  1288. for (var _iterator9 = this._fields[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
  1289. var field = _step9.value;
  1290. totalStr = _pad(totalStr, ", ");
  1291. var name = field.name;
  1292. var alias = field.alias;
  1293. var _options = field.options;
  1294. if (typeof name === 'string') {
  1295. totalStr += this._formatFieldName(name, _options);
  1296. } else {
  1297. var ret = name._toParamString({
  1298. nested: true,
  1299. buildParameterized: buildParameterized
  1300. });
  1301. totalStr += ret.text;
  1302. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1303. }
  1304. if (alias) {
  1305. totalStr += ' AS ' + this._formatFieldAlias(alias);
  1306. }
  1307. }
  1308. } catch (err) {
  1309. _didIteratorError9 = true;
  1310. _iteratorError9 = err;
  1311. } finally {
  1312. try {
  1313. if (!_iteratorNormalCompletion9 && _iterator9.return) {
  1314. _iterator9.return();
  1315. }
  1316. } finally {
  1317. if (_didIteratorError9) {
  1318. throw _iteratorError9;
  1319. }
  1320. }
  1321. }
  1322. if (!totalStr.length) {
  1323. // if select query and a table is set then all fields wanted
  1324. var fromTableBlock = queryBuilder && queryBuilder.getBlock(cls.FromTableBlock);
  1325. if (fromTableBlock && fromTableBlock._hasTable()) {
  1326. totalStr = "*";
  1327. }
  1328. }
  1329. return {
  1330. text: totalStr,
  1331. values: totalValues
  1332. };
  1333. }
  1334. }]);
  1335. return _class13;
  1336. }(cls.Block);
  1337. // Base class for setting fields to values (used for INSERT and UPDATE queries)
  1338. cls.AbstractSetFieldBlock = function (_cls$Block5) {
  1339. _inherits(_class14, _cls$Block5);
  1340. function _class14(options) {
  1341. _classCallCheck(this, _class14);
  1342. var _this16 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class14).call(this, options));
  1343. _this16._reset();
  1344. return _this16;
  1345. }
  1346. _createClass(_class14, [{
  1347. key: '_reset',
  1348. value: function _reset() {
  1349. this._fields = [];
  1350. this._values = [[]];
  1351. this._valueOptions = [[]];
  1352. }
  1353. // Update the given field with the given value.
  1354. // This will override any previously set value for the given field.
  1355. }, {
  1356. key: '_set',
  1357. value: function _set(field, value) {
  1358. var valueOptions = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  1359. if (this._values.length > 1) {
  1360. throw new Error("Cannot set multiple rows of fields this way.");
  1361. }
  1362. if (typeof value !== 'undefined') {
  1363. value = this._sanitizeValue(value);
  1364. }
  1365. field = this._sanitizeField(field);
  1366. // Explicity overwrite existing fields
  1367. var index = this._fields.indexOf(field);
  1368. // if field not defined before
  1369. if (-1 === index) {
  1370. this._fields.push(field);
  1371. index = this._fields.length - 1;
  1372. }
  1373. this._values[0][index] = value;
  1374. this._valueOptions[0][index] = valueOptions;
  1375. }
  1376. // Insert fields based on the key/value pairs in the given object
  1377. }, {
  1378. key: '_setFields',
  1379. value: function _setFields(fields) {
  1380. var valueOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  1381. if ((typeof fields === 'undefined' ? 'undefined' : _typeof(fields)) !== 'object') {
  1382. throw new Error("Expected an object but got " + (typeof fields === 'undefined' ? 'undefined' : _typeof(fields)));
  1383. }
  1384. for (var field in fields) {
  1385. this._set(field, fields[field], valueOptions);
  1386. }
  1387. }
  1388. // Insert multiple rows for the given fields. Accepts an array of objects.
  1389. // This will override all previously set values for every field.
  1390. }, {
  1391. key: '_setFieldsRows',
  1392. value: function _setFieldsRows(fieldsRows) {
  1393. var valueOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  1394. if (!_isArray(fieldsRows)) {
  1395. throw new Error("Expected an array of objects but got " + (typeof fieldsRows === 'undefined' ? 'undefined' : _typeof(fieldsRows)));
  1396. }
  1397. // Reset the objects stored fields and values
  1398. this._reset();
  1399. // for each row
  1400. for (var i = 0; fieldsRows.length > i; ++i) {
  1401. var fieldRow = fieldsRows[i];
  1402. // for each field
  1403. for (var field in fieldRow) {
  1404. var value = fieldRow[field];
  1405. field = this._sanitizeField(field);
  1406. value = this._sanitizeValue(value);
  1407. var index = this._fields.indexOf(field);
  1408. if (0 < i && -1 === index) {
  1409. throw new Error('All fields in subsequent rows must match the fields in the first row');
  1410. }
  1411. // Add field only if it hasn't been added before
  1412. if (-1 === index) {
  1413. this._fields.push(field);
  1414. index = this._fields.length - 1;
  1415. }
  1416. // The first value added needs to add the array
  1417. if (!_isArray(this._values[i])) {
  1418. this._values[i] = [];
  1419. this._valueOptions[i] = [];
  1420. }
  1421. this._values[i][index] = value;
  1422. this._valueOptions[i][index] = valueOptions;
  1423. }
  1424. }
  1425. }
  1426. }]);
  1427. return _class14;
  1428. }(cls.Block);
  1429. // (UPDATE) SET field=value
  1430. cls.SetFieldBlock = function (_cls$AbstractSetField) {
  1431. _inherits(_class15, _cls$AbstractSetField);
  1432. function _class15() {
  1433. _classCallCheck(this, _class15);
  1434. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class15).apply(this, arguments));
  1435. }
  1436. _createClass(_class15, [{
  1437. key: 'set',
  1438. value: function set(field, value, options) {
  1439. this._set(field, value, options);
  1440. }
  1441. }, {
  1442. key: 'setFields',
  1443. value: function setFields(fields, valueOptions) {
  1444. this._setFields(fields, valueOptions);
  1445. }
  1446. }, {
  1447. key: '_toParamString',
  1448. value: function _toParamString() {
  1449. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1450. var buildParameterized = options.buildParameterized;
  1451. if (0 >= this._fields.length) {
  1452. throw new Error("set() needs to be called");
  1453. }
  1454. var totalStr = '',
  1455. totalValues = [];
  1456. for (var i = 0; i < this._fields.length; ++i) {
  1457. totalStr = _pad(totalStr, ', ');
  1458. var field = this._formatFieldName(this._fields[i]);
  1459. var value = this._values[0][i];
  1460. // e.g. field can be an expression such as `count = count + 1`
  1461. if (0 > field.indexOf('=')) {
  1462. field = field + ' = ' + this.options.parameterCharacter;
  1463. }
  1464. var ret = this._buildString(field, [value], {
  1465. buildParameterized: buildParameterized,
  1466. formattingOptions: this._valueOptions[0][i]
  1467. });
  1468. totalStr += ret.text;
  1469. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1470. }
  1471. return {
  1472. text: 'SET ' + totalStr,
  1473. values: totalValues
  1474. };
  1475. }
  1476. }]);
  1477. return _class15;
  1478. }(cls.AbstractSetFieldBlock);
  1479. // (INSERT INTO) ... field ... value
  1480. cls.InsertFieldValueBlock = function (_cls$AbstractSetField2) {
  1481. _inherits(_class16, _cls$AbstractSetField2);
  1482. function _class16() {
  1483. _classCallCheck(this, _class16);
  1484. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class16).apply(this, arguments));
  1485. }
  1486. _createClass(_class16, [{
  1487. key: 'set',
  1488. value: function set(field, value) {
  1489. var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  1490. this._set(field, value, options);
  1491. }
  1492. }, {
  1493. key: 'setFields',
  1494. value: function setFields(fields, valueOptions) {
  1495. this._setFields(fields, valueOptions);
  1496. }
  1497. }, {
  1498. key: 'setFieldsRows',
  1499. value: function setFieldsRows(fieldsRows, valueOptions) {
  1500. this._setFieldsRows(fieldsRows, valueOptions);
  1501. }
  1502. }, {
  1503. key: '_toParamString',
  1504. value: function _toParamString() {
  1505. var _this19 = this;
  1506. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1507. var buildParameterized = options.buildParameterized;
  1508. var fieldString = this._fields.map(function (f) {
  1509. return _this19._formatFieldName(f);
  1510. }).join(', ');
  1511. var valueStrings = [],
  1512. totalValues = [];
  1513. for (var i = 0; i < this._values.length; ++i) {
  1514. valueStrings[i] = '';
  1515. for (var j = 0; j < this._values[i].length; ++j) {
  1516. var ret = this._buildString(this.options.parameterCharacter, [this._values[i][j]], {
  1517. buildParameterized: buildParameterized,
  1518. formattingOptions: this._valueOptions[i][j]
  1519. });
  1520. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1521. valueStrings[i] = _pad(valueStrings[i], ', ');
  1522. valueStrings[i] += ret.text;
  1523. }
  1524. }
  1525. return {
  1526. text: fieldString.length ? '(' + fieldString + ') VALUES (' + valueStrings.join('), (') + ')' : '',
  1527. values: totalValues
  1528. };
  1529. }
  1530. }]);
  1531. return _class16;
  1532. }(cls.AbstractSetFieldBlock);
  1533. // (INSERT INTO) ... field ... (SELECT ... FROM ...)
  1534. cls.InsertFieldsFromQueryBlock = function (_cls$Block6) {
  1535. _inherits(_class17, _cls$Block6);
  1536. function _class17(options) {
  1537. _classCallCheck(this, _class17);
  1538. var _this20 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class17).call(this, options));
  1539. _this20._fields = [];
  1540. _this20._query = null;
  1541. return _this20;
  1542. }
  1543. _createClass(_class17, [{
  1544. key: 'fromQuery',
  1545. value: function fromQuery(fields, selectQuery) {
  1546. var _this21 = this;
  1547. this._fields = fields.map(function (v) {
  1548. return _this21._sanitizeField(v);
  1549. });
  1550. this._query = this._sanitizeBaseBuilder(selectQuery);
  1551. }
  1552. }, {
  1553. key: '_toParamString',
  1554. value: function _toParamString() {
  1555. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1556. var totalStr = '',
  1557. totalValues = [];
  1558. if (this._fields.length && this._query) {
  1559. var _query$_toParamString = this._query._toParamString({
  1560. buildParameterized: options.buildParameterized,
  1561. nested: true
  1562. });
  1563. var text = _query$_toParamString.text;
  1564. var values = _query$_toParamString.values;
  1565. totalStr = '(' + this._fields.join(', ') + ') ' + this._applyNestingFormatting(text);
  1566. totalValues = values;
  1567. }
  1568. return {
  1569. text: totalStr,
  1570. values: totalValues
  1571. };
  1572. }
  1573. }]);
  1574. return _class17;
  1575. }(cls.Block);
  1576. // DISTINCT
  1577. cls.DistinctBlock = function (_cls$Block7) {
  1578. _inherits(_class18, _cls$Block7);
  1579. function _class18() {
  1580. _classCallCheck(this, _class18);
  1581. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class18).apply(this, arguments));
  1582. }
  1583. _createClass(_class18, [{
  1584. key: 'distinct',
  1585. // Add the DISTINCT keyword to the query.
  1586. value: function distinct() {
  1587. this._useDistinct = true;
  1588. }
  1589. }, {
  1590. key: '_toParamString',
  1591. value: function _toParamString() {
  1592. return {
  1593. text: this._useDistinct ? "DISTINCT" : "",
  1594. values: []
  1595. };
  1596. }
  1597. }]);
  1598. return _class18;
  1599. }(cls.Block);
  1600. // GROUP BY
  1601. cls.GroupByBlock = function (_cls$Block8) {
  1602. _inherits(_class19, _cls$Block8);
  1603. function _class19(options) {
  1604. _classCallCheck(this, _class19);
  1605. var _this23 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class19).call(this, options));
  1606. _this23._groups = [];
  1607. return _this23;
  1608. }
  1609. // Add a GROUP BY transformation for the given field.
  1610. _createClass(_class19, [{
  1611. key: 'group',
  1612. value: function group(field) {
  1613. this._groups.push(this._sanitizeField(field));
  1614. }
  1615. }, {
  1616. key: '_toParamString',
  1617. value: function _toParamString() {
  1618. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1619. return {
  1620. text: this._groups.length ? 'GROUP BY ' + this._groups.join(', ') : '',
  1621. values: []
  1622. };
  1623. }
  1624. }]);
  1625. return _class19;
  1626. }(cls.Block);
  1627. // OFFSET x
  1628. cls.OffsetBlock = function (_cls$Block9) {
  1629. _inherits(_class20, _cls$Block9);
  1630. function _class20(options) {
  1631. _classCallCheck(this, _class20);
  1632. var _this24 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class20).call(this, options));
  1633. _this24._offsets = null;
  1634. return _this24;
  1635. }
  1636. /**
  1637. # Set the OFFSET transformation.
  1638. #
  1639. # Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
  1640. # the offset.
  1641. */
  1642. _createClass(_class20, [{
  1643. key: 'offset',
  1644. value: function offset(start) {
  1645. this._offsets = this._sanitizeLimitOffset(start);
  1646. }
  1647. }, {
  1648. key: '_toParamString',
  1649. value: function _toParamString() {
  1650. return {
  1651. text: this._offsets ? 'OFFSET ' + this._offsets : '',
  1652. values: []
  1653. };
  1654. }
  1655. }]);
  1656. return _class20;
  1657. }(cls.Block);
  1658. // Abstract condition base class
  1659. cls.AbstractConditionBlock = function (_cls$Block10) {
  1660. _inherits(_class21, _cls$Block10);
  1661. /**
  1662. * @param {String} options.verb The condition verb.
  1663. */
  1664. function _class21(options) {
  1665. _classCallCheck(this, _class21);
  1666. var _this25 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class21).call(this, options));
  1667. _this25._conditions = [];
  1668. return _this25;
  1669. }
  1670. /**
  1671. # Add a condition.
  1672. #
  1673. # When the final query is constructed all the conditions are combined using the intersection (AND) operator.
  1674. #
  1675. # Concrete subclasses should provide a method which calls this
  1676. */
  1677. _createClass(_class21, [{
  1678. key: '_condition',
  1679. value: function _condition(condition) {
  1680. for (var _len7 = arguments.length, values = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
  1681. values[_key7 - 1] = arguments[_key7];
  1682. }
  1683. condition = this._sanitizeExpression(condition);
  1684. this._conditions.push({
  1685. expr: condition,
  1686. values: values
  1687. });
  1688. }
  1689. }, {
  1690. key: '_toParamString',
  1691. value: function _toParamString() {
  1692. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1693. var totalStr = [],
  1694. totalValues = [];
  1695. var _iteratorNormalCompletion10 = true;
  1696. var _didIteratorError10 = false;
  1697. var _iteratorError10 = undefined;
  1698. try {
  1699. for (var _iterator10 = this._conditions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
  1700. var _step10$value = _step10.value;
  1701. var expr = _step10$value.expr;
  1702. var values = _step10$value.values;
  1703. var ret = expr instanceof cls.Expression ? expr._toParamString({
  1704. buildParameterized: options.buildParameterized
  1705. }) : this._buildString(expr, values, {
  1706. buildParameterized: options.buildParameterized
  1707. });
  1708. if (ret.text.length) {
  1709. totalStr.push(ret.text);
  1710. }
  1711. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1712. }
  1713. } catch (err) {
  1714. _didIteratorError10 = true;
  1715. _iteratorError10 = err;
  1716. } finally {
  1717. try {
  1718. if (!_iteratorNormalCompletion10 && _iterator10.return) {
  1719. _iterator10.return();
  1720. }
  1721. } finally {
  1722. if (_didIteratorError10) {
  1723. throw _iteratorError10;
  1724. }
  1725. }
  1726. }
  1727. if (totalStr.length) {
  1728. totalStr = totalStr.join(') AND (');
  1729. }
  1730. return {
  1731. text: totalStr.length ? this.options.verb + ' (' + totalStr + ')' : '',
  1732. values: totalValues
  1733. };
  1734. }
  1735. }]);
  1736. return _class21;
  1737. }(cls.Block);
  1738. // WHERE
  1739. cls.WhereBlock = function (_cls$AbstractConditio) {
  1740. _inherits(_class22, _cls$AbstractConditio);
  1741. function _class22(options) {
  1742. _classCallCheck(this, _class22);
  1743. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class22).call(this, _extend({}, options, {
  1744. verb: 'WHERE'
  1745. })));
  1746. }
  1747. _createClass(_class22, [{
  1748. key: 'where',
  1749. value: function where(condition) {
  1750. for (var _len8 = arguments.length, values = Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) {
  1751. values[_key8 - 1] = arguments[_key8];
  1752. }
  1753. this._condition.apply(this, [condition].concat(values));
  1754. }
  1755. }]);
  1756. return _class22;
  1757. }(cls.AbstractConditionBlock);
  1758. // HAVING
  1759. cls.HavingBlock = function (_cls$AbstractConditio2) {
  1760. _inherits(_class23, _cls$AbstractConditio2);
  1761. function _class23(options) {
  1762. _classCallCheck(this, _class23);
  1763. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class23).call(this, _extend({}, options, {
  1764. verb: 'HAVING'
  1765. })));
  1766. }
  1767. _createClass(_class23, [{
  1768. key: 'having',
  1769. value: function having(condition) {
  1770. for (var _len9 = arguments.length, values = Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
  1771. values[_key9 - 1] = arguments[_key9];
  1772. }
  1773. this._condition.apply(this, [condition].concat(values));
  1774. }
  1775. }]);
  1776. return _class23;
  1777. }(cls.AbstractConditionBlock);
  1778. // ORDER BY
  1779. cls.OrderByBlock = function (_cls$Block11) {
  1780. _inherits(_class24, _cls$Block11);
  1781. function _class24(options) {
  1782. _classCallCheck(this, _class24);
  1783. var _this28 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class24).call(this, options));
  1784. _this28._orders = [];
  1785. return _this28;
  1786. }
  1787. /**
  1788. # Add an ORDER BY transformation for the given field in the given order.
  1789. #
  1790. # To specify descending order pass false for the 'asc' parameter.
  1791. */
  1792. _createClass(_class24, [{
  1793. key: 'order',
  1794. value: function order(field, asc) {
  1795. for (var _len10 = arguments.length, values = Array(_len10 > 2 ? _len10 - 2 : 0), _key10 = 2; _key10 < _len10; _key10++) {
  1796. values[_key10 - 2] = arguments[_key10];
  1797. }
  1798. field = this._sanitizeField(field);
  1799. asc = asc === undefined ? true : asc;
  1800. asc = asc !== null ? !!asc : asc;
  1801. this._orders.push({
  1802. field: field,
  1803. dir: asc,
  1804. values: values
  1805. });
  1806. }
  1807. }, {
  1808. key: '_toParamString',
  1809. value: function _toParamString() {
  1810. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1811. var totalStr = '',
  1812. totalValues = [];
  1813. var _iteratorNormalCompletion11 = true;
  1814. var _didIteratorError11 = false;
  1815. var _iteratorError11 = undefined;
  1816. try {
  1817. for (var _iterator11 = this._orders[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
  1818. var _step11$value = _step11.value;
  1819. var field = _step11$value.field;
  1820. var dir = _step11$value.dir;
  1821. var values = _step11$value.values;
  1822. totalStr = _pad(totalStr, ', ');
  1823. var ret = this._buildString(field, values, {
  1824. buildParameterized: options.buildParameterized
  1825. });
  1826. totalStr += ret.text, totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1827. if (dir !== null) {
  1828. totalStr += ' ' + (dir ? 'ASC' : 'DESC');
  1829. }
  1830. }
  1831. } catch (err) {
  1832. _didIteratorError11 = true;
  1833. _iteratorError11 = err;
  1834. } finally {
  1835. try {
  1836. if (!_iteratorNormalCompletion11 && _iterator11.return) {
  1837. _iterator11.return();
  1838. }
  1839. } finally {
  1840. if (_didIteratorError11) {
  1841. throw _iteratorError11;
  1842. }
  1843. }
  1844. }
  1845. return {
  1846. text: totalStr.length ? 'ORDER BY ' + totalStr : '',
  1847. values: totalValues
  1848. };
  1849. }
  1850. }]);
  1851. return _class24;
  1852. }(cls.Block);
  1853. // LIMIT
  1854. cls.LimitBlock = function (_cls$Block12) {
  1855. _inherits(_class25, _cls$Block12);
  1856. function _class25(options) {
  1857. _classCallCheck(this, _class25);
  1858. var _this29 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class25).call(this, options));
  1859. _this29._limit = null;
  1860. return _this29;
  1861. }
  1862. /**
  1863. # Set the LIMIT transformation.
  1864. #
  1865. # Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
  1866. # the limit.
  1867. */
  1868. _createClass(_class25, [{
  1869. key: 'limit',
  1870. value: function limit(_limit) {
  1871. this._limit = this._sanitizeLimitOffset(_limit);
  1872. }
  1873. }, {
  1874. key: '_toParamString',
  1875. value: function _toParamString() {
  1876. return {
  1877. text: null !== this._limit ? 'LIMIT ' + this._limit : '',
  1878. values: []
  1879. };
  1880. }
  1881. }]);
  1882. return _class25;
  1883. }(cls.Block);
  1884. // JOIN
  1885. cls.JoinBlock = function (_cls$Block13) {
  1886. _inherits(_class26, _cls$Block13);
  1887. function _class26(options) {
  1888. _classCallCheck(this, _class26);
  1889. var _this30 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class26).call(this, options));
  1890. _this30._joins = [];
  1891. return _this30;
  1892. }
  1893. /**
  1894. # Add a JOIN with the given table.
  1895. #
  1896. # 'table' is the name of the table to join with.
  1897. #
  1898. # 'alias' is an optional alias for the table name.
  1899. #
  1900. # 'condition' is an optional condition (containing an SQL expression) for the JOIN.
  1901. #
  1902. # 'type' must be either one of INNER, OUTER, LEFT or RIGHT. Default is 'INNER'.
  1903. #
  1904. */
  1905. _createClass(_class26, [{
  1906. key: 'join',
  1907. value: function join(table) {
  1908. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1909. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1910. var type = arguments.length <= 3 || arguments[3] === undefined ? 'INNER' : arguments[3];
  1911. table = this._sanitizeTable(table, true);
  1912. alias = alias ? this._sanitizeTableAlias(alias) : alias;
  1913. condition = condition ? this._sanitizeExpression(condition) : condition;
  1914. this._joins.push({
  1915. type: type,
  1916. table: table,
  1917. alias: alias,
  1918. condition: condition
  1919. });
  1920. }
  1921. }, {
  1922. key: 'left_join',
  1923. value: function left_join(table) {
  1924. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1925. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1926. this.join(table, alias, condition, 'LEFT');
  1927. }
  1928. }, {
  1929. key: 'right_join',
  1930. value: function right_join(table) {
  1931. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1932. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1933. this.join(table, alias, condition, 'RIGHT');
  1934. }
  1935. }, {
  1936. key: 'outer_join',
  1937. value: function outer_join(table) {
  1938. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1939. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1940. this.join(table, alias, condition, 'OUTER');
  1941. }
  1942. }, {
  1943. key: 'left_outer_join',
  1944. value: function left_outer_join(table) {
  1945. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1946. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1947. this.join(table, alias, condition, 'LEFT OUTER');
  1948. }
  1949. }, {
  1950. key: 'full_join',
  1951. value: function full_join(table) {
  1952. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1953. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1954. this.join(table, alias, condition, 'FULL');
  1955. }
  1956. }, {
  1957. key: 'cross_join',
  1958. value: function cross_join(table) {
  1959. var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  1960. var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  1961. this.join(table, alias, condition, 'CROSS');
  1962. }
  1963. }, {
  1964. key: '_toParamString',
  1965. value: function _toParamString() {
  1966. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1967. var totalStr = "",
  1968. totalValues = [];
  1969. var _iteratorNormalCompletion12 = true;
  1970. var _didIteratorError12 = false;
  1971. var _iteratorError12 = undefined;
  1972. try {
  1973. for (var _iterator12 = this._joins[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
  1974. var _step12$value = _step12.value;
  1975. var type = _step12$value.type;
  1976. var table = _step12$value.table;
  1977. var alias = _step12$value.alias;
  1978. var condition = _step12$value.condition;
  1979. totalStr = _pad(totalStr, this.options.separator);
  1980. var tableStr = void 0;
  1981. if (table instanceof cls.BaseBuilder) {
  1982. var ret = table._toParamString({
  1983. buildParameterized: options.buildParameterized,
  1984. nested: true
  1985. });
  1986. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  1987. tableStr = ret.text;
  1988. } else {
  1989. tableStr = this._formatTableName(table);
  1990. }
  1991. totalStr += type + ' JOIN ' + tableStr;
  1992. if (alias) {
  1993. totalStr += ' ' + this._formatTableAlias(alias);
  1994. }
  1995. if (condition) {
  1996. totalStr += ' ON ';
  1997. var _ret4 = void 0;
  1998. if (condition instanceof cls.Expression) {
  1999. _ret4 = condition._toParamString({
  2000. buildParameterized: options.buildParameterized
  2001. });
  2002. } else {
  2003. _ret4 = this._buildString(condition, [], {
  2004. buildParameterized: options.buildParameterized
  2005. });
  2006. }
  2007. totalStr += this._applyNestingFormatting(_ret4.text);
  2008. totalValues.push.apply(totalValues, _toConsumableArray(_ret4.values));
  2009. }
  2010. }
  2011. } catch (err) {
  2012. _didIteratorError12 = true;
  2013. _iteratorError12 = err;
  2014. } finally {
  2015. try {
  2016. if (!_iteratorNormalCompletion12 && _iterator12.return) {
  2017. _iterator12.return();
  2018. }
  2019. } finally {
  2020. if (_didIteratorError12) {
  2021. throw _iteratorError12;
  2022. }
  2023. }
  2024. }
  2025. return {
  2026. text: totalStr,
  2027. values: totalValues
  2028. };
  2029. }
  2030. }]);
  2031. return _class26;
  2032. }(cls.Block);
  2033. // UNION
  2034. cls.UnionBlock = function (_cls$Block14) {
  2035. _inherits(_class27, _cls$Block14);
  2036. function _class27(options) {
  2037. _classCallCheck(this, _class27);
  2038. var _this31 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class27).call(this, options));
  2039. _this31._unions = [];
  2040. return _this31;
  2041. }
  2042. /**
  2043. # Add a UNION with the given table/query.
  2044. #
  2045. # 'table' is the name of the table or query to union with.
  2046. #
  2047. # 'type' must be either one of UNION or UNION ALL.... Default is 'UNION'.
  2048. */
  2049. _createClass(_class27, [{
  2050. key: 'union',
  2051. value: function union(table) {
  2052. var type = arguments.length <= 1 || arguments[1] === undefined ? 'UNION' : arguments[1];
  2053. table = this._sanitizeTable(table);
  2054. this._unions.push({
  2055. type: type,
  2056. table: table
  2057. });
  2058. }
  2059. // Add a UNION ALL with the given table/query.
  2060. }, {
  2061. key: 'union_all',
  2062. value: function union_all(table) {
  2063. this.union(table, 'UNION ALL');
  2064. }
  2065. }, {
  2066. key: '_toParamString',
  2067. value: function _toParamString() {
  2068. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  2069. var totalStr = '',
  2070. totalValues = [];
  2071. var _iteratorNormalCompletion13 = true;
  2072. var _didIteratorError13 = false;
  2073. var _iteratorError13 = undefined;
  2074. try {
  2075. for (var _iterator13 = this._unions[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
  2076. var _step13$value = _step13.value;
  2077. var type = _step13$value.type;
  2078. var table = _step13$value.table;
  2079. totalStr = _pad(totalStr, this.options.separator);
  2080. var tableStr = void 0;
  2081. if (table instanceof cls.BaseBuilder) {
  2082. var ret = table._toParamString({
  2083. buildParameterized: options.buildParameterized,
  2084. nested: true
  2085. });
  2086. tableStr = ret.text;
  2087. totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
  2088. } else {
  2089. totalStr = this._formatTableName(table);
  2090. }
  2091. totalStr += type + ' ' + tableStr;
  2092. }
  2093. } catch (err) {
  2094. _didIteratorError13 = true;
  2095. _iteratorError13 = err;
  2096. } finally {
  2097. try {
  2098. if (!_iteratorNormalCompletion13 && _iterator13.return) {
  2099. _iterator13.return();
  2100. }
  2101. } finally {
  2102. if (_didIteratorError13) {
  2103. throw _iteratorError13;
  2104. }
  2105. }
  2106. }
  2107. return {
  2108. text: totalStr,
  2109. values: totalValues
  2110. };
  2111. }
  2112. }]);
  2113. return _class27;
  2114. }(cls.Block);
  2115. /*
  2116. # ---------------------------------------------------------------------------------------------------------
  2117. # ---------------------------------------------------------------------------------------------------------
  2118. # Query builders
  2119. # ---------------------------------------------------------------------------------------------------------
  2120. # ---------------------------------------------------------------------------------------------------------
  2121. */
  2122. /**
  2123. # Query builder base class
  2124. #
  2125. # Note that the query builder does not check the final query string for correctness.
  2126. #
  2127. # All the build methods in this object return the object instance for chained method calling purposes.
  2128. */
  2129. cls.QueryBuilder = function (_cls$BaseBuilder4) {
  2130. _inherits(_class28, _cls$BaseBuilder4);
  2131. /**
  2132. # Constructor
  2133. #
  2134. # blocks - array of cls.BaseBuilderBlock instances to build the query with.
  2135. */
  2136. function _class28(options, blocks) {
  2137. _classCallCheck(this, _class28);
  2138. var _this32 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class28).call(this, options));
  2139. _this32.blocks = blocks || [];
  2140. // Copy exposed methods into myself
  2141. var _iteratorNormalCompletion14 = true;
  2142. var _didIteratorError14 = false;
  2143. var _iteratorError14 = undefined;
  2144. try {
  2145. for (var _iterator14 = _this32.blocks[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
  2146. var block = _step14.value;
  2147. var exposedMethods = block.exposedMethods();
  2148. for (var methodName in exposedMethods) {
  2149. var methodBody = exposedMethods[methodName];
  2150. if (undefined !== _this32[methodName]) {
  2151. throw new Error('Builder already has a builder method called: ' + methodName);
  2152. }
  2153. (function (block, name, body) {
  2154. _this32[name] = function () {
  2155. for (var _len11 = arguments.length, args = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
  2156. args[_key11] = arguments[_key11];
  2157. }
  2158. body.call.apply(body, [block].concat(args));
  2159. return _this32;
  2160. };
  2161. })(block, methodName, methodBody);
  2162. }
  2163. }
  2164. } catch (err) {
  2165. _didIteratorError14 = true;
  2166. _iteratorError14 = err;
  2167. } finally {
  2168. try {
  2169. if (!_iteratorNormalCompletion14 && _iterator14.return) {
  2170. _iterator14.return();
  2171. }
  2172. } finally {
  2173. if (_didIteratorError14) {
  2174. throw _iteratorError14;
  2175. }
  2176. }
  2177. }
  2178. return _this32;
  2179. }
  2180. /**
  2181. # Register a custom value handler for this query builder and all its contained blocks.
  2182. #
  2183. # Note: This will override any globally registered handler for this value type.
  2184. */
  2185. _createClass(_class28, [{
  2186. key: 'registerValueHandler',
  2187. value: function registerValueHandler(type, handler) {
  2188. var _iteratorNormalCompletion15 = true;
  2189. var _didIteratorError15 = false;
  2190. var _iteratorError15 = undefined;
  2191. try {
  2192. for (var _iterator15 = this.blocks[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
  2193. var block = _step15.value;
  2194. block.registerValueHandler(type, handler);
  2195. }
  2196. } catch (err) {
  2197. _didIteratorError15 = true;
  2198. _iteratorError15 = err;
  2199. } finally {
  2200. try {
  2201. if (!_iteratorNormalCompletion15 && _iterator15.return) {
  2202. _iterator15.return();
  2203. }
  2204. } finally {
  2205. if (_didIteratorError15) {
  2206. throw _iteratorError15;
  2207. }
  2208. }
  2209. }
  2210. _get(Object.getPrototypeOf(_class28.prototype), 'registerValueHandler', this).call(this, type, handler);
  2211. return this;
  2212. }
  2213. /**
  2214. # Update query builder options
  2215. #
  2216. # This will update the options for all blocks too. Use this method with caution as it allows you to change the
  2217. # behaviour of your query builder mid-build.
  2218. */
  2219. }, {
  2220. key: 'updateOptions',
  2221. value: function updateOptions(options) {
  2222. this.options = _extend({}, this.options, options);
  2223. var _iteratorNormalCompletion16 = true;
  2224. var _didIteratorError16 = false;
  2225. var _iteratorError16 = undefined;
  2226. try {
  2227. for (var _iterator16 = this.blocks[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
  2228. var block = _step16.value;
  2229. block.options = _extend({}, block.options, options);
  2230. }
  2231. } catch (err) {
  2232. _didIteratorError16 = true;
  2233. _iteratorError16 = err;
  2234. } finally {
  2235. try {
  2236. if (!_iteratorNormalCompletion16 && _iterator16.return) {
  2237. _iterator16.return();
  2238. }
  2239. } finally {
  2240. if (_didIteratorError16) {
  2241. throw _iteratorError16;
  2242. }
  2243. }
  2244. }
  2245. }
  2246. // Get the final fully constructed query param obj.
  2247. }, {
  2248. key: '_toParamString',
  2249. value: function _toParamString() {
  2250. var _this33 = this,
  2251. _ref2;
  2252. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  2253. options = _extend({}, this.options, options);
  2254. var blockResults = this.blocks.map(function (b) {
  2255. return b._toParamString({
  2256. buildParameterized: options.buildParameterized,
  2257. queryBuilder: _this33
  2258. });
  2259. });
  2260. var blockTexts = blockResults.map(function (b) {
  2261. return b.text;
  2262. });
  2263. var blockValues = blockResults.map(function (b) {
  2264. return b.values;
  2265. });
  2266. var totalStr = blockTexts.filter(function (v) {
  2267. return 0 < v.length;
  2268. }).join(options.separator);
  2269. var totalValues = (_ref2 = []).concat.apply(_ref2, _toConsumableArray(blockValues));
  2270. if (!options.nested) {
  2271. if (options.numberedParameters) {
  2272. (function () {
  2273. var i = undefined !== options.numberedParametersStartAt ? options.numberedParametersStartAt : 1;
  2274. // construct regex for searching
  2275. var regex = options.parameterCharacter.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  2276. totalStr = totalStr.replace(new RegExp(regex, 'g'), function () {
  2277. return '' + options.numberedParametersPrefix + i++;
  2278. });
  2279. })();
  2280. }
  2281. }
  2282. return {
  2283. text: this._applyNestingFormatting(totalStr, !!options.nested),
  2284. values: totalValues
  2285. };
  2286. }
  2287. // Deep clone
  2288. }, {
  2289. key: 'clone',
  2290. value: function clone() {
  2291. var blockClones = this.blocks.map(function (v) {
  2292. return v.clone();
  2293. });
  2294. return new this.constructor(this.options, blockClones);
  2295. }
  2296. // Get a specific block
  2297. }, {
  2298. key: 'getBlock',
  2299. value: function getBlock(blockType) {
  2300. var filtered = this.blocks.filter(function (b) {
  2301. return b instanceof blockType;
  2302. });
  2303. return filtered[0];
  2304. }
  2305. }]);
  2306. return _class28;
  2307. }(cls.BaseBuilder);
  2308. // SELECT query builder.
  2309. cls.Select = function (_cls$QueryBuilder) {
  2310. _inherits(_class29, _cls$QueryBuilder);
  2311. function _class29(options) {
  2312. var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  2313. _classCallCheck(this, _class29);
  2314. blocks = blocks || [new cls.StringBlock(options, 'SELECT'), new cls.FunctionBlock(options), new cls.DistinctBlock(options), new cls.GetFieldBlock(options), new cls.FromTableBlock(options), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.GroupByBlock(options), new cls.HavingBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options), new cls.OffsetBlock(options), new cls.UnionBlock(options)];
  2315. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class29).call(this, options, blocks));
  2316. }
  2317. return _class29;
  2318. }(cls.QueryBuilder);
  2319. // UPDATE query builder.
  2320. cls.Update = function (_cls$QueryBuilder2) {
  2321. _inherits(_class30, _cls$QueryBuilder2);
  2322. function _class30(options) {
  2323. var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  2324. _classCallCheck(this, _class30);
  2325. blocks = blocks || [new cls.StringBlock(options, 'UPDATE'), new cls.UpdateTableBlock(options), new cls.SetFieldBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options)];
  2326. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class30).call(this, options, blocks));
  2327. }
  2328. return _class30;
  2329. }(cls.QueryBuilder);
  2330. // DELETE query builder.
  2331. cls.Delete = function (_cls$QueryBuilder3) {
  2332. _inherits(_class31, _cls$QueryBuilder3);
  2333. function _class31(options) {
  2334. var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  2335. _classCallCheck(this, _class31);
  2336. blocks = blocks || [new cls.StringBlock(options, 'DELETE'), new cls.TargetTableBlock(options), new cls.FromTableBlock(_extend({}, options, {
  2337. singleTable: true
  2338. })), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options)];
  2339. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class31).call(this, options, blocks));
  2340. }
  2341. return _class31;
  2342. }(cls.QueryBuilder);
  2343. // An INSERT query builder.
  2344. cls.Insert = function (_cls$QueryBuilder4) {
  2345. _inherits(_class32, _cls$QueryBuilder4);
  2346. function _class32(options) {
  2347. var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  2348. _classCallCheck(this, _class32);
  2349. blocks = blocks || [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.InsertFieldValueBlock(options), new cls.InsertFieldsFromQueryBlock(options)];
  2350. return _possibleConstructorReturn(this, Object.getPrototypeOf(_class32).call(this, options, blocks));
  2351. }
  2352. return _class32;
  2353. }(cls.QueryBuilder);
  2354. var _squel = {
  2355. VERSION: '5.3.3',
  2356. flavour: flavour,
  2357. expr: function expr(options) {
  2358. return new cls.Expression(options);
  2359. },
  2360. case: function _case(name, options) {
  2361. return new cls.Case(name, options);
  2362. },
  2363. select: function select(options, blocks) {
  2364. return new cls.Select(options, blocks);
  2365. },
  2366. update: function update(options, blocks) {
  2367. return new cls.Update(options, blocks);
  2368. },
  2369. insert: function insert(options, blocks) {
  2370. return new cls.Insert(options, blocks);
  2371. },
  2372. delete: function _delete(options, blocks) {
  2373. return new cls.Delete(options, blocks);
  2374. },
  2375. str: function str() {
  2376. var inst = new cls.FunctionBlock();
  2377. inst.function.apply(inst, arguments);
  2378. return inst;
  2379. },
  2380. registerValueHandler: cls.registerValueHandler
  2381. };
  2382. // aliases
  2383. _squel.remove = _squel.delete;
  2384. // classes
  2385. _squel.cls = cls;
  2386. return _squel;
  2387. }
  2388. /**
  2389. # ---------------------------------------------------------------------------------------------------------
  2390. # ---------------------------------------------------------------------------------------------------------
  2391. # Exported instance (and for use by flavour definitions further down).
  2392. # ---------------------------------------------------------------------------------------------------------
  2393. # ---------------------------------------------------------------------------------------------------------
  2394. */
  2395. var squel = _buildSquel();
  2396. /**
  2397. # ---------------------------------------------------------------------------------------------------------
  2398. # ---------------------------------------------------------------------------------------------------------
  2399. # Squel SQL flavours
  2400. # ---------------------------------------------------------------------------------------------------------
  2401. # ---------------------------------------------------------------------------------------------------------
  2402. */
  2403. // Available flavours
  2404. squel.flavours = {};
  2405. // Setup Squel for a particular SQL flavour
  2406. squel.useFlavour = function () {
  2407. var flavour = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
  2408. if (!flavour) {
  2409. return squel;
  2410. }
  2411. if (squel.flavours[flavour] instanceof Function) {
  2412. var s = _buildSquel(flavour);
  2413. squel.flavours[flavour].call(null, s);
  2414. // add in flavour methods
  2415. s.flavours = squel.flavours;
  2416. s.useFlavour = squel.useFlavour;
  2417. return s;
  2418. } else {
  2419. throw new Error('Flavour not available: ' + flavour);
  2420. }
  2421. };
  2422. return squel;
  2423. }));