@fxjs/sql-query
Advanced tools
Comparing version 0.6.0 to 0.6.1
v0.6.0 / 2019-10-22 | ||
v0.6.1 / 2019-10-24 | ||
================== | ||
* bugfix: fix type. | ||
* feat: support bigint | ||
v0.6.0 / 2019-10-22 | ||
=================== | ||
* Release v0.6.0 | ||
* feat: upgrade typo | ||
@@ -6,0 +13,0 @@ |
@@ -57,2 +57,4 @@ /// <reference types="@fibjs/types" /> | ||
break; | ||
case "bigint": | ||
return val.toString(); | ||
default: | ||
@@ -59,0 +61,0 @@ val = JSON.stringify(val); |
@@ -55,2 +55,4 @@ /// <reference types="@fibjs/types" /> | ||
return val(Dialect); | ||
case 'bigint': | ||
return val.toString(); | ||
} | ||
@@ -57,0 +59,0 @@ } |
@@ -66,2 +66,4 @@ var util = require("util"); | ||
break; | ||
case "bigint": | ||
return val.toString(); | ||
default: | ||
@@ -68,0 +70,0 @@ val = JSON.stringify(val); |
@@ -45,2 +45,4 @@ /// <reference path="../../@types/index.d.ts" /> | ||
break; | ||
case "bigint": | ||
return val.toString(); | ||
default: | ||
@@ -47,0 +49,0 @@ val = JSON.stringify(val); |
@@ -1,1 +0,1 @@ | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var util=_interopDefault(require("util")),vm=_interopDefault(require("vm")),path=_interopDefault(require("path")),uuid=_interopDefault(require("uuid")),fs=_interopDefault(require("fs")),os=_interopDefault(require("os")),url=_interopDefault(require("url")),tty=_interopDefault(require("tty")),events=_interopDefault(require("events")),assert=_interopDefault(require("assert")),crypto=_interopDefault(require("crypto"));function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var Helpers=createCommonjsModule(function(e,t){function r(e){return e.alias||e.a}Object.defineProperty(t,"__esModule",{value:!0}),t.escapeQuery=function(e,t,r){let s=0;return t.replace(/\?{1,2}/g,function(t){return"?"==t?e.escapeVal(r[s++]):"??"==t?e.escapeId(r[s++]):void 0})},t.dateToString=function(e,r,s){const n=new Date(e);if("local"!=r){const e=function(e){if("Z"==e)return 0;const t=e.match(/([\+\-\s])(\d\d):?(\d\d)?/);if(t)return("-"==t[1]?-1:1)*(parseInt(t[2],10)+(t[3]?parseInt(t[3],10):0)/60)*60;return!1}(r);n.setTime(n.getTime()+6e4*n.getTimezoneOffset()),!1!==e&&n.setTime(n.getTime()+6e4*e)}const i=n.getFullYear(),a=t.zeroPad(n.getMonth()+1),l=t.zeroPad(n.getDate()),o=t.zeroPad(n.getHours()),c=t.zeroPad(n.getMinutes()),u=t.zeroPad(n.getSeconds()),p=t.zeroPad(n.getMilliseconds(),3);return"mysql"==s.dialect||"local"==r?i+"-"+a+"-"+l+" "+o+":"+c+":"+u+"."+p:i+"-"+a+"-"+l+"T"+o+":"+c+":"+u+"."+p+"Z"},t.zeroPad=function(e,t=2){for(e=""+e;e.length<t;)e="0"+e;return e},t.get_table_alias=function(e,t){for(let s=0;s<e.from.length;s++)if(e.from[s].table==t)return r(e.from[s]);return t},t.parseTableInputStr=function(e){if(!e)throw"invalid input table_name!";let t=["",""];return t="string"==typeof e?(e=e.trim()).indexOf(" as ")>0?e.split(" as ").slice(0,2):e.split(" ").slice(0,2):e.slice(0,2)},t.pickAliasFromFromDescriptor=r,t.pickColumnAsFromSelectFieldsDescriptor=function(e){return e.as||e.a},t.autoIncreatementTableIndex=function(e){return e.length+1},t.defaultTableAliasNameRule=function(e){return`t${e}`},t.DialectTypes=["mysql","sqlite","mssql"],t.ucfirst=function(e=""){return e.length<=1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)},t.ensureNumber=function(e){return"number"!=typeof e&&(e=parseInt(e)),isNaN(e)?0:e},t.bufferToString=function(e,t){switch(t){case"mssql":case"mysql":case"sqlite":return"X'"+e.toString("hex")+"'";case"postgresql":return"'\\x"+e.toString("hex")+"'"}},t.escapeValForKnex=function(e,t,r){const s=typeof e;return"string"===s?e:"number"===s?e:"symbol"===s?null:"boolean"===s?t.DataTypes.isSQLITE?e?1:0:e:"function"===s?t.knex.raw(e(t)):e instanceof Date?e:Buffer.isBuffer(e)?e:e instanceof Array?e:null===e?e:void 0===e?null:t.escapeVal(e,r.timezone)},t.cutOffOrderDirectionFromColumnFirstStr=function(e){const t={col_name:e,direction:"ASC"};return"string"!=typeof e?t:("-"===e[0]&&(t.col_name=e.substr(1),t.direction="DESC"),t)}});unwrapExports(Helpers);var Helpers_1=Helpers.escapeQuery,Helpers_2=Helpers.dateToString,Helpers_3=Helpers.zeroPad,Helpers_4=Helpers.get_table_alias,Helpers_5=Helpers.parseTableInputStr,Helpers_6=Helpers.pickAliasFromFromDescriptor,Helpers_7=Helpers.pickColumnAsFromSelectFieldsDescriptor,Helpers_8=Helpers.autoIncreatementTableIndex,Helpers_9=Helpers.defaultTableAliasNameRule,Helpers_10=Helpers.DialectTypes,Helpers_11=Helpers.ucfirst,Helpers_12=Helpers.ensureNumber,Helpers_13=Helpers.bufferToString,Helpers_14=Helpers.escapeValForKnex,Helpers_15=Helpers.cutOffOrderDirectionFromColumnFirstStr,Create=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.CreateQuery=class{constructor(e){this.Dialect=e,this.tableName=null,this.structure={}}table(e){return this.tableName=e,this}field(e,t){return this.structure[e]=t,this}fields(e){return e?(this.structure=e,this):this.structure}build(){if(!this.tableName)return"";const e=this.structure;return this.Dialect.knex.schema.createTable(this.tableName,function(t){Object.keys(e).forEach(r=>{switch(e[r]){case"id":t.increments(r);break;case"int":t.integer(r);break;case"float":t.float(r,12,2);break;case"bool":t.specificType(r,"TINYINT(1)");break;case"text":t.text(r)}})}).toQuery()}}});unwrapExports(Create);var Create_1=Create.CreateQuery;function between(e,t){return createSpecialObject({from:e,to:t},"between")}function not_between(e,t){return createSpecialObject({from:e,to:t},"not_between")}function like(e){return createSpecialObject({expr:e},"like")}function not_like(e){return createSpecialObject({expr:e},"not_like")}function eq(e){return createSpecialObject({val:e},"eq")}function ne(e){return createSpecialObject({val:e},"ne")}function gt(e){return createSpecialObject({val:e},"gt")}function gte(e){return createSpecialObject({val:e},"gte")}function lt(e){return createSpecialObject({val:e},"lt")}function lte(e){return createSpecialObject({val:e},"lte")}function _in(e){return createSpecialObject({val:e},"in")}function not_in(e){return createSpecialObject({val:e},"not_in")}function createSpecialObject(e,t){return Object.defineProperty(e,"sql_comparator",{configurable:!1,enumerable:!1,value:function(){return t}}),e}var Comparators={between:between,not_between:not_between,like:like,not_like:not_like,eq:eq,ne:ne,gt:gt,gte:gte,lt:lt,lte:lte,in:_in,not_in:not_in},Where=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.build=function(e,t,r,s){if(0!==r.length)for(let n=0;n<r.length;n++)i(e,t,r[n],s)};const r=["or","and","not_or","not_and","not"],s="not_".length;function n(e){return e.indexOf("_")>=0}function i(e,t,h,g,d,_){if(g=g||{},h.exists)return void function(e,t,r,s){const n=r.exists.table_linked;e.whereExists(function(){if(this.select("*").from(r.exists.table),Array.isArray(r.exists.link_info[0])&&Array.isArray(r.exists.link_info[1])){const e=r.exists.link_info[0],s=r.exists.link_info[1];for(let r=0;r<e.length;r++)this.where(`${e[r]}`,t.knex.ref(s[r]).withSchema(n))}else{const[e,s]=r.exists.link_info;e&&s&&this.where(`${e}`,t.knex.ref(s).withSchema(n))}i(this,t,{table:null,wheres:r.wheres},s)})}(e,t,h,g);let y,m=[],b=y;for(let m in h.wheres){let q=h.wheres[m];if(null===q||void 0===q){e.whereNull(m);continue}if(m=m,q,r.indexOf(m)>=0){let r=m.toLocaleLowerCase();b=("not"==m?"and":n(m)?m.substr(s):m).toUpperCase();const l=q;let{nextOperator:o}=a(d),{nextOperator:c,conjunction:u,suffix:p}=a(r);"whereNot"===c&&(c=a("not",p,u).nextOperator),function(t){e[o].call(e,t)}(function(){const e=a(void 0,p,u).nextOperator;for(let r=0;r<l.length;r++){const s=l[r];this[c].call(this,function(){i(this,t,{table:h.table,wheres:s},g,null,{innerOperator:0===r?void 0:e})})}});continue}let{innerOperator:D="where"}=_||{};const x=l(t,h.table,m);let w=u(q,x,h.wheres)||q;if(c(w))switch(y=w.sql_comparator()){case"between":D=a(d,"between").nextOperator,e[D].call(e,x,[w.from,w.to]);break;case"not_between":D=a(d,"notBetween").nextOperator,e[D].call(e,x,[w.from,w.to]);break;case"like":D=D||a(d).nextOperator,e[D].call(e,x,"like",Helpers.escapeValForKnex(w.expr,t,g));break;case"not_like":D=D||a(d).nextOperator,e[D].call(e,x,"not like",Helpers.escapeValForKnex(w.expr,t,g));break;case"eq":case"ne":case"gt":case"gte":case"lt":case"lte":case"in":case"not_in":switch(y){case"eq":b=null===w.val?"IS":"=";break;case"ne":b=null===w.val?"IS NOT":"<>";break;case"gt":b=">";break;case"gte":b=">=";break;case"lt":b="<";break;case"lte":b="<=";break;case"in":b="IN";break;case"not_in":b="NOT IN"}f(y,w),D=D||a(d).nextOperator,e[D].call(e,x,b,Helpers.escapeValForKnex(w.val,t,g))}else if(p(m,w))for(let r=0;r<w.length;r++)e.whereRaw(o(t,w[r]));else if(Array.isArray(w))D=a(d,"in").nextOperator,e[D].call(e,x,Helpers.escapeValForKnex(w,t,g));else{const r=w;D=D||a(d).nextOperator,e[D].call(e,x,Helpers.escapeValForKnex(r,t,g))}}var q;return 0!==m.length&&m.join(" AND ")}function a(e,t,r){const s={nextOperator:"where",conjunction:"and",suffix:void 0,prefix:void 0};switch(e){case"not_and":case"not":s.nextOperator="whereNot",s.conjunction="and";break;case"and":s.nextOperator="where";break;case"or":s.nextOperator="orWhere",s.conjunction="or";break;case"not_or":s.nextOperator="whereNot",s.conjunction="or";break;default:s.nextOperator="where"}return(s.suffix=t)&&(s.nextOperator=`${s.nextOperator}${Helpers.ucfirst(t)}`),(s.prefix=r)&&(s.nextOperator=`${r}${Helpers.ucfirst(s.nextOperator)}`),s}function l(e,t,r){return t?e.knex.ref(r).withSchema(t):r}function o(e,t){return 1==t.length?t[0]:Helpers.escapeQuery(e,t[0],t[1])}function c(e){return"object"==typeof e&&("sql_comparator"in e&&"function"==typeof e.sql_comparator)}function u(e,t,r){if("object"!=typeof e)return!1;const s=Object.keys(e).find(e=>e in Comparators);if(!s)return!1;const n=e,i=n.modifiers=n.modifiers||{},a=Comparators[s];let l=n[s];const o=["not_in","in"].includes(s),c=Array.isArray(l);if(i.is_date){let e=c?l:[l];const t=e.map(e=>new Date(e)).filter(e=>e+""!="Invalid Date");t.length===e.length&&(e=t,l=c?e:e[0])}const u=c&&!o?l:[l],p=a.apply(null,u);return r[t]=p,p}function p(e,t){return"__sql"===e}function f(e,t){return!!~["in","not_in"].indexOf(e)}});unwrapExports(Where);var Where_1=Where.build,Select=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Helpers;function s(e){let{joinType:t=""}=e||{};switch(t=(t=(t||"").trim()).toUpperCase()){default:case"FULL":return"join";case"LEFT":case"LEFT INNER":return"leftJoin";case"LEFT OUTER JOIN":return"leftOuterJoin";case"RIGHT":case"RIGHT INNER":return"rightJoin";case"RIGHT OUTER":return"rightOuterJoin";case"FULL OUTER":return"fullOuterJoin";case"CROSS":return"crossJoin"}}function n(e,t,s,n,i){const a=r.pickAliasFromFromDescriptor(n);if(!t.func_name&&t.column_name){const s=t.column_name,n=r.pickColumnAsFromSelectFieldsDescriptor(t);n?e.select(this.Dialect.knex.ref(s).as(n)):e.select(s)}if(t.having,t.select&&e.select(t.select),t.func_name){let n="",i=null;t.column_name&&(i=Array.isArray(t.column_name)?t.column_name:[t.column_name]),Array.isArray(i)&&i.length&&(n+=i.map(e=>{if(!e)return this.Dialect.escapeVal(e);if("object"==typeof e&&"function"==typeof e.type)switch(e.type()){case"text":return this.Dialect.escapeVal(e.data,this.opts.timezone);default:return e}else if("string"!=typeof e)return e;return s?this.Dialect.escapeId(e):this.Dialect.escapeId(a,e)}).join(", ")),n||(n="*"),n?n=`${t.func_name}(${n})`:n+=`${t.func_name}(*)`,t.func_stack&&t.func_stack.length>0&&(n=t.func_stack.join("(")+"("+n+Array(t.func_stack.length+1).join(")"));const l=r.pickColumnAsFromSelectFieldsDescriptor(t);l&&(n+=` as ${this.Dialect.escapeId(l)}`),e.select(this.Dialect.knex.raw(n))}else if(t.sql){const s=r.pickColumnAsFromSelectFieldsDescriptor(t),n=this.Dialect.knex.raw(`${t.sql}${s?` as ${this.Dialect.escapeId(s)}`:""}`);e.select(n)}return{should_continue:!1,return_value:""}}t.SelectQuery=class{constructor(e,t){this.opts=t,this.sql={from:[],where:[],order:[],group_by:null,found_rows:!1,where_exists:!1},this._aggregation_functions={},this.fun_stack=[],this.Dialect=e}get_aggregate_fun(e){return this._aggregation_functions[e]?this._aggregation_functions[e]:this._aggregation_functions[e]=((...t)=>{if(e=e.toUpperCase(),0===t.length)return this.fun_stack.push(e),this;var r=t.length>1&&"string"==typeof t[t.length-1]?t.pop():null;return t.length&&Array.isArray(t[0])&&(t=t[0].concat(t.slice(1))),this.fun(e,t.length&&t[0]?t:"*",r)})}select(e){if(e){const t=this.sql.from[this.sql.from.length-1];t.select&&Array.isArray(t.select)||(t.select=[]),this.sql.from[this.sql.from.length-1].select=t.select.concat(Array.isArray(e)?e:Array.prototype.slice.apply(arguments))}return this}calculateFoundRows(){return this.sql.found_rows=!0,this}as(e){var t=this.sql.from.length-1;if(Array.isArray(this.sql.from[t].select)){const s=this.sql.from[t].select;var r=s.length-1;"string"==typeof s[r]&&(s[r]={column_name:s[r]}),s[s.length-1].as=e||null}return this}fun(e,t,r){return Array.isArray(this.sql.from[this.sql.from.length-1].select)||(this.sql.from[this.sql.from.length-1].select=[]),this.sql.from[this.sql.from.length-1].select.push({func_name:e.toUpperCase(),column_name:t&&"*"!=t?t:null,as:r||null,func_stack:this.fun_stack}),this.fun_stack=[],this}from(e,t,s,n,i){const[a,l]=r.parseTableInputStr(e),o={table:a,alias:l||r.defaultTableAliasNameRule(r.autoIncreatementTableIndex(this.sql.from))};if(0===this.sql.from.length)return this.sql.from.push(o),this;let c;const u=Array.prototype.slice.call(arguments),p=u[u.length-1];if("object"!=typeof p||Array.isArray(p)||(i=u.pop(),o.opts=i),3==u.length)c=r.pickAliasFromFromDescriptor(this.sql.from[this.sql.from.length-1]),n=s;else{const[e,t]=r.parseTableInputStr(s);c=t||Helpers.get_table_alias(this.sql,e)}if(o.joins=[],!t.length||!n.length)throw new Error("[SQL-QUERY] both from_id & to_id cannot be empty!");if(Array.isArray(t)&&Array.isArray(n)&&t.length==n.length)for(let e=0;e<t.length;e++)o.joins.push([t[e],c,n[e]]);else o.joins.push([t,c,n]);return this.sql.from.push(o),this}where(...e){var t=null;const r=()=>{null!==t&&this.sql.where.push(t)};for(let s=0;s<e.length;s++)if(null!==e[s])if("string"==typeof e[s]){const n=e[s];r(),t={table:Helpers.get_table_alias(this.sql,n),wheres:e[s+1]},s++}else r(),t={table:null,wheres:e[s]};return r(),t=null,this}whereExists(e,t,s,n){return this.sql.where.push({table:this.sql.from.length?r.pickAliasFromFromDescriptor(this.sql.from[this.sql.from.length-1]):null,wheres:n,exists:{table:e,table_linked:Helpers.get_table_alias(this.sql,t),link_info:s}}),this.sql.where_exists=!0,this}groupBy(...e){return this.sql.group_by=e,this}offset(e){return this.sql.offset=e,this}limit(e){return this.sql.limit=e,this}order(e,t){if(Array.isArray(t))this.sql.order.push(r.escapeQuery(this.Dialect,e,t));else{let s=Array.isArray(e)?e[1]:e,n=null;const{direction:i,col_name:a}=r.cutOffOrderDirectionFromColumnFirstStr(s);n=i,s=a,t&&(n="Z"===t?"DESC":"ASC"),this.sql.order.push({c:Array.isArray(e)?[Helpers.get_table_alias(this.sql,e[0]),s]:s,d:n})}return this}build(){const e=[],t=this.sql.from;this.fun_stack.length&&this.fun(this.fun_stack.pop());const i={};for(let e=0;e<t.length;e++)t[e].alias=r.pickAliasFromFromDescriptor(t[e])||r.defaultTableAliasNameRule(e+1),i[`${t[e].alias}`]=`${t[e].table}`;const a=1===t.length,l=this.Dialect.knex(i);for(let r=0;r<t.length;r++)if(t[r].select)for(let s=0;s<t[r].select.length;s++){const i=t[r],o=i.select[s],c=a?"":`${i.alias}.`;if("string"!=typeof o){if("object"==typeof o){const{should_continue:t}=n.apply(this,[l,o,a,i,e]);if(t)continue}else if("function"==typeof o){const e=o(this.Dialect);l.select(this.Dialect.knex.raw(e));continue}}else l.select(`${c}${o}`)}if(t.length>0){t.length;const e=1==t.length&&!this.sql.where_exists;for(let n=0,i=!1;n<t.length;n++){const a=t[n];if(e)l.from(a.table);else if(i){const e={},t=r.pickAliasFromFromDescriptor(a)||a.table;a.joins.forEach(r=>{e[`${t}.${r[0]}`]=`${r[1]}.${r[2]}`}),l[s(a.opts)](`${a.table} as ${r.pickAliasFromFromDescriptor(a)}`,e)}else l.from(`${a.table} as ${r.pickAliasFromFromDescriptor(a)}`);i=!0}}if(Where.build(l,this.Dialect,this.sql.where,this.opts),null!==this.sql.group_by){const e=this.sql.group_by.map(e=>{if("-"==e[0]){const t=e.substr(1);return this.sql.order.unshift({c:t,d:"DESC"}),t}return e});l.groupBy(e)}let o;if(this.sql.order.length>0)for(let e=0;e<this.sql.order.length;e++)if("object"==typeof(o=this.sql.order[e]))if(Array.isArray(o.c)){if(2!==o.c.length)throw"invalid order item input!";l.orderBy(this.Dialect.knex.ref(o.c[1]).withSchema(o.c[0]),o.d)}else l.orderBy(o.c,o.d);else"string"==typeof o&&l.orderByRaw(o);this.Dialect.limitAsTop||(this.sql.hasOwnProperty("limit")?(this.sql.hasOwnProperty("offset")&&l.offset(r.ensureNumber(this.sql.offset)),l.limit(r.ensureNumber(this.sql.limit))):this.sql.hasOwnProperty("offset")&&l.offset(r.ensureNumber(this.sql.offset)));const c=l.toQuery();return this.sql.found_rows?c.replace("select ","select SQL_CALC_FOUND_ROWS "):c}abs(...e){return this.get_aggregate_fun("ABS")(...e)}ceil(...e){return this.get_aggregate_fun("CEIL")(...e)}floor(...e){return this.get_aggregate_fun("FLOOR")(...e)}round(...e){return this.get_aggregate_fun("ROUND")(...e)}avg(...e){return this.get_aggregate_fun("AVG")(...e)}min(...e){return this.get_aggregate_fun("MIN")(...e)}max(...e){return this.get_aggregate_fun("MAX")(...e)}log(...e){return this.get_aggregate_fun("LOG")(...e)}log2(...e){return this.get_aggregate_fun("LOG2")(...e)}log10(...e){return this.get_aggregate_fun("LOG10")(...e)}exp(...e){return this.get_aggregate_fun("EXP")(...e)}power(...e){return this.get_aggregate_fun("POWER")(...e)}acos(...e){return this.get_aggregate_fun("ACOS")(...e)}asin(...e){return this.get_aggregate_fun("ASIN")(...e)}atan(...e){return this.get_aggregate_fun("ATAN")(...e)}cos(...e){return this.get_aggregate_fun("COS")(...e)}sin(...e){return this.get_aggregate_fun("SIN")(...e)}tan(...e){return this.get_aggregate_fun("TAN")(...e)}conv(...e){return this.get_aggregate_fun("CONV")(...e)}random(...e){return this.get_aggregate_fun("RANDOM")(...e)}rand(...e){return this.get_aggregate_fun("RAND")(...e)}radians(...e){return this.get_aggregate_fun("RADIANS")(...e)}degrees(...e){return this.get_aggregate_fun("DEGREES")(...e)}sum(...e){return this.get_aggregate_fun("SUM")(...e)}count(...e){return this.get_aggregate_fun("COUNT")(...e)}distinct(...e){return this.get_aggregate_fun("DISTINCT")(...e)}}});unwrapExports(Select);var Select_1=Select.SelectQuery,Insert=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.InsertQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={}}into(e){return this.sql.table=e,this}set(e){return this.sql.set=e,this}build(){const e=this.Dialect.knex(this.sql.table),t={};if(this.sql.hasOwnProperty("set")){let r=null;for(let e in this.sql.set)r=Helpers.escapeValForKnex(this.sql.set[e],this.Dialect,this.opts),t[e]=r;e.insert(t)}return e.toQuery()}}});unwrapExports(Insert);var Insert_1=Insert.InsertQuery,_Set=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.build=function(e,t,r,s){if(s=s||{},!r||0===r.length)return;const n={};for(let e in r)n[e]=Helpers.escapeValForKnex(r[e],this.Dialect,s);e.update(n)}});unwrapExports(_Set);var _Set_1=_Set.build,Update=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.UpdateQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={where:[]}}into(e){return this.sql.table=e,this}set(e){return this.sql.set=e,this}where(...e){for(let t=0;t<e.length;t++)this.sql.where.push({table:null,wheres:e[t]});return this}build(){const e=this.Dialect.knex(this.sql.table);return _Set.build(e,this.Dialect,this.sql.set,this.opts),Where.build(e,this.Dialect,this.sql.where,this.opts),e.toQuery()}}});unwrapExports(Update);var Update_1=Update.UpdateQuery,Remove=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.RemoveQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={where:[],order:[]}}from(e){return this.sql.table=e,this}where(...e){for(let t=0;t<e.length;t++)this.sql.where.push({table:null,wheres:e[t]});return this}build(){var e=[];const t=this.Dialect.knex(this.sql.table);Where.build(t,this.Dialect,this.sql.where,this.opts),t.del();const r=[t.toQuery()];if(this.sql.order.length>0){const t=this.sql.order,s=[];for(let e=0;e<t.length;e++){const r=t[e].c,n=t[e].d;Array.isArray(r)?s.push(this.Dialect.escapeId.apply(this.Dialect,r)+" "+n):s.push(this.Dialect.escapeId(r)+" "+n)}s.length>0&&(e.push("ORDER BY "+s.join(", ")),r.push(util.last(e)))}return this.Dialect.limitAsTop?this.sql.hasOwnProperty("limit")&&r[0].replace("delete from",`delete top ${this.sql.limit}`):this.sql.hasOwnProperty("limit")?(this.sql.hasOwnProperty("offset")?e.push("LIMIT "+this.sql.limit+" OFFSET "+this.sql.offset):e.push("LIMIT "+this.sql.limit),r.push(util.last(e))):this.sql.hasOwnProperty("offset")&&(e.push("OFFSET "+this.sql.offset),t.offset(this.sql.offset),r.push(util.last(e))),r.join(" ")}offset(e){return this.sql.offset=e,this}limit(e){return this.sql.limit=e,this}order(e,t){return this.sql.order.push({c:Array.isArray(e)?[Helpers.get_table_alias(this.sql,e[0]),e[1]]:e,d:"Z"==t?"DESC":"ASC"}),this}}});unwrapExports(Remove);var Remove_1=Remove.RemoveQuery;const DataTypes={id:"INTEGER PRIMARY KEY AUTO_INCREMENT",int:"INTEGER",float:"FLOAT(12,2)",bool:"TINYINT(1)",text:"TEXT"};function escape(e,t){return Helpers.escapeQuery(Dialect,e,t)}function escapeId(...e){return e.map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(t){return"?:id"==t?escapeId(e.escapes.shift()):escapeVal(e.escapes.shift())}):"`"+e.replace(/`/g,"``")+"`"}).join(".")}function escapeVal(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"mysql");if(Array.isArray(e))return arrayToList(e,t||"local");if(util.isDate(e))e=Helpers.dateToString(e,t||"local",{dialect:"mysql"});else switch(typeof e){case"boolean":return e?"true":"false";case"number":if(!isFinite(e)){e=e.toString();break}return e+"";case"object":return objectToValues(e,t||"Z");case"function":return e(Dialect)}return"'"+(e=e.replace(/[\0\n\r\b\t\\\'\"\x1a]/g,function(e){switch(e){case"\0":return"\\0";case"\n":return"\\n";case"\r":return"\\r";case"\b":return"\\b";case"\t":return"\\t";case"":return"\\Z";default:return"\\"+e}}))+"'"}function objectToValues(e,t){var r=[];for(var s in e){var n=e[s];"function"!=typeof n&&r.push(escapeId(s)+" = "+escapeVal(n,t))}return r.join(", ")}function arrayToList(e,t){return"("+e.map(function(e){return Array.isArray(e)?arrayToList(e):escapeVal(e,t)}).join(", ")+")"}const Dialect={type:"mysql",DataTypes:DataTypes,escape:escape,escapeId:escapeId,escapeVal:escapeVal,limitAsTop:!1,knex:null};var mysql=Dialect,postgresql=createCommonjsModule(function(e,t){t.DataTypes={id:"SERIAL PRIMARY KEY",int:"INTEGER",float:"REAL",bool:"SMALLINT",text:"TEXT"},t.type="postgresql",t.escape=function(e,r){return Helpers.escapeQuery(t,e,r)},t.escapeId=function(){return Array.prototype.slice.apply(arguments).map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(r){return"?:id"==r?t.escapeId(e.escapes.shift()):t.escapeVal(e.escapes.shift())}):e.split(".").map(function(e){return'"'+e.replace(/\"/g,'""')+'"'}).join(".")}).join(".")},t.escapeVal=function(e,r){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(t.escapeVal.bind(this))+")":"("+e.map(t.escapeVal.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,r||"local",{dialect:"postgresql"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"postgresql");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?"true":"false";case"function":return e(t);case"string":break;default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"},t.defaultValuesStmt="DEFAULT VALUES"}),postgresql_1=postgresql.DataTypes,postgresql_2=postgresql.type,postgresql_3=postgresql.escape,postgresql_4=postgresql.escapeId,postgresql_5=postgresql.escapeVal,postgresql_6=postgresql.defaultValuesStmt;const DataTypes$1={isSQLITE:!0,id:"INTEGER PRIMARY KEY AUTOINCREMENT",int:"INTEGER",float:"FLOAT(12,2)",bool:"TINYINT(1)",text:"TEXT"};function escape$1(e,t){return Helpers.escapeQuery(Dialect$1,e,t)}const escapeId$1=mysql.escapeId;function escapeVal$1(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(escapeVal$1.bind(this))+")":"("+e.map(escapeVal$1.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,t||"local",{dialect:"sqlite"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"sqlite");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?1:0;case"function":return e(Dialect$1);case"string":break;default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"}const Dialect$1={type:"sqlite",DataTypes:DataTypes$1,escape:escape$1,escapeId:escapeId$1,escapeVal:escapeVal$1,limitAsTop:!1,knex:null};var sqlite=Dialect$1;const DataTypes$2={id:"INT IDENTITY(1,1) NOT NULL PRIMARY KEY",int:"INT",float:"FLOAT",bool:"BIT",text:"TEXT"},escape$2=function(e,t){return Helpers.escapeQuery(Dialect$2,e,t)};function escapeId$2(...e){return e.map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(t){return"?:id"==t?escapeId$2(e.escapes.shift()):escapeVal$2(e.escapes.shift())}):"["+e+"]"}).join(".")}const escapeVal$2=function(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(escapeVal$2.bind(this))+")":"("+e.map(escapeVal$2.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,t||"local",{dialect:"mssql"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"mssql");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?1:0;case"function":return e(Dialect$2);case"string":break;default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"},Dialect$2={type:"mssql",DataTypes:DataTypes$2,escape:escape$2,escapeId:escapeId$2,escapeVal:escapeVal$2,limitAsTop:!0,knex:null};var mssql=Dialect$2,Dialects=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.mysql=mysql,t.postgresql=postgresql,t.sqlite=sqlite,t.mssql=mssql});unwrapExports(Dialects);var Dialects_1=Dialects.mysql,Dialects_2=Dialects.postgresql,Dialects_3=Dialects.sqlite,Dialects_4=Dialects.mssql,sandbox=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});path.resolve(__dirname,"../");t.default=class extends vm.SandBox{constructor(){const[e={},t=function(){},r]=Array.prototype.slice.apply(arguments);super(Object.assign({},e,{fs:fs,path:path,os:os,url:url,tty:tty,util:util,events:events,assert:assert,crypto:crypto}),t,r),function(){this.add({uuid:{v4:()=>uuid.snowflake()}})}.call(this)}}});unwrapExports(sandbox);const sandbox$1=new sandbox.default,OKnex=sandbox$1.require("knex",__dirname);OKnex.SandBox=sandbox.default;var lib=OKnex,Query_1=createCommonjsModule(function(e,t){var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Helpers=Helpers,t.Dialects=Dialects,t.comparators=Comparators,t.Text=(r="text",function(e){var t={data:e};return Object.defineProperty(t,"type",{value:function(){return r},enumerable:!1}),t});t.Query=class{constructor(e){this._fns={};let r=null;if("string"==typeof e){if(!Helpers.DialectTypes.includes(e))throw`invalid dialect type ${e}`;r={dialect:e}}else r=e||{};this.opts=r,r.dialect=r.dialect||"mysql",function(e){const t=lib;this.Dialect=util.extend({},e),Object.defineProperty(this.Dialect,"knex",{value:t({client:this.Dialect.type,useNullAsDefault:!0}),writable:!1,configurable:!1}),Object.defineProperty(this,"knex",{value:this.Dialect.knex,writable:!1,configurable:!1})}.call(this,t.Dialects[r.dialect]),this.escape=this._proxyFn("escape"),this.escapeId=this._proxyFn("escapeId"),this.escapeVal=this._proxyFn("escapeVal")}_proxyFn(e){if(!this._fns[e])switch(e){case"escape":this._fns[e]=t.Helpers.escapeQuery.bind(t.Helpers,this.Dialect);break;case"escapeId":this._fns[e]=this.Dialect.escapeId.bind(this.Dialect);break;case"escapeVal":this._fns[e]=this.Dialect.escapeVal.bind(this.Dialect)}return this._fns[e]}create(){return new Create.CreateQuery(this.Dialect)}select(){return new Select.SelectQuery(this.Dialect,this.opts)}insert(){return new Insert.InsertQuery(this.Dialect,this.opts)}update(){return new Update.UpdateQuery(this.Dialect,this.opts)}remove(){return new Remove.RemoveQuery(this.Dialect,this.opts)}}}),Query=unwrapExports(Query_1),Query_2=Query_1.Helpers,Query_3=Query_1.Dialects,Query_4=Query_1.comparators,Query_5=Query_1.Text,Query_6=Query_1.Query;exports.Dialects=Query_3,exports.Helpers=Query_2,exports.Query=Query_6,exports.Text=Query_5,exports.comparators=Query_4,exports.default=Query; | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var util=_interopDefault(require("util")),vm=_interopDefault(require("vm")),path=_interopDefault(require("path")),uuid=_interopDefault(require("uuid")),fs=_interopDefault(require("fs")),os=_interopDefault(require("os")),url=_interopDefault(require("url")),tty=_interopDefault(require("tty")),events=_interopDefault(require("events")),assert=_interopDefault(require("assert")),crypto=_interopDefault(require("crypto"));function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var Helpers=createCommonjsModule(function(e,t){function r(e){return e.alias||e.a}Object.defineProperty(t,"__esModule",{value:!0}),t.escapeQuery=function(e,t,r){let s=0;return t.replace(/\?{1,2}/g,function(t){return"?"==t?e.escapeVal(r[s++]):"??"==t?e.escapeId(r[s++]):void 0})},t.dateToString=function(e,r,s){const n=new Date(e);if("local"!=r){const e=function(e){if("Z"==e)return 0;const t=e.match(/([\+\-\s])(\d\d):?(\d\d)?/);if(t)return("-"==t[1]?-1:1)*(parseInt(t[2],10)+(t[3]?parseInt(t[3],10):0)/60)*60;return!1}(r);n.setTime(n.getTime()+6e4*n.getTimezoneOffset()),!1!==e&&n.setTime(n.getTime()+6e4*e)}const i=n.getFullYear(),a=t.zeroPad(n.getMonth()+1),l=t.zeroPad(n.getDate()),o=t.zeroPad(n.getHours()),c=t.zeroPad(n.getMinutes()),u=t.zeroPad(n.getSeconds()),p=t.zeroPad(n.getMilliseconds(),3);return"mysql"==s.dialect||"local"==r?i+"-"+a+"-"+l+" "+o+":"+c+":"+u+"."+p:i+"-"+a+"-"+l+"T"+o+":"+c+":"+u+"."+p+"Z"},t.zeroPad=function(e,t=2){for(e=""+e;e.length<t;)e="0"+e;return e},t.get_table_alias=function(e,t){for(let s=0;s<e.from.length;s++)if(e.from[s].table==t)return r(e.from[s]);return t},t.parseTableInputStr=function(e){if(!e)throw"invalid input table_name!";let t=["",""];return t="string"==typeof e?(e=e.trim()).indexOf(" as ")>0?e.split(" as ").slice(0,2):e.split(" ").slice(0,2):e.slice(0,2)},t.pickAliasFromFromDescriptor=r,t.pickColumnAsFromSelectFieldsDescriptor=function(e){return e.as||e.a},t.autoIncreatementTableIndex=function(e){return e.length+1},t.defaultTableAliasNameRule=function(e){return`t${e}`},t.DialectTypes=["mysql","sqlite","mssql"],t.ucfirst=function(e=""){return e.length<=1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)},t.ensureNumber=function(e){return"number"!=typeof e&&(e=parseInt(e)),isNaN(e)?0:e},t.bufferToString=function(e,t){switch(t){case"mssql":case"mysql":case"sqlite":return"X'"+e.toString("hex")+"'";case"postgresql":return"'\\x"+e.toString("hex")+"'"}},t.escapeValForKnex=function(e,t,r){const s=typeof e;return"string"===s?e:"number"===s?e:"symbol"===s?null:"boolean"===s?t.DataTypes.isSQLITE?e?1:0:e:"function"===s?t.knex.raw(e(t)):e instanceof Date?e:Buffer.isBuffer(e)?e:e instanceof Array?e:null===e?e:void 0===e?null:t.escapeVal(e,r.timezone)},t.cutOffOrderDirectionFromColumnFirstStr=function(e){const t={col_name:e,direction:"ASC"};return"string"!=typeof e?t:("-"===e[0]&&(t.col_name=e.substr(1),t.direction="DESC"),t)}});unwrapExports(Helpers);var Helpers_1=Helpers.escapeQuery,Helpers_2=Helpers.dateToString,Helpers_3=Helpers.zeroPad,Helpers_4=Helpers.get_table_alias,Helpers_5=Helpers.parseTableInputStr,Helpers_6=Helpers.pickAliasFromFromDescriptor,Helpers_7=Helpers.pickColumnAsFromSelectFieldsDescriptor,Helpers_8=Helpers.autoIncreatementTableIndex,Helpers_9=Helpers.defaultTableAliasNameRule,Helpers_10=Helpers.DialectTypes,Helpers_11=Helpers.ucfirst,Helpers_12=Helpers.ensureNumber,Helpers_13=Helpers.bufferToString,Helpers_14=Helpers.escapeValForKnex,Helpers_15=Helpers.cutOffOrderDirectionFromColumnFirstStr,Create=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.CreateQuery=class{constructor(e){this.Dialect=e,this.tableName=null,this.structure={}}table(e){return this.tableName=e,this}field(e,t){return this.structure[e]=t,this}fields(e){return e?(this.structure=e,this):this.structure}build(){if(!this.tableName)return"";const e=this.structure;return this.Dialect.knex.schema.createTable(this.tableName,function(t){Object.keys(e).forEach(r=>{switch(e[r]){case"id":t.increments(r);break;case"int":t.integer(r);break;case"float":t.float(r,12,2);break;case"bool":t.specificType(r,"TINYINT(1)");break;case"text":t.text(r)}})}).toQuery()}}});unwrapExports(Create);var Create_1=Create.CreateQuery;function between(e,t){return createSpecialObject({from:e,to:t},"between")}function not_between(e,t){return createSpecialObject({from:e,to:t},"not_between")}function like(e){return createSpecialObject({expr:e},"like")}function not_like(e){return createSpecialObject({expr:e},"not_like")}function eq(e){return createSpecialObject({val:e},"eq")}function ne(e){return createSpecialObject({val:e},"ne")}function gt(e){return createSpecialObject({val:e},"gt")}function gte(e){return createSpecialObject({val:e},"gte")}function lt(e){return createSpecialObject({val:e},"lt")}function lte(e){return createSpecialObject({val:e},"lte")}function _in(e){return createSpecialObject({val:e},"in")}function not_in(e){return createSpecialObject({val:e},"not_in")}function createSpecialObject(e,t){return Object.defineProperty(e,"sql_comparator",{configurable:!1,enumerable:!1,value:function(){return t}}),e}var Comparators={between:between,not_between:not_between,like:like,not_like:not_like,eq:eq,ne:ne,gt:gt,gte:gte,lt:lt,lte:lte,in:_in,not_in:not_in},Where=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.build=function(e,t,r,s){if(0!==r.length)for(let n=0;n<r.length;n++)i(e,t,r[n],s)};const r=["or","and","not_or","not_and","not"],s="not_".length;function n(e){return e.indexOf("_")>=0}function i(e,t,h,g,d,_){if(g=g||{},h.exists)return void function(e,t,r,s){const n=r.exists.table_linked;e.whereExists(function(){if(this.select("*").from(r.exists.table),Array.isArray(r.exists.link_info[0])&&Array.isArray(r.exists.link_info[1])){const e=r.exists.link_info[0],s=r.exists.link_info[1];for(let r=0;r<e.length;r++)this.where(`${e[r]}`,t.knex.ref(s[r]).withSchema(n))}else{const[e,s]=r.exists.link_info;e&&s&&this.where(`${e}`,t.knex.ref(s).withSchema(n))}i(this,t,{table:null,wheres:r.wheres},s)})}(e,t,h,g);let y,m=[],b=y;for(let m in h.wheres){let q=h.wheres[m];if(null===q||void 0===q){e.whereNull(m);continue}if(m=m,q,r.indexOf(m)>=0){let r=m.toLocaleLowerCase();b=("not"==m?"and":n(m)?m.substr(s):m).toUpperCase();const l=q;let{nextOperator:o}=a(d),{nextOperator:c,conjunction:u,suffix:p}=a(r);"whereNot"===c&&(c=a("not",p,u).nextOperator),function(t){e[o].call(e,t)}(function(){const e=a(void 0,p,u).nextOperator;for(let r=0;r<l.length;r++){const s=l[r];this[c].call(this,function(){i(this,t,{table:h.table,wheres:s},g,null,{innerOperator:0===r?void 0:e})})}});continue}let{innerOperator:D="where"}=_||{};const x=l(t,h.table,m);let w=u(q,x,h.wheres)||q;if(c(w))switch(y=w.sql_comparator()){case"between":D=a(d,"between").nextOperator,e[D].call(e,x,[w.from,w.to]);break;case"not_between":D=a(d,"notBetween").nextOperator,e[D].call(e,x,[w.from,w.to]);break;case"like":D=D||a(d).nextOperator,e[D].call(e,x,"like",Helpers.escapeValForKnex(w.expr,t,g));break;case"not_like":D=D||a(d).nextOperator,e[D].call(e,x,"not like",Helpers.escapeValForKnex(w.expr,t,g));break;case"eq":case"ne":case"gt":case"gte":case"lt":case"lte":case"in":case"not_in":switch(y){case"eq":b=null===w.val?"IS":"=";break;case"ne":b=null===w.val?"IS NOT":"<>";break;case"gt":b=">";break;case"gte":b=">=";break;case"lt":b="<";break;case"lte":b="<=";break;case"in":b="IN";break;case"not_in":b="NOT IN"}f(y,w),D=D||a(d).nextOperator,e[D].call(e,x,b,Helpers.escapeValForKnex(w.val,t,g))}else if(p(m,w))for(let r=0;r<w.length;r++)e.whereRaw(o(t,w[r]));else if(Array.isArray(w))D=a(d,"in").nextOperator,e[D].call(e,x,Helpers.escapeValForKnex(w,t,g));else{const r=w;D=D||a(d).nextOperator,e[D].call(e,x,Helpers.escapeValForKnex(r,t,g))}}var q;return 0!==m.length&&m.join(" AND ")}function a(e,t,r){const s={nextOperator:"where",conjunction:"and",suffix:void 0,prefix:void 0};switch(e){case"not_and":case"not":s.nextOperator="whereNot",s.conjunction="and";break;case"and":s.nextOperator="where";break;case"or":s.nextOperator="orWhere",s.conjunction="or";break;case"not_or":s.nextOperator="whereNot",s.conjunction="or";break;default:s.nextOperator="where"}return(s.suffix=t)&&(s.nextOperator=`${s.nextOperator}${Helpers.ucfirst(t)}`),(s.prefix=r)&&(s.nextOperator=`${r}${Helpers.ucfirst(s.nextOperator)}`),s}function l(e,t,r){return t?e.knex.ref(r).withSchema(t):r}function o(e,t){return 1==t.length?t[0]:Helpers.escapeQuery(e,t[0],t[1])}function c(e){return"object"==typeof e&&("sql_comparator"in e&&"function"==typeof e.sql_comparator)}function u(e,t,r){if("object"!=typeof e)return!1;const s=Object.keys(e).find(e=>e in Comparators);if(!s)return!1;const n=e,i=n.modifiers=n.modifiers||{},a=Comparators[s];let l=n[s];const o=["not_in","in"].includes(s),c=Array.isArray(l);if(i.is_date){let e=c?l:[l];const t=e.map(e=>new Date(e)).filter(e=>e+""!="Invalid Date");t.length===e.length&&(e=t,l=c?e:e[0])}const u=c&&!o?l:[l],p=a.apply(null,u);return r[t]=p,p}function p(e,t){return"__sql"===e}function f(e,t){return!!~["in","not_in"].indexOf(e)}});unwrapExports(Where);var Where_1=Where.build,Select=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Helpers;function s(e){let{joinType:t=""}=e||{};switch(t=(t=(t||"").trim()).toUpperCase()){default:case"FULL":return"join";case"LEFT":case"LEFT INNER":return"leftJoin";case"LEFT OUTER JOIN":return"leftOuterJoin";case"RIGHT":case"RIGHT INNER":return"rightJoin";case"RIGHT OUTER":return"rightOuterJoin";case"FULL OUTER":return"fullOuterJoin";case"CROSS":return"crossJoin"}}function n(e,t,s,n,i){const a=r.pickAliasFromFromDescriptor(n);if(!t.func_name&&t.column_name){const s=t.column_name,n=r.pickColumnAsFromSelectFieldsDescriptor(t);n?e.select(this.Dialect.knex.ref(s).as(n)):e.select(s)}if(t.having,t.select&&e.select(t.select),t.func_name){let n="",i=null;t.column_name&&(i=Array.isArray(t.column_name)?t.column_name:[t.column_name]),Array.isArray(i)&&i.length&&(n+=i.map(e=>{if(!e)return this.Dialect.escapeVal(e);if("object"==typeof e&&"function"==typeof e.type)switch(e.type()){case"text":return this.Dialect.escapeVal(e.data,this.opts.timezone);default:return e}else if("string"!=typeof e)return e;return s?this.Dialect.escapeId(e):this.Dialect.escapeId(a,e)}).join(", ")),n||(n="*"),n?n=`${t.func_name}(${n})`:n+=`${t.func_name}(*)`,t.func_stack&&t.func_stack.length>0&&(n=t.func_stack.join("(")+"("+n+Array(t.func_stack.length+1).join(")"));const l=r.pickColumnAsFromSelectFieldsDescriptor(t);l&&(n+=` as ${this.Dialect.escapeId(l)}`),e.select(this.Dialect.knex.raw(n))}else if(t.sql){const s=r.pickColumnAsFromSelectFieldsDescriptor(t),n=this.Dialect.knex.raw(`${t.sql}${s?` as ${this.Dialect.escapeId(s)}`:""}`);e.select(n)}return{should_continue:!1,return_value:""}}t.SelectQuery=class{constructor(e,t){this.opts=t,this.sql={from:[],where:[],order:[],group_by:null,found_rows:!1,where_exists:!1},this._aggregation_functions={},this.fun_stack=[],this.Dialect=e}get_aggregate_fun(e){return this._aggregation_functions[e]?this._aggregation_functions[e]:this._aggregation_functions[e]=((...t)=>{if(e=e.toUpperCase(),0===t.length)return this.fun_stack.push(e),this;var r=t.length>1&&"string"==typeof t[t.length-1]?t.pop():null;return t.length&&Array.isArray(t[0])&&(t=t[0].concat(t.slice(1))),this.fun(e,t.length&&t[0]?t:"*",r)})}select(e){if(e){const t=this.sql.from[this.sql.from.length-1];t.select&&Array.isArray(t.select)||(t.select=[]),this.sql.from[this.sql.from.length-1].select=t.select.concat(Array.isArray(e)?e:Array.prototype.slice.apply(arguments))}return this}calculateFoundRows(){return this.sql.found_rows=!0,this}as(e){var t=this.sql.from.length-1;if(Array.isArray(this.sql.from[t].select)){const s=this.sql.from[t].select;var r=s.length-1;"string"==typeof s[r]&&(s[r]={column_name:s[r]}),s[s.length-1].as=e||null}return this}fun(e,t,r){return Array.isArray(this.sql.from[this.sql.from.length-1].select)||(this.sql.from[this.sql.from.length-1].select=[]),this.sql.from[this.sql.from.length-1].select.push({func_name:e.toUpperCase(),column_name:t&&"*"!=t?t:null,as:r||null,func_stack:this.fun_stack}),this.fun_stack=[],this}from(e,t,s,n,i){const[a,l]=r.parseTableInputStr(e),o={table:a,alias:l||r.defaultTableAliasNameRule(r.autoIncreatementTableIndex(this.sql.from))};if(0===this.sql.from.length)return this.sql.from.push(o),this;let c;const u=Array.prototype.slice.call(arguments),p=u[u.length-1];if("object"!=typeof p||Array.isArray(p)||(i=u.pop(),o.opts=i),3==u.length)c=r.pickAliasFromFromDescriptor(this.sql.from[this.sql.from.length-1]),n=s;else{const[e,t]=r.parseTableInputStr(s);c=t||Helpers.get_table_alias(this.sql,e)}if(o.joins=[],!t.length||!n.length)throw new Error("[SQL-QUERY] both from_id & to_id cannot be empty!");if(Array.isArray(t)&&Array.isArray(n)&&t.length==n.length)for(let e=0;e<t.length;e++)o.joins.push([t[e],c,n[e]]);else o.joins.push([t,c,n]);return this.sql.from.push(o),this}where(...e){var t=null;const r=()=>{null!==t&&this.sql.where.push(t)};for(let s=0;s<e.length;s++)if(null!==e[s])if("string"==typeof e[s]){const n=e[s];r(),t={table:Helpers.get_table_alias(this.sql,n),wheres:e[s+1]},s++}else r(),t={table:null,wheres:e[s]};return r(),t=null,this}whereExists(e,t,s,n){return this.sql.where.push({table:this.sql.from.length?r.pickAliasFromFromDescriptor(this.sql.from[this.sql.from.length-1]):null,wheres:n,exists:{table:e,table_linked:Helpers.get_table_alias(this.sql,t),link_info:s}}),this.sql.where_exists=!0,this}groupBy(...e){return this.sql.group_by=e,this}offset(e){return this.sql.offset=e,this}limit(e){return this.sql.limit=e,this}order(e,t){if(Array.isArray(t))this.sql.order.push(r.escapeQuery(this.Dialect,e,t));else{let s=Array.isArray(e)?e[1]:e,n=null;const{direction:i,col_name:a}=r.cutOffOrderDirectionFromColumnFirstStr(s);n=i,s=a,t&&(n="Z"===t?"DESC":"ASC"),this.sql.order.push({c:Array.isArray(e)?[Helpers.get_table_alias(this.sql,e[0]),s]:s,d:n})}return this}build(){const e=[],t=this.sql.from;this.fun_stack.length&&this.fun(this.fun_stack.pop());const i={};for(let e=0;e<t.length;e++)t[e].alias=r.pickAliasFromFromDescriptor(t[e])||r.defaultTableAliasNameRule(e+1),i[`${t[e].alias}`]=`${t[e].table}`;const a=1===t.length,l=this.Dialect.knex(i);for(let r=0;r<t.length;r++)if(t[r].select)for(let s=0;s<t[r].select.length;s++){const i=t[r],o=i.select[s],c=a?"":`${i.alias}.`;if("string"!=typeof o){if("object"==typeof o){const{should_continue:t}=n.apply(this,[l,o,a,i,e]);if(t)continue}else if("function"==typeof o){const e=o(this.Dialect);l.select(this.Dialect.knex.raw(e));continue}}else l.select(`${c}${o}`)}if(t.length>0){t.length;const e=1==t.length&&!this.sql.where_exists;for(let n=0,i=!1;n<t.length;n++){const a=t[n];if(e)l.from(a.table);else if(i){const e={},t=r.pickAliasFromFromDescriptor(a)||a.table;a.joins.forEach(r=>{e[`${t}.${r[0]}`]=`${r[1]}.${r[2]}`}),l[s(a.opts)](`${a.table} as ${r.pickAliasFromFromDescriptor(a)}`,e)}else l.from(`${a.table} as ${r.pickAliasFromFromDescriptor(a)}`);i=!0}}if(Where.build(l,this.Dialect,this.sql.where,this.opts),null!==this.sql.group_by){const e=this.sql.group_by.map(e=>{if("-"==e[0]){const t=e.substr(1);return this.sql.order.unshift({c:t,d:"DESC"}),t}return e});l.groupBy(e)}let o;if(this.sql.order.length>0)for(let e=0;e<this.sql.order.length;e++)if("object"==typeof(o=this.sql.order[e]))if(Array.isArray(o.c)){if(2!==o.c.length)throw"invalid order item input!";l.orderBy(this.Dialect.knex.ref(o.c[1]).withSchema(o.c[0]),o.d)}else l.orderBy(o.c,o.d);else"string"==typeof o&&l.orderByRaw(o);this.Dialect.limitAsTop||(this.sql.hasOwnProperty("limit")?(this.sql.hasOwnProperty("offset")&&l.offset(r.ensureNumber(this.sql.offset)),l.limit(r.ensureNumber(this.sql.limit))):this.sql.hasOwnProperty("offset")&&l.offset(r.ensureNumber(this.sql.offset)));const c=l.toQuery();return this.sql.found_rows?c.replace("select ","select SQL_CALC_FOUND_ROWS "):c}abs(...e){return this.get_aggregate_fun("ABS")(...e)}ceil(...e){return this.get_aggregate_fun("CEIL")(...e)}floor(...e){return this.get_aggregate_fun("FLOOR")(...e)}round(...e){return this.get_aggregate_fun("ROUND")(...e)}avg(...e){return this.get_aggregate_fun("AVG")(...e)}min(...e){return this.get_aggregate_fun("MIN")(...e)}max(...e){return this.get_aggregate_fun("MAX")(...e)}log(...e){return this.get_aggregate_fun("LOG")(...e)}log2(...e){return this.get_aggregate_fun("LOG2")(...e)}log10(...e){return this.get_aggregate_fun("LOG10")(...e)}exp(...e){return this.get_aggregate_fun("EXP")(...e)}power(...e){return this.get_aggregate_fun("POWER")(...e)}acos(...e){return this.get_aggregate_fun("ACOS")(...e)}asin(...e){return this.get_aggregate_fun("ASIN")(...e)}atan(...e){return this.get_aggregate_fun("ATAN")(...e)}cos(...e){return this.get_aggregate_fun("COS")(...e)}sin(...e){return this.get_aggregate_fun("SIN")(...e)}tan(...e){return this.get_aggregate_fun("TAN")(...e)}conv(...e){return this.get_aggregate_fun("CONV")(...e)}random(...e){return this.get_aggregate_fun("RANDOM")(...e)}rand(...e){return this.get_aggregate_fun("RAND")(...e)}radians(...e){return this.get_aggregate_fun("RADIANS")(...e)}degrees(...e){return this.get_aggregate_fun("DEGREES")(...e)}sum(...e){return this.get_aggregate_fun("SUM")(...e)}count(...e){return this.get_aggregate_fun("COUNT")(...e)}distinct(...e){return this.get_aggregate_fun("DISTINCT")(...e)}}});unwrapExports(Select);var Select_1=Select.SelectQuery,Insert=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.InsertQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={}}into(e){return this.sql.table=e,this}set(e){return this.sql.set=e,this}build(){const e=this.Dialect.knex(this.sql.table),t={};if(this.sql.hasOwnProperty("set")){let r=null;for(let e in this.sql.set)r=Helpers.escapeValForKnex(this.sql.set[e],this.Dialect,this.opts),t[e]=r;e.insert(t)}return e.toQuery()}}});unwrapExports(Insert);var Insert_1=Insert.InsertQuery,_Set=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.build=function(e,t,r,s){if(s=s||{},!r||0===r.length)return;const n={};for(let e in r)n[e]=Helpers.escapeValForKnex(r[e],this.Dialect,s);e.update(n)}});unwrapExports(_Set);var _Set_1=_Set.build,Update=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.UpdateQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={where:[]}}into(e){return this.sql.table=e,this}set(e){return this.sql.set=e,this}where(...e){for(let t=0;t<e.length;t++)this.sql.where.push({table:null,wheres:e[t]});return this}build(){const e=this.Dialect.knex(this.sql.table);return _Set.build(e,this.Dialect,this.sql.set,this.opts),Where.build(e,this.Dialect,this.sql.where,this.opts),e.toQuery()}}});unwrapExports(Update);var Update_1=Update.UpdateQuery,Remove=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.RemoveQuery=class{constructor(e,t){this.Dialect=e,this.opts=t,this.sql={where:[],order:[]}}from(e){return this.sql.table=e,this}where(...e){for(let t=0;t<e.length;t++)this.sql.where.push({table:null,wheres:e[t]});return this}build(){var e=[];const t=this.Dialect.knex(this.sql.table);Where.build(t,this.Dialect,this.sql.where,this.opts),t.del();const r=[t.toQuery()];if(this.sql.order.length>0){const t=this.sql.order,s=[];for(let e=0;e<t.length;e++){const r=t[e].c,n=t[e].d;Array.isArray(r)?s.push(this.Dialect.escapeId.apply(this.Dialect,r)+" "+n):s.push(this.Dialect.escapeId(r)+" "+n)}s.length>0&&(e.push("ORDER BY "+s.join(", ")),r.push(util.last(e)))}return this.Dialect.limitAsTop?this.sql.hasOwnProperty("limit")&&r[0].replace("delete from",`delete top ${this.sql.limit}`):this.sql.hasOwnProperty("limit")?(this.sql.hasOwnProperty("offset")?e.push("LIMIT "+this.sql.limit+" OFFSET "+this.sql.offset):e.push("LIMIT "+this.sql.limit),r.push(util.last(e))):this.sql.hasOwnProperty("offset")&&(e.push("OFFSET "+this.sql.offset),t.offset(this.sql.offset),r.push(util.last(e))),r.join(" ")}offset(e){return this.sql.offset=e,this}limit(e){return this.sql.limit=e,this}order(e,t){return this.sql.order.push({c:Array.isArray(e)?[Helpers.get_table_alias(this.sql,e[0]),e[1]]:e,d:"Z"==t?"DESC":"ASC"}),this}}});unwrapExports(Remove);var Remove_1=Remove.RemoveQuery;const DataTypes={id:"INTEGER PRIMARY KEY AUTO_INCREMENT",int:"INTEGER",float:"FLOAT(12,2)",bool:"TINYINT(1)",text:"TEXT"};function escape(e,t){return Helpers.escapeQuery(Dialect,e,t)}function escapeId(...e){return e.map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(t){return"?:id"==t?escapeId(e.escapes.shift()):escapeVal(e.escapes.shift())}):"`"+e.replace(/`/g,"``")+"`"}).join(".")}function escapeVal(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"mysql");if(Array.isArray(e))return arrayToList(e,t||"local");if(util.isDate(e))e=Helpers.dateToString(e,t||"local",{dialect:"mysql"});else switch(typeof e){case"boolean":return e?"true":"false";case"number":if(!isFinite(e)){e=e.toString();break}return e+"";case"object":return objectToValues(e,t||"Z");case"function":return e(Dialect);case"bigint":return e.toString()}return"'"+(e=e.replace(/[\0\n\r\b\t\\\'\"\x1a]/g,function(e){switch(e){case"\0":return"\\0";case"\n":return"\\n";case"\r":return"\\r";case"\b":return"\\b";case"\t":return"\\t";case"":return"\\Z";default:return"\\"+e}}))+"'"}function objectToValues(e,t){var r=[];for(var s in e){var n=e[s];"function"!=typeof n&&r.push(escapeId(s)+" = "+escapeVal(n,t))}return r.join(", ")}function arrayToList(e,t){return"("+e.map(function(e){return Array.isArray(e)?arrayToList(e):escapeVal(e,t)}).join(", ")+")"}const Dialect={type:"mysql",DataTypes:DataTypes,escape:escape,escapeId:escapeId,escapeVal:escapeVal,limitAsTop:!1,knex:null};var mysql=Dialect,postgresql=createCommonjsModule(function(e,t){t.DataTypes={id:"SERIAL PRIMARY KEY",int:"INTEGER",float:"REAL",bool:"SMALLINT",text:"TEXT"},t.type="postgresql",t.escape=function(e,r){return Helpers.escapeQuery(t,e,r)},t.escapeId=function(){return Array.prototype.slice.apply(arguments).map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(r){return"?:id"==r?t.escapeId(e.escapes.shift()):t.escapeVal(e.escapes.shift())}):e.split(".").map(function(e){return'"'+e.replace(/\"/g,'""')+'"'}).join(".")}).join(".")},t.escapeVal=function(e,r){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(t.escapeVal.bind(this))+")":"("+e.map(t.escapeVal.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,r||"local",{dialect:"postgresql"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"postgresql");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?"true":"false";case"function":return e(t);case"string":break;case"bigint":return e.toString();default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"},t.defaultValuesStmt="DEFAULT VALUES"}),postgresql_1=postgresql.DataTypes,postgresql_2=postgresql.type,postgresql_3=postgresql.escape,postgresql_4=postgresql.escapeId,postgresql_5=postgresql.escapeVal,postgresql_6=postgresql.defaultValuesStmt;const DataTypes$1={isSQLITE:!0,id:"INTEGER PRIMARY KEY AUTOINCREMENT",int:"INTEGER",float:"FLOAT(12,2)",bool:"TINYINT(1)",text:"TEXT"};function escape$1(e,t){return Helpers.escapeQuery(Dialect$1,e,t)}const escapeId$1=mysql.escapeId;function escapeVal$1(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(escapeVal$1.bind(this))+")":"("+e.map(escapeVal$1.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,t||"local",{dialect:"sqlite"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"sqlite");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?1:0;case"function":return e(Dialect$1);case"string":break;case"bigint":return e.toString();default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"}const Dialect$1={type:"sqlite",DataTypes:DataTypes$1,escape:escape$1,escapeId:escapeId$1,escapeVal:escapeVal$1,limitAsTop:!1,knex:null};var sqlite=Dialect$1;const DataTypes$2={id:"INT IDENTITY(1,1) NOT NULL PRIMARY KEY",int:"INT",float:"FLOAT",bool:"BIT",text:"TEXT"},escape$2=function(e,t){return Helpers.escapeQuery(Dialect$2,e,t)};function escapeId$2(...e){return e.map(function(e){return"object"==typeof e?e.str.replace(/\?:(id|value)/g,function(t){return"?:id"==t?escapeId$2(e.escapes.shift()):escapeVal$2(e.escapes.shift())}):"["+e+"]"}).join(".")}const escapeVal$2=function(e,t){if(void 0===e||null===e||"symbol"==typeof e)return"NULL";if(Array.isArray(e))return 1===e.length&&Array.isArray(e[0])?"("+e[0].map(escapeVal$2.bind(this))+")":"("+e.map(escapeVal$2.bind(this)).join(", ")+")";if(util.isDate(e))return"'"+Helpers.dateToString(e,t||"local",{dialect:"mssql"})+"'";if(Buffer.isBuffer(e))return Helpers.bufferToString(e,"mssql");switch(typeof e){case"number":if(!isFinite(e)){e=e.toString();break}return e;case"boolean":return e?1:0;case"function":return e(Dialect$2);case"string":break;case"bigint":return e.toString();default:e=JSON.stringify(e)}return"'"+e.replace(/\'/g,"''")+"'"},Dialect$2={type:"mssql",DataTypes:DataTypes$2,escape:escape$2,escapeId:escapeId$2,escapeVal:escapeVal$2,limitAsTop:!0,knex:null};var mssql=Dialect$2,Dialects=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.mysql=mysql,t.postgresql=postgresql,t.sqlite=sqlite,t.mssql=mssql});unwrapExports(Dialects);var Dialects_1=Dialects.mysql,Dialects_2=Dialects.postgresql,Dialects_3=Dialects.sqlite,Dialects_4=Dialects.mssql,sandbox=createCommonjsModule(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});path.resolve(__dirname,"../");t.default=class extends vm.SandBox{constructor(){const[e={},t=function(){},r]=Array.prototype.slice.apply(arguments);super(Object.assign({},e,{fs:fs,path:path,os:os,url:url,tty:tty,util:util,events:events,assert:assert,crypto:crypto}),t,r),function(){this.add({uuid:{v4:()=>uuid.snowflake()}})}.call(this)}}});unwrapExports(sandbox);const sandbox$1=new sandbox.default,OKnex=sandbox$1.require("knex",__dirname);OKnex.SandBox=sandbox.default;var lib=OKnex,Query_1=createCommonjsModule(function(e,t){var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Helpers=Helpers,t.Dialects=Dialects,t.comparators=Comparators,t.Text=(r="text",function(e){var t={data:e};return Object.defineProperty(t,"type",{value:function(){return r},enumerable:!1}),t});t.Query=class{constructor(e){this._fns={};let r=null;if("string"==typeof e){if(!Helpers.DialectTypes.includes(e))throw`invalid dialect type ${e}`;r={dialect:e}}else r=e||{};this.opts=r,r.dialect=r.dialect||"mysql",function(e){const t=lib;this.Dialect=util.extend({},e),Object.defineProperty(this.Dialect,"knex",{value:t({client:this.Dialect.type,useNullAsDefault:!0}),writable:!1,configurable:!1}),Object.defineProperty(this,"knex",{value:this.Dialect.knex,writable:!1,configurable:!1})}.call(this,t.Dialects[r.dialect]),this.escape=this._proxyFn("escape"),this.escapeId=this._proxyFn("escapeId"),this.escapeVal=this._proxyFn("escapeVal")}_proxyFn(e){if(!this._fns[e])switch(e){case"escape":this._fns[e]=t.Helpers.escapeQuery.bind(t.Helpers,this.Dialect);break;case"escapeId":this._fns[e]=this.Dialect.escapeId.bind(this.Dialect);break;case"escapeVal":this._fns[e]=this.Dialect.escapeVal.bind(this.Dialect)}return this._fns[e]}create(){return new Create.CreateQuery(this.Dialect)}select(){return new Select.SelectQuery(this.Dialect,this.opts)}insert(){return new Insert.InsertQuery(this.Dialect,this.opts)}update(){return new Update.UpdateQuery(this.Dialect,this.opts)}remove(){return new Remove.RemoveQuery(this.Dialect,this.opts)}}}),Query=unwrapExports(Query_1),Query_2=Query_1.Helpers,Query_3=Query_1.Dialects,Query_4=Query_1.comparators,Query_5=Query_1.Text,Query_6=Query_1.Query;exports.Dialects=Query_3,exports.Helpers=Query_2,exports.Query=Query_6,exports.Text=Query_5,exports.comparators=Query_4,exports.default=Query; |
{ | ||
"version": "0.6.0", | ||
"version": "0.6.1", | ||
"name": "@fxjs/sql-query", | ||
@@ -55,5 +55,6 @@ "types": "@types/index.d.ts", | ||
"0.26.1", | ||
"0.27.0" | ||
"0.27.0", | ||
"0.28.0" | ||
] | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
141627
2439