UNPKG

@abw/badger-database

Version:
1 lines 65.5 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("events"),t=require("timers");const s="id",r=/:/,i=/^\w+$/,n="true",o="unknown",a=" ",l="=",c=", ",u="\n",h="",d="INSERT",p="SELECT",m="UPDATE",b="DELETE",g="FROM",y="IN",f="NOT IN",x="INTO",w="VALUES",v="JOIN",q="LEFT JOIN",k="RIGHT JOIN",O="INNER JOIN",j="FULL JOIN",R="WHERE",A="GROUP BY",E="ORDER BY",I="HAVING",T="LIMIT",C="OFFSET",M="RETURNING",D="ON",_="DESC",L="BEGIN",N="ROLLBACK",P="COMMIT";function S(e){return"string"==typeof e}function V(e){return Number.isInteger(e)}function $(e){return Array.isArray(e)}function B(e){return"function"==typeof e}function F(e){return"object"==typeof e&&!$(e)&&!W(e)}function Q(e){return typeof e>"u"}function W(e){return null===e}function U(e){return!(Q(e)||W(e))}function H(e){return!U(e)}function J(...e){return e.find(e=>U(e))??void 0}function G(...e){throw new Error(e.join(""))}function z(...e){}function Y(e,t=/,\s*|\s+/){return H(e)?[]:S(e)?e.length?e.split(t):[]:$(e)?e:[e]}function K(e,t=!0,s={}){return F(e)?e:Y(e).reduce((e,s)=>(e[s]=B(t)?t(s):t,e),s)}function X(e){if(B(e))return e;if(function(e){return e instanceof RegExp}(e))return t=>e.test(t);if(F(e))return t=>!!e[t];if($(e)||S(e)){const t=K(e);return e=>!!t[e]}G("Invalid selector() specification: "+e)}Intl.DateTimeFormat().resolvedOptions().locale;const Z=(e,t,s={})=>{let r={};const i={delete:!1,...s},n=X(t);return Object.keys(e).map(t=>{if(n(t)){let s=e[t];i.delete&&delete e[t],i.key&&(t=i.key(t)),i.value&&(s=i.value(s)),r={...r,[t]:s}}}),r},ee=(e,t)=>{const s=e[t];return delete e[t],s},te=e=>$(e)?e:[e],se=e=>e.match(/^[aeiou]/i)?"an":"a",re={reset:0,bold:1,bright:1,dark:2,black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,grey:7,white:8,fg:30,bg:40},ie={fg:e=>`38;2;${e.r};${e.g};${e.b}`,bg:e=>`48;2;${e.r};${e.g};${e.b}`},ne=(e,t="fg")=>{const s=(e=>{const t=e.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null})(e)||(e=>{const t=Y(e);return 3===t.length?{r:t[0],g:t[1],b:t[2]}:null})(e);return s?((e,t="fg")=>"["+ie[t](e)+"m")(s,t):((e,t="fg")=>{let s=[],r=e.split(/ /,2);const i=r.pop(),n=(t?re[t]:0)+re[i];if(s.push(n),r.length){const e=r.length?r.shift():"dark";s.push(re[e])}return"["+s.join(";")+"m"})(e,t)},oe=(e={})=>{const t=F(e)?e:{fg:e};let s=[];return t.bg&&s.push(ne(t.bg,"bg")),t.fg&&s.push(ne(t.fg,"fg")),s.join("")},ae=ne("reset",!1),le=()=>ae,ce=e=>(...t)=>oe(e)+t.join("")+ae,ue=ce("black"),he=ce("red"),de=ce("green"),pe=ce("yellow"),me=ce("blue"),be=ce("magenta"),ge=ce("cyan"),ye=ce("grey"),fe=ce("white"),xe=ce("bright black"),we=ce("bright red"),ve=ce("bright green"),qe=ce("bright yellow"),ke=ce("bright blue"),Oe=ce("bright magenta"),je=ce("bright cyan"),Re=ce("bright grey"),Ae=ce("bright white"),Ee=ce("dark black"),Ie=ce("dark red"),Te=ce("dark green"),Ce=ce("dark yellow"),Me=ce("dark blue"),De=ce("dark magenta"),_e=ce("dark cyan"),Le=ce("dark grey"),Ne=ce("dark white"),Pe=(e,t)=>e.replace(/<(\w+)>/g,(s,r)=>{const i=t[r];return H(i)&&G(`Invalid variable expansion <${r}> in message format: ${e}`),i}),Se=e=>G(`No "${e}" specified`),Ve=(e,t)=>G(`Invalid "${e}" specified: ${t}`),$e=(e,t)=>G(`${e} is not implemented in ${t}`),Be=e=>t=>$e(t,e),Fe=e=>Be(`the ${e} base class`);class Qe extends Error{constructor(e){super(e),this.name=this.constructor.name}}class We extends Error{constructor(e,t){super(t.message),this.name=this.constructor.name,this.query=e,this.type=t.type,this.code=t.code,this.position=t.position,t.stack&&(this.stack=t.stack)}}class Ue extends Qe{}const He=(e,t)=>{throw new Ue(`Failed to load "${e}" engine driver module. Have you installed it?\nError: `+t.message)};class Je extends Qe{}class Ge extends Qe{}class ze extends Qe{}class Ye extends Qe{}class Ke extends Qe{}function Xe(e,t="returned"){throw new Je(`${e} rows were ${t} when one was expected`)}const Ze=(e,t=Error)=>(s,r)=>{const i=Pe(e[s]||G("Invalid message format: ",s),r);throw new t(i)},et=Ze({unknown:'Unknown "<column>" column in the <table> table',readonly:'The "<column>" column is readonly in the <table> table',fixed:'The "<column>" column is fixed in the <table> table',required:'Missing required column "<column>" for the <table> table',multipleIds:'Multiple columns are marked as "id" in the <table> table',noColumns:'No "columns" specified for the <table> table',invalidColumns:'Invalid "columns" specified for the <table> table: <columns>'},Ge),tt=Ze({action:"Cannot <action> deleted <table> record #<id>"},ze),st=e=>{const t=e.columns||et("noColumns",{table:e.table});return S(t)?rt(t,e):$(t)?it(t,e):F(t)?nt(t,e):et("invalidColumns",{table:e.table,columns:t})},rt=(e,t)=>it(Y(e),t),it=(e,t)=>{let s={};return e.forEach(e=>{const i=e.split(r),n=i.shift();s[n]=ot(n,i,t)}),nt(s,t)},nt=(e,t)=>{return s=e,i=(e,s)=>{if(S(e))return ot(s,e.split(r),t);if(F(e)){const r=e.column||(e.column=s);return e.tableColumn=t.table+"."+r,e}G(`Invalid "${s}" columns specified in ${t.table} table: ${e}`)},Object.keys(s).reduce((e,t)=>({...e,[t]:i(s[t],t)}),{});var s,i},ot=(e,t,s)=>t.reduce((e,t)=>{const s=t.split("=",2);return e[s.shift()]=!s.length||s[0],e},{column:e,tableColumn:s.table+"."+e}),at=(e,t={})=>{let r=Y(e.keys);const i=Object.keys(t).filter(e=>t[e].id);return i.length>1?et("multipleIds",{table:e.table}):(0===r.length&&(r=Object.keys(t).filter(e=>t[e].key)),e.id?r.unshift(e.id):i.length?(e.id=i[0],r.unshift(e.id)):0===r.length&&(e.id=s,r.unshift(e.id)),r)},lt=/^(\w+):\/\/(?:(?:(\w+)(?::(\w+))?@)?(\w+)(?::(\d+))?\/)?(\w+)/,ct={engine:1,user:2,password:3,host:4,port:5,database:6},ut={username:"user",pass:"password",hostname:"host",file:"filename",name:"database"},ht=e=>{e.env&&Object.assign(e,dt(e.env,{prefix:e.envPrefix}));let t=e.database||Se("database");return S(t)&&(e.database=t=pt(t)),e.engine||=t.engine||Se("database.engine"),delete t.engine,Object.entries(ut).map(([e,s])=>{U(t[e])&&(t[s]||=ee(t,e))}),e.engineOptions&&Object.assign(t,ee(e,"engineOptions")),e},dt=(e,t={})=>{const s=t.prefix||"DATABASE",r=s.match(/_$/)?"":"_",i=new RegExp(`^${s}${r}`);return{database:e[s]||Z(e,i,{key:e=>e.replace(i,"").toLowerCase()})}},pt=e=>{let t,s={};return e.match(/^postgres(ql)?:/)?(s.engine="postgres",s.connectionString=e.replace(/^postgres:/,"postgresql:")):(t=e.match(/^sqlite:\/\/(.*)/))?(s.engine="sqlite",s.filename=t[1]):"sqlite:memory"===e?(s.engine="sqlite",s.filename=":memory:"):(t=e.match(lt))?Object.entries(ct).map(([e,r])=>{const i=t[r];U(i)&&(s[e]=i)}):Ve("database",e),s};function mt(e,t="",s){return e?t?(e,...r)=>console.log("%s"+t+"%s"+e,s?oe(s):"",le(),...r):console.log.bind(console):z}function bt(e,t,s="",r){e.debug=mt(t,s,r)}let gt={database:{debug:!1,prefix:"Database",color:"bright magenta"},engine:{debug:!1,prefix:"Engine",color:"red"},query:{debug:!1,prefix:"Query",color:"cyan"},tables:{debug:!1,prefix:"Tables",color:"blue"},table:{debug:!1,prefix:"Table",color:"bright cyan"},record:{debug:!1,prefix:"Record",color:"green"},builder:{debug:!1,prefix:"Builder",color:"yellow"},transaction:{debug:!1,prefix:"Transaction",color:"bright red"},test:{debug:!1,prefix:"Test",color:"green"}};const yt=e=>G(`Invalid debug item "${e}" specified`),ft=(e,...t)=>{const s=gt[e]||yt(e);return Object.assign({},s,...t)},xt=(e,t,...s)=>{const r=ft(t,...s),i=r.debug,n=r.debugPrefix||r.prefix,o=r.debugColor||r.color,a=n.length>14?n+"\n"+"".padEnd(16,"-")+"> ":(n+" ").padEnd(16,"-")+"> ";bt(e,i,a,o),e.debugData=function(e,t,s,r=16){return e?(e,i={})=>{console.log("%s"+t+"%s"+e,s?oe(s):"",s?le():""),Object.entries(i).map(([e,t])=>console.log("%s"+e.padStart(r," ")+":%s",s?oe(s):"",s?le():"",t))}:z}(i,a,o)};const wt={[y]:y,[f]:f},vt=e=>wt[e.toUpperCase().replaceAll(/\s+/g," ")],qt=/^(\w+)\s*([-~=#]>)\s*(\w+)\.(\w+)$/,kt={"~>":"any","->":"one","=>":"many","#>":"map"},Ot={localKey:"from",local_key:"from",remoteKey:"to",remote_key:"to",orderBy:"order",order_by:"order"},jt=(e,t,s)=>(S(s)?s=Rt(s):S(s.relation)&&(s={...Rt(s.relation),...s}),Object.entries(Ot).map(([e,t])=>{U(s[e])&&(s[t]||=ee(s,e))}),s.load||["type","table","to","from"].forEach(r=>{H(s[r])&&G(`Missing "${r}" in ${t} relation for ${e} table`)}),s.name=`${e}.${t}`,s),Rt=e=>{let t;return(t=e.match(qt))?{from:t[1],type:kt[t[2]]||G('Invalid type "',t[2],'" specified in relation: ',e),table:t[3],to:t[4]}:G("Invalid relation string specified: ",e)},At=(e,t)=>{const s=t.from,r=t.to;let i=t.where||{};return s&&r&&(i[r]=e.row[s]),i},Et=e=>e&&e.length?e+a:h,It=e=>e&&e.length?a+e:h,Tt=e=>e&&e.length?a+e+a:h,Ct=e=>e&&e.length?"("+e+")":h;let Mt={},Dt={};const _t=Fe("Builder");class Lt{static generateSQL(e){const t=this.keyword,s=this.joint;return Et(t)+($(e)?e.join(s):e)}constructor(e,...t){this.parent=e,this.args=t,this.messages=this.constructor.messages,this.method=this.constructor.buildMethod,this.slot=this.constructor.contextSlot||this.method,this.initBuilder(...t),xt(this,"builder",{debugPrefix:this.method&&`Builder:${this.method}`})}initBuilder(){}async one(e,t){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("one()",{sql:s,values:i}),r.one(s,i,t)}async any(e,t){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("any()",{sql:s,values:i}),r.any(s,i,t)}async all(e,t={}){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("all()",{sql:s,values:i}),r.all(s,i,t)}async run(e,t={}){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("all()",{sql:s,values:i}),r.run(s,i,{...t,sanitizeResult:!0})}contextValues(){const{setValues:e,whereValues:t,havingValues:s}=this.resolveChain();return{setValues:e,whereValues:t,havingValues:s}}allValues(e=[]){const{setValues:t,whereValues:s,havingValues:r}=this.resolveChain();return B(e)?e(t,s,r):[...t,...s,...r,...e]}setValues(...e){return e.length&&(this.context.setValues=[...this.context.setValues,...e]),this.context.setValues}whereValues(...e){return e.length&&(this.context.whereValues=[...this.context.whereValues,...e]),this.context.whereValues}havingValues(...e){return e.length&&(this.context.havingValues=[...this.context.havingValues,...e]),this.context.havingValues}sql(){const e=this.resolveChain();return Object.entries(Dt).sort((e,t)=>e[1][1]-t[1][1]).filter(([t])=>e[t]).map(([t,s])=>s[0].generateSQL(e[t],e)).filter(e=>U(e)).join(u)}resolveChain(){return this.context||this.resolve(this.parent?this.parent.resolveChain():{setValues:[],whereValues:[],havingValues:[],placeholder:1})}resolve(e,t={}){const s=this.slot;this.context={...e,...t};const r=this.resolveLink();return r&&r.length&&(this.context[s]=[...this.context[s]||[],...r]),this.context}resolveLink(){return this.args.map(e=>F(e)&&e.sql?e.sql:this.resolveLinkItem(e)).flat()}resolveLinkItem(e){return S(e)?this.resolveLinkString(e):$(e)?this.resolveLinkArray(e):B(e)?e(this):F(e)?this.resolveLinkObject(e):H(e)?this.resolveLinkNothing(e):void G("Invalid query builder value: ",e)}resolveLinkString(){_t("resolveLinkString()")}resolveLinkArray(){_t("resolveLinkArray()")}resolveLinkObject(){_t("resolveLinkObject()")}resolveLinkNothing(){return[]}lookup(e,t){return this[e]||(this.parent?this.parent.lookup(e):G(t||`Missing item in query chain: ${e}`))}lookupDatabase(){return this.context.database||this.lookup("database")}lookupTable(){return this.context.table||this.lookup("table")}quote(e){return this.lookupDatabase().quote(e)}quoteTableColumns(e,t,s){const r=e?s?t=>this.quoteTableColumnAs(e,t,s+t):t=>this.quoteTableColumn(e,t):s?e=>this.quoteColumnAs(e,s+e):e=>this.quote(e);return Y(t).map(r)}tableColumn(e,t){return t.match(/\./)?t:`${e}.${t}`}quoteTableColumn(e,t){return this.quote(this.tableColumn(e,t))}quoteTableAs(e,t){return[this.quote(e),this.quote(t)].join(" AS ")}quoteTableColumnAs(e,t,s){return[this.quoteTableColumn(e,t),this.quote(s)].join(" AS ")}quoteColumnAs(e,t){return[this.quote(e),this.quote(t)].join(" AS ")}errorMsg(e,t){const s=this.method||o;return this.error(Pe(this.messages?.[e]||G("Invalid message format: ",e),{method:s,...t}))}toString(){return this.sql()}error(...e){throw new(this.errorType||Ye)(e.join(""))}}class Nt extends Lt{static buildMethod="select";static buildOrder=20;static subMethods="select columns from table prefix join where having group groupBy order orderBy limit offset range returning";static keyword=p;static joint=c;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, alias] or [table, column, alias].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "table", "prefix" and "as".'};resolveLinkString(e,t,s){return this.quoteTableColumns(t,e,s)}resolveLinkArray(e){return 2===e.length?this.quoteColumnAs(...e):3===e.length?this.quoteTableColumnAs(...e):void this.errorMsg("array",{n:e.length})}resolveLinkObject(e){if(e.column&&e.as)return e.table?this.quoteTableColumnAs(e.table,e.column,e.as):this.quoteColumnAs(e.column,e.as);const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table,e.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}}let Pt=class extends Lt{initBuilder(e){this.database=e}resolve(e){return{database:this.database,...e}}};class St extends Lt{static buildMethod="from";static buildOrder=30;static keyword=g;static joint=c;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [table, alias].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "tables", "table" and "as".'};initBuilder(...e){const t=e.at(-1);S(t)?this.tableName=Y(t).at(-1):$(t)&&2===t.length?this.tableName=t[1]:F(t)&&t.as&&(this.tableName=t.as)}resolve(e){return super.resolve(e,this.tableName?{table:this.tableName}:void 0)}resolveLinkString(e){return Y(e).map(e=>this.quote(e))}resolveLinkArray(e){return 2===e.length?this.quoteTableAs(...e):this.errorMsg("array",{n:e.length})}resolveLinkObject(e){return e.table?e.as?this.quoteTableAs(e.table,e.as):this.quote(e.table):e.tables?this.resolveLinkString(e.tables):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}}class Vt extends Lt{static buildMethod="where";static buildOrder=50;static keyword=R;static joint=" AND ";static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, value] or [column, operator, value].',object:'Invalid value array with <n> items specified for query builder "<method>" component. Expected [value] or [operator, value].',comparator:'Invalid comparator object with <keys> specified for query builder "<method>" component. Expected object to contain "isNull", "notNull", etc.'};resolveLinkString(e){const t=this.lookupDatabase();return Y(e).map(e=>t.engine.formatWherePlaceholder(e,void 0,this.context.placeholder++))}resolveLinkArray(e){const t=this.lookupDatabase();if(2===e.length){let s;if($(e[1])){const t=vt(e[1][0]);if(t){const s=te(e[1][1]);return this.resolveIn(e[0],t,s)}U(e[1][1])&&this.addValues(e[1][1]),s=[e[1][0],void 0]}else{if(F(e[1]))return this.resolveLinkObjectValue(e[0],e[1]);this.addValues(e[1])}return t.engine.formatWherePlaceholder(e[0],s,this.context.placeholder++)}if(3===e.length){const s=vt(e[1]);if(s){const t=te(e[2]);return this.resolveIn(e[0],s,t)}return U(e[2])&&this.addValues(e[2]),t.engine.formatWherePlaceholder(e[0],[e[1],e[2]],this.context.placeholder++)}this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=this.lookupDatabase(),s=Object.entries(e).map(([e,s])=>{if($(s))if(2===s.length){const t=vt(s[0]),r=te(s[1]);if(t)return this.resolveIn(e,t,r);this.addValues(s[1])}else 1!==s.length&&this.errorMsg("object",{n:s.length});else{if(F(s))return this.resolveLinkObjectValue(e,s);if(W(s))return t.engine.formatWhereNull(e);this.addValues(s)}return t.engine.formatWherePlaceholder(e,s,this.context.placeholder++)});return s}resolveLinkObjectValue(e,t){const s=this.lookupDatabase();if(t.isNull)return s.engine.formatWhereNull(e);if(t.notNull)return s.engine.formatWhereNotNull(e);if(t.isIn)return this.resolveIn(e,y,t.isIn);if(t.notIn)return this.resolveIn(e,f,t.notIn);{const e=Object.keys(t),s=function(e,t=", ",s=" and "){return function(e,t=" ",s=t){const r=[...e],i=r.pop()??"";return r.length?[r.join(t),i].join(s):i}(e,t,s)}(e.map(e=>`"${e}"`))+(e.length>1?" keys":" key");this.errorMsg("comparator",{keys:s})}}resolveIn(e,t,s){const r=this.lookupDatabase();console.log(`adding ${e} ${t} values: `,s);const i=this.context.placeholder;return this.context.placeholder+=s.length,this.addValues(...s),r.engine.formatWhereInPlaceholder(e,t,s,i)}addValues(...e){this.whereValues(...e)}}const $t=/^(\w+)\.(\w+)$/,Bt=/^(.*?)\s*(<?=>?)\s*(\w+)\.(\w+)(?:\s+as\s+(\w+))?$/,Ft={from:1,type:2,table:3,to:4,as:5},Qt={default:v,inner:O,"=":v,left:q,"<=":q,right:k,"=>":k,full:j,"<=>":j};class Wt extends Lt{static buildMethod="simple";static generateSQL(e){const t=this.keyword;return Et(t)+($(e)?e.at(-1):e)}initBuilder(e){this.value=e}resolve(e){return this.context={...e,[this.slot]:this.value},this.context}}let Ut=class extends Lt{static buildMethod="table";initBuilder(e){this.tableName=e}resolve(e){return this.context={...e,table:this.tableName},this.context}};const Ht=(e,t,s={})=>new Proxy(t,{get(r,i){if("toString"===i)return r.toString.bind(r);const n=e[i];if(!n)return Reflect.get(r,i);if(s.valid){let e=Boolean(s.valid[i]);if(!e&&n.validFor&&(e=Boolean(K(n.validFor)[s.keyword])),!e)throw new Ye(`${i}() is not a valid builder method for ${se(s.keyword)} ${s.keyword} query.`)}return((...s)=>{const r=new n(t,...s),i=n.subMethods;return i?Ht(e,r,{valid:Z(e,i),keyword:n.keyword}):Ht(e,r)}).bind(r)}}),Jt=e=>{const t=e.contextSlot||e.buildMethod,s=e.buildOrder;[e.buildMethod,...Y(e.buildAlias)].forEach(t=>Mt[t]=e),t&&U(s)&&(Dt[t]=[e,s])},Gt=(...e)=>e.forEach(Jt);Gt(class extends Lt{static buildMethod="after";static buildOrder=100},class extends Lt{static buildMethod="before";static buildOrder=0},class extends Nt{static buildMethod="columns";static contextSlot="select";initBuilder(){}resolveLinkString(e,t=this.lookupTable(),s=this.context.prefix){return super.resolveLinkString(e,t,s)}resolveLinkArray(e){const t=this.lookupTable();return 2===e.length?this.quoteTableColumnAs(t,...e):3===e.length?this.quoteTableColumnAs(...e):void this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=this.lookupTable();if(e.column&&e.as)return this.quoteTableColumnAs(e.table||t,e.column,e.as);const s=e.column||e.columns;if(s)return this.resolveLinkString(s,e.table||t,e.prefix||this.context.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Lt{static buildMethod="delete";static buildOrder=19;static subMethods="from join where order order_by limit returning";static keyword=b;static joint=c;static messages={object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "table" and "prefix".'};static generateSQL(e){const t=this.keyword,s=this.joint;return e&&e.length?Et(t)+($(e)?e.join(s):e):t}resolveLink(){if(this.args.length)return super.resolveLink();this.context.delete=[]}resolveLinkString(e,t,s){return this.quoteTableColumns(t,e,s)}resolveLinkObject(e){const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table,e.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},St,class extends Lt{static buildMethod="group";static buildAlias="groupBy";static buildOrder=60;static keyword=A;static joint=c;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns" and "column".'};resolveLinkString(e){return Y(e).map(e=>this.quote(e))}resolveLinkArray(e){if(1===e.length)return this.quote(e[0]);this.errorMsg("array",{n:e.length})}resolveLinkObject(e){return e.column?this.quote(e.column):e.columns?this.resolveLinkString(e.columns):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Vt{static buildMethod="having";static buildOrder=70;static keyword=I;addValues(...e){this.havingValues(...e)}},class extends Lt{static buildMethod="insert";static buildOrder=17;static subMethods="into join values returning";static keyword=d;static joint=c;static messages={object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns" and "column".'};static generateSQL(){return this.keyword}resolveLink(){if(this.args.length)return super.resolveLink();this.context.insert=[]}resolveLinkString(e){return this.quoteTableColumns(void 0,e)}resolveLinkArray(e){return this.quoteTableColumns(void 0,e)}resolveLinkObject(e){const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Lt{static buildMethod="into";static buildOrder=29;static keyword=x;static joint=c;static generateSQL(e,t){const s=this.keyword,r=this.joint,i=t.database,n=t.insert||[];let o=t.placeholder;return Et(s)+($(e)?e.join(r):e)+(n.length?It(Ct(n.join(c))):h)+(n.length?u+Et(w)+Ct(n.map(()=>i.engine.formatPlaceholder(o++)).join(c)):h)}initBuilder(...e){1===e.length&&S(e[0])&&(this.tableName=e[0])}resolve(e){return super.resolve(e,this.tableName?{table:this.tableName}:void 0)}resolveLinkString(e){return[this.quote(e)]}},class extends Lt{static buildMethod="join";static buildOrder=40;static keyword=h;static joint=u;static messages={type:'Invalid join type "<joinType>" specified for query builder "<method>" component. Valid types are "left", "right", "inner" and "full".',string:'Invalid join string "<join>" specified for query builder "<method>" component. Expected "from=table.to".',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "type", "table", "from" and "to".',array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [type, from, table, to], [from, table, to] or [from, table.to].'};resolveLinkString(e){let t=e.match(Bt),s={};if(t)return Object.entries(Ft).map(([e,r])=>s[e]=t[r]),this.resolveLinkObject(s);this.errorMsg("string",{join:e})}resolveLinkArray(e){if(4===e.length){const[t,s,r,i]=e;return this.resolveLinkObject({type:t,from:s,table:r,to:i})}if(3===e.length){const[t,s,r]=e;return this.resolveLinkObject({from:t,table:s,to:r})}if(2===e.length){const t=e[1].match($t);if(t){const s=e[0],[,r,i]=t;return this.resolveLinkObject({from:s,table:r,to:i})}}this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=Qt[e.type||"default"]||this.errorMsg("type",{joinType:e.type});if(e.table&&e.from&&e.to)return e.as?this.constructJoinAs(t,e.from,e.table,e.as,this.tableColumn(e.as,e.to)):this.constructJoin(t,e.from,e.table,this.tableColumn(e.table,e.to));if(e.from&&e.to){const s=e.to.match($t);if(s)return e.as?this.constructJoinAs(t,e.from,s[1],e.as,this.tableColumn(e.as,s[2])):this.constructJoin(t,e.from,s[1],this.tableColumn(s[1],s[2]))}this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}constructJoin(e,t,s,r){return Et(e)+this.quote(s)+Tt(D)+this.quote(t)+Tt(l)+this.quote(r)}constructJoinAs(e,t,s,r,i){return Et(e)+this.quote(s)+Tt("AS")+this.quote(r)+Tt(D)+this.quote(t)+Tt(l)+this.quote(i)}},class extends Wt{static buildMethod="limit";static buildOrder=90;static keyword=T;initBuilder(e){this.value=e}},class extends Wt{static buildMethod="offset";static buildOrder=95;static keyword=C;initBuilder(e){this.value=e}},class extends Lt{static buildMethod="order";static buildAlias="orderBy";static buildOrder=80;static keyword=E;static joint=c;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, direction] or [column].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "direction", "dir", "asc" and "desc".'};resolveLinkString(e,t){return Y(e).map(e=>this.constructOrder(e)).join(", ")+(t?a+t:"")}resolveLinkArray(e){if(2===e.length||1===e.length)return this.constructOrder(...e);this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=e.direction||e.dir||e.desc&&_||e.asc&&"ASC";return e.column?this.constructOrder(e.column,t):e.columns?this.resolveLinkString(e.columns,t):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}constructOrder(e,t){return this.quote(e)+(t?a+t:"")}},class extends Lt{static buildMethod="prefix";initBuilder(e){this.prefix=e}resolve(e){return this.context={...e,prefix:this.prefix},this.context}},class extends Lt{static buildMethod="range";static messages={arg:'Invalid argument specified for query builder "<method>" component. Expected (from, to), (from) or object.',args:'Invalid arguments with <n> items specified for query builder "<method>" component. Expected (from, to), (from) or object.',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "from", "to", "limit" and "offset".'};initBuilder(...e){if(2===e.length)this.args=this.twoNumberArgs(...e);else if(1===e.length){const t=e[0];V(t)?this.args=this.oneNumberArg(t):F(t)?this.args=this.objectArgs(t):this.errorMsg("arg")}else this.errorMsg("args",{n:e.length})}twoNumberArgs(e,t){return{offset:e,limit:t-e+1}}oneNumberArg(e){return{offset:e}}objectArgs(e){return e.from&&e.to?this.twoNumberArgs(e.from,e.to):e.from?this.oneNumberArg(e.from):e.to?{limit:e.to+1}:e.limit||e.offset?{limit:e.limit,offset:e.offset}:void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}resolve(e){return this.context={...e,...this.args},this.context}},class extends Nt{static buildMethod="returning";static buildOrder=96;static keyword=M},Nt,class extends Vt{static buildMethod="set";static buildOrder=45;static keyword="SET";static joint=c;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, value].',object:'Invalid value array with <n> items specified for query builder "<method>" component. Expected [value] or [operator, value].'};addValues(...e){this.setValues(...e)}resolveLinkObject(e){const t=this.lookupDatabase();let s=[];const r=Object.entries(e).map(([e,r])=>(s.push(r),t.engine.formatWherePlaceholder(e,"",this.context.placeholder++)));return s.length&&this.addValues(...s),r}resolveLinkArray(e){if(2==e.length)return this.addValues(e[1]),this.lookupDatabase().engine.formatSetPlaceholder(e[0],this.context.placeholder++);this.errorMsg("array",{n:e.length})}},Ut,class extends St{static buildMethod="update";static buildOrder=18;static subMethods="join set where order order_by limit returning";static keyword=m;static joint=c},class extends Lt{static buildMethod="values";static buildOrder=0;resolveLinkItem(e){return V(e)||function(e){return"number"==typeof e}(t=e)&&!V(t)?this.resolveLinkString(e):super.resolveLinkItem(e);var t}resolveLinkString(e){return this.setValues(e),[]}resolveLinkArray(e){return e.forEach(e=>{this.setValues(e)}),[]}},Vt);const zt=e=>Ht(Mt,new Pt(void 0,e)),Yt=e=>t=>Q(t)?[e]:[e,t],Kt=e=>(...t)=>1===t.length&&$(t[0])?{[e]:t[0]}:{[e]:[...t]},Xt=Yt("="),Zt=Yt("<"),es=Yt("<="),ts=Yt(">"),ss=Yt(">="),rs=Yt("!="),is=Kt("isIn"),ns=Kt("notIn");class os{constructor(e,t,s={}){if(this.engine=e||Se("engine"),this.setValues=s.setValues||[],this.whereValues=s.whereValues||[],this.havingValues=s.havingValues||[],this.transact=s.transact,S(t))this.query=t;else if(t instanceof Lt){this.query=t.sql();const e=t.contextValues();Object.keys(e).forEach(t=>this[t]=[...e[t],...this[t]])}else G("Invalid query type: ",t);xt(this,"query",this.config)}sql(){return this.query}run(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("run()",{sql:t,values:s,options:r}),this.engine.run(t,s,r)}one(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("one()",{sql:t,values:s,options:r}),this.engine.one(t,s,r)}any(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("any()",{sql:t,values:s,options:r}),this.engine.any(t,s,r)}all(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("all()",{sql:t,values:s,options:r}),this.engine.all(t,s,r)}queryArgs(e){const t=$(e[0])?e.shift():[],s=e.length?e.shift():{};return[this.allValues(t),this.transact?{...s,transact:this.transact}:s]}allValues(e=[]){const t=this.whereValues,s=this.havingValues;return B(e)?e(t,s):[...t,...s,...e]}toString(){return this.sql()}}const as=e=>S(e)||e instanceof Lt,ls=(e,t,s=16)=>{let r=e=e.trim(),i=0,n=[];for(;;){let e=!1;if(r=r.replace(/<(\w+?)>/g,(s,r)=>(e=!0,n.push(r),t.fragment(r))),!e)break;++i>=s&&G("Maximum SQL expansion limit (maxDepth=",s,") exceeded: ",n.join(" -> "))}return r};class cs{constructor(e,t={}){this.engine=e||Se("engine"),this.transact=t.transact}query(e){this.debugData("query()",{source:e});const t=this.queries[e]||this.database&&this.database.query(e)||G("Invalid named query specified: ",e);return B(t)?t(this):t}fragment(e){return this.debugData("fragment()",{name:e}),this.fragments[e]||this.database&&this.database.fragment(e)||G("Invalid query fragment in SQL expansion: <",e,">")}buildQuery(e,t={}){return t.transact||=this.transact,this.debugData("buildQuery()",{source:e,config:t}),new os(this.engine,S(e)?this.expandQuery(e):e,t)}expandQuery(e,t){return this.debugData("expandQuery()",{source:e}),e.match(i)?this.expandNamedQuery(e,t):ls(e,this)}expandNamedQuery(e){this.debugData("expandNamedQuery()",{name:e});const t=this.query(e);return S(t)?ls(t,this):t}sql(e,t){return this.debugData("sql()",{name:e,config:t}),this.buildQuery(e,t).sql()}async run(e,t,s){return this.debugData("run()",{query:e,params:t,options:s}),this.buildQuery(e).run(t,s)}async one(e,t,s){return this.debugData("one()",{query:e,params:t,options:s}),this.loadedOne(await this.buildQuery(e).one(t,s),s)}async any(e,t,s){return this.debugData("any()",{query:e,params:t,options:s}),this.loadedAny(await this.buildQuery(e).any(t,s),s)}async all(e,t,s){return this.debugData("all()",{query:e,params:t,options:s}),this.loadedAll(await this.buildQuery(e).all(t,s),s)}loadedOne(e){return e}loadedAny(e){return e}loadedAll(e){return e}}const us={one:async(e,t={})=>{const s=At(e,t),r=await e.database.table(t.table);return await r.oneRecord(s)},any:async(e,t={})=>{const s=At(e,t),r=await e.database.table(t.table);return await r.anyRecord(s)},many:async(e,t={})=>{const s=At(e,t),r=t.order,i=r?{order:r}:{},n=await e.database.table(t.table);return await n.allRecords(s,i)},map:async(e,t={})=>{const s=At(e,t),r=t.key||e.table.id,i=t.value,n=await e.database.table(t.table);return(await n.allRecords(s)).reduce((e,s)=>(e[s[r]]=t.value?s[i]:s,e),{})}};class hs{constructor(e,t,s={}){this.table=e,this.database=e.database,this.row=t,this.relations={},this.config=s,xt(this,"record",{debugPrefix:`Record:${this.table.table}`},s)}async update(e,t={}){this.debugData("update()",{set:e}),this.assertNotDeleted("update");const s=this.table.identity(this.row),r=await this.table.updateOne(e,s,{...t,reload:!0});return Object.assign(this.row,r),this}async delete(){this.debugData("delete()"),this.assertNotDeleted("delete");const e=this.table.identity(this.row);return await this.table.delete(e),this.deleted=!0,this}assertNotDeleted(e){this.deleted&&tt("action",{action:e,table:this.table.table,id:this.table.keys.map(e=>this.row[e]).join("/")})}async relation(e){return this.debug("relation(%s)",e),this.relations[e]||=await this.initRelation(e)}async initRelation(e){this.debug("initRelation(%s)",e);const t=this.table.table,s=jt(t,e,this.table.relations[e]||G(`Invalid "${e}" relation specified for ${t} table`));if(s.load)return await s.load(this);const r=us[s.type]||G(`Invalid "${s.type}" relation type specified for ${e} relation in ${t} table`);return await r(this,s)}}const ds=e=>new Proxy(e,{get:(e,t)=>Reflect.has(e,t)?Reflect.get(e,t):Reflect.has(e.row,t)?Reflect.get(e.row,t):Reflect.has(e.table.relations,t)?e.relation(t):Reflect.get(e,t)}),ps={insertRow:"insertOneRow",insertRows:"insertAllRows",insertRecord:"insertOneRecord",insertRecords:"insertAllRecords",update:"updateAll",updateRow:"updateOneRow",fetch:"fetchAll",fetchRecord:"fetchOneRecord",fetchRecords:"fetchAllRecords"};class ms extends cs{constructor(e,t){var s,r;super(e.engine,t),this.config=this.configure(t)||t,this.database=e||G("No database specified"),this.table=t.table,this.columns=st(t),this.readonly=Object.keys(this.columns).filter(e=>this.columns[e].readonly),this.required=Object.keys(this.columns).filter(e=>this.columns[e].required),this.keys=at(t,this.columns),this.id=t.id,this.recordClass=t.recordClass||hs,this.recordConfig=t.recordConfig,this.queries=t.queries||{},this.fragments=this.prepareFragments(t),this.relations=t.relations||{},this.build=zt(this.database),s=this,r=ps,Object.entries(r).map(([e,t])=>s[e]=s[t]||G(`Invalid alias "${e}" references non-existent method "${t}"`)),xt(this,"table",{debugPrefix:`Table:${this.table}`},t)}configure(e){return e}prepareFragments(e){const t=this.database.quote.bind(this.database),s=e.fragments||={};return s.table=t(this.table),s.columns=Object.values(this.columns).map(e=>t(e.tableColumn)).join(", "),s}async insert(e,t){return $(e)?this.insertAll(e,t):this.insertOne(e,t)}async prepareInsert(e,t){const[s,r]=await this.validateInsert(e,t),i=this.engine.returning?{table:this.table,columns:this.keys}:void 0;this.checkRequiredColumns(e);const n=this.build.insert(s).into(this.table).values(r).returning(i);return this.debugData("prepareInsert()",{data:e,sql:n.sql()}),n}async validateInsert(e,t){return this.checkWritableColumns(e,t)}async insertOne(e,t={}){const s=await this.prepareInsert(e,t).then(e=>e.run(void 0,{keys:this.keys}));return this.inserted(e,s,t)}async insertAll(e,t){this.debugData("insertAll()",{data:e,options:t});let s=[];for(const r of e)s.push(await this.insertOne(r,t));return s}async insertOneRow(e,t){return this.debugData("insertOneRow()",{data:e,options:t}),this.insertOne(e,this.withReloadOption(t))}async insertAllRows(e,t){return this.debugData("insertAllRows()",{data:e,options:t}),this.insertAll(e,this.withReloadOption(t))}async insertOneRecord(e,t){return this.debugData("insertOneRecord()",{data:e,options:t}),this.insertOne(e,this.withRecordOption(t))}async insertAllRecords(e,t){return this.debugData("insertAllRecords()",{data:e,options:t}),this.insertAll(e,this.withRecordOption(t))}async inserted(e,t,s={}){return s.reload||s.record?this.insertReload(e,t,s):t}async insertReload(e,t,s={}){const r={};return this.keys.map(s=>r[s]=J(t[s],e[s])),s.record?this.oneRecord(r):this.oneRow(r)}async prepareUpdate(e,t,s){const[r,i]=await this.validateUpdate(e,t,s),n=this.build.update(this.table).set(r).where(i),o=n.sql();return this.debugData("prepareUpdate()",{where:t,sql:o}),n}async validateUpdate(e,t,s){const[,,r]=this.checkUpdatableColumns(e,s),[,,i]=this.checkWhereColumns(t,s);return[r,i]}async updateOne(e,t,s={}){this.debugData("updateOne()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then(e=>e.run());return 1===r.changes?this.updated(e,t,r,s):Xe(r.changes,"updated")}async updateAny(e,t,s={}){this.debugData("updateAny()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then(e=>e.run());return r.changes>1?Xe(r.changes,"updated"):1===r.changes?this.updated(e,t,r,s):s.reload?void 0:r}async updateAll(e,t,s={}){this.debugData("updateAllRows()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then(e=>e.run());return s.reload?G("Cannot reload multiple updated rows"):r}async updateOneRow(e,t,s){return this.debugData("updateOneRow()",{set:e,where:t,options:s}),this.updateOne(e,t,this.withReloadOption(s))}async updateAnyRow(e,t,s){return this.debugData("updateAnyRow()",{set:e,where:t,options:s}),this.updateAny(e,t,this.withReloadOption(s))}async updated(e,t,s,r){return r.reload?this.updateReload(e,t,r):s}async updateReload(e,t,s){const r={};return Object.keys(t).map(s=>r[s]=J(e[s],t[s])),this.oneRow(r,s)}async delete(e,t){this.debugData("delete()",{where:e});const s=await this.validateDelete(e,t),r=this.build.delete().from(this.table).where(s),i=r.sql();this.debugData("delete()",{where:e,sql:i});const n=await r.run();return this.deleted(e,n,t)}async validateDelete(e,t){const[,,s]=this.checkWhereColumns(e,t);return s}async deleted(e,t){return t}prepareFetch(e,t){const s=this.table,r=t.columns||Object.keys(this.columns);this.checkColumnNames(r);const[,,i]=this.checkWhereColumns(e,t),n=this.select({table:s,columns:r}).where(i).order(t.orderBy||t.order),o=n.sql();return this.debugData("prepareFetch()",{where:e,sql:o}),n}async fetchOne(e,t={}){this.debugData("fetchOne()",{where:e,options:t});const s=await this.prepareFetch(e,t).one();return this.loadedOne(s,t)}async fetchAny(e,t={}){this.debugData("fetchAny()",{where:e,options:t});const s=await this.prepareFetch(e,t).any();return s?this.loadedOne(s,t):void 0}async fetchAll(e,t={}){this.debugData("fetchAllRows()",{where:e,options:t});const s=await this.prepareFetch(e,t).all();return this.loadedAll(s,t)}async fetchOneRecord(e,t){return this.debugData("fetchOneRecord()",{where:e,options:t}),this.fetchOne(e,this.withRecordOption(t))}async fetchAnyRecord(e,t){return this.debugData("fetchAnyRecord()",{where:e,options:t}),this.fetchAny(e,this.withRecordOption(t))}async fetchAllRecords(e,t){return this.debugData("fetchAllRecords()",{where:e,options:t}),this.fetchAll(e,this.withRecordOption(t))}async oneRow(e,...t){return this.debugData("oneRow()",{query:e,args:t}),as(e)?this.one(e,...t):this.fetchOne(e,...t)}async anyRow(e,...t){return this.debugData("anyRow()",{query:e,...t}),as(e)?this.any(e,...t):this.fetchAny(e,...t)}async allRows(e,...t){return this.debugData("allRows()",{query:e,...t}),as(e)?this.all(e,...t):this.fetchAll(e,...t)}async oneRecord(e,...t){return this.debugData("oneRecord()",{query:e,args:t}),as(e)?this.one(e,t[0],this.withRecordOption(t[1])):this.fetchOne(e,this.withRecordOption(t[0]))}async anyRecord(e,...t){return this.debugData("anyRecord()",{query:e,args:t}),as(e)?this.any(e,t[0],this.withRecordOption(t[1])):this.fetchAny(e,this.withRecordOption(t[0]))}async allRecords(e,...t){return this.debugData("allRecords()",{query:e,args:t}),as(e)?this.all(e,t[0],this.withRecordOption(t[1])):this.fetchAll(e,this.withRecordOption(t[0]))}loaded(e,t={}){return t.record?this.record(e):e}loadedOne(e,t={}){return this.loaded(e,t)}loadedAny(e,t={}){return e?this.loaded(e,t):void 0}loadedAll(e,t={}){return Promise.all(e.map(e=>this.loaded(e,t)))}withReloadOption(e={}){return{...e,reload:!0}}withRecordOption(e={}){return{...e,record:!0}}checkColumnNames(e){const t=this.table;Y(e).forEach(e=>this.columns[e]||et("unknown",{column:e,table:t}))}checkColumns(e={},t={},s=[],r=[]){this.debugData("checkColumns()",{data:e,options:t});const i=this.table;let n={};return Object.keys(e).forEach(o=>{const a=this.columns[o];a?(t.writable&&a.readonly&&et("readonly",{column:o,table:i}),t.fixed&&a.fixed&&et("fixed",{column:o,table:i}),s.push(a.column),r.push(e[o]),n[a.column]=e[o]):t.pick||et("unknown",{column:o,table:i})}),this.debugData("checkColumns()",{cols:s,vals:r}),[s,r,n]}checkWritableColumns(e,t={}){return this.checkColumns(e,{...t,writable:!0})}checkUpdatableColumns(e,t={}){return this.checkColumns(e,{...t,writable:!0,fixed:!0})}checkWhereColumns(e,t){return this.checkColumns(e,t)}checkRequiredColumns(e){const t=this.table;this.required.forEach(s=>{H(e[s])&&et("required",{column:s,table:t})})}select(...e){return 0===e.length&&e.push({table:this.table,columns:Object.keys(this.columns)}),this.build.select(...e).from(this.table)}newRecord(e){return ds(new this.recordClass(this,e,this.recordConfig))}record(e){return this.debugData("record()",{row:e}),Promise.resolve(this.newRecord(e))}records(e){return this.debugData("records()",{rows:e}),Promise.resolve(e.map(e=>this.newRecord(e)))}tableFragments(){return this.tableFragments}identity(e){return this.keys.reduce((t,s)=>(t[s]=e[s],t),{})}}class bs{constructor(e={}){this.tables=e,xt(this,"tables")}async table(e){const t=this.tables[e];return B(t)&&B(t.constructor)?{tableClass:t}:t}}class gs{constructor(e,t={}){this.engine=e||Se("engine"),this.completed=!1,this.autoCommit=t.autoCommit,this.autoRollback=t.autoRollback,xt(this,"transaction",t)}async run(e,t){this.debug("run()");const s=this.commit.bind(this),r=this.rollback.bind(this);try{await this.acquire(),await this.begin(),await t(e,s,r),this.debug("code complete"),this.completed||(this.autoCommit?(this.debug("autoCommit"),await this.commit()):this.autoRollback?(this.debug("autoRollback"),await this.rollback()):this.fail("Transaction was not committed or rolled back"))}catch(e){throw this.completed||(this.debug("caught error, rolling back transaction"),await this.rollback()),e}finally{await this.release()}}async acquire(){this.debug("acquire()"),this.connection&&this.fail("Transaction has already acquired a connection"),this.connection=await this.engine.acquire()}async release(){this.debug("release()"),this.connection||this.fail("Transaction does not have a connection to release"),await this.engine.release(this.connection),delete this.connection}async begin(){this.debug("begin()"),this.engine.begin(this)}async commit(){this.debug("commit()"),this.complete("commit"),await this.engine.commit(this)}async rollback(){this.debug("rollback()"),this.complete("rollback"),await this.engine.rollback(this)}complete(e){if(this.completed)throw new Ke(`Cannot ${e} transaction - ${this.completed}() has already been called`);this.completed=e}fail(...e){throw new Ke(e.join(""))}}function ys(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}const fs=e=>{if("object"==typeof e){const t=()=>e;return t.__proxy__=!0,new Proxy(t,xs)}return"function"==typeof e?new Proxy(e,xs):e},xs={construct:(e,t)=>(e.__proxy__&&(e=e()),fs(Reflect.construct(e,t))),get:(e,t,s)=>(e.__proxy__&&(e=e()),"then"!==t&&"catch"!==t&&"function"==typeof e.then?fs(e.then(e=>ws(e,t,s))):fs(ws(e,t,s))),apply:(e,t,s)=>(e.__proxy__&&(e=e()),"function"==typeof e.then?fs(e.then(e=>Reflect.apply(e,t,s))):fs(Reflect.apply(e,t,s)))},ws=(e,t,s)=>{const r="object"==typeof e?Reflect.get(e,t,s):e[t];return"function"==typeof r&&"function"==typeof r.bind?Object.assign(r.bind(e),r):r};var vs=ys(fs);const qs=e=>new Proxy(e,{get:(e,t)=>"then"===t?Reflect.get(e,t):e.table(t)});var ks={exports:{}},Os={},js={},Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});class As extends Error{}Rs.TimeoutError=As;var Es={},Is={};Object.defineProperty(Is,"__esModule",{value:!0});Is.PromiseInspection=class{constructor(e){this._value=e.value,this._error=e.error}value(){return this._value}reason(){return this._error}isRejected(){return!!this._error}isFulfilled(){return!!this._value}},Object.defineProperty(Es,"__esModule",{value:!0});const Ts=Is;function Cs(e){return"number"==typeof e&&e===Math.round(e)&&e>0}Es.defer=function(){let e=null,t=null;return{promise:new Promise((s,r)=>{e=s,t=r}),resolve:e,reject:t}},Es.now=function(){return Date.now()},Es.duration=function(e,t){return Math.abs(t-e)},Es.checkOptionalTime=function(e){return void 0===e||Cs(e)},Es.checkRequiredTime=Cs,Es.delay=function(e){return new Promise(t=>setTimeout(t,e))},Es.reflect=function(e){return e.then(e=>new Ts.PromiseInspection({value:e})).catch(e=>new Ts.PromiseInspection({error:e}))},Es.tryPromise=function(e){try{const t=e();return Promise.resolve(t)}catch(e){return Promise.reject(e)}},Object.defineProperty(js,"__esModule",{value:!0});const Ms=Rs,Ds=Es;js.PendingOperation=class{constructor(e){var t,s;this.timeoutMillis=e,this.deferred=Ds.defer(),this.possibleTimeoutCause=null,this.isRejected=!1,this.promise=(t=this.deferred.promise,s=e,new Promise((e,r)=>{const i=setTimeout(()=>r(new Ms.TimeoutError),s);t.then(t=>{clearTimeout(i),e(t)}).catch(e=>{clearTimeout(i),r(e)})})).catch(e=>(e instanceof Ms.TimeoutError&&(e=this.possibleTimeoutCause?new Ms.TimeoutError(this.possibleTimeoutCause.message):new Ms.TimeoutError("operation timed out for an unknown reason")),this.isRejected=!0,Promise.reject(e)))}abort(){this.reject(new Error("aborted"))}reject(e){this.deferred.reject(e)}resolve(e){this.deferred.resolve(e)}};var _s={};Object.defineProperty(_s,"__esModule",{value:!0});const Ls=Es;class Ns{constructor(e){this.resource=e,this.resource=e,this.timestamp=Ls.now(),this.deferred=Ls.defer()}get promise(){return this.deferred.promise}resolve(){return this.deferred.resolve(void 0),new Ns(this.resource)}}_s.Resource=Ns,Object.defineProperty(Os,"__esModule",{value:!0});const Ps=js,Ss=_s,Vs=Es,$s=e,Bs=t;function Fs(e,t){const s=e.indexOf(t);return-1!==s&&(e.splice(s,1),!0)}Os.Pool=class{constructor(e){if(this.destroyed=!1,this.emitter=new $s.EventEmitter,!(e=e||{}).create)throw new Error("Tarn: opt.create function most be provided");if(!e.destroy)throw new Error("Tarn: opt.destroy function most be provided");if("number"!=typeof e.min||e.min<0||e.min!==Math.round(e.min))throw new Error("Tarn: opt.min must be an integer >= 0");if("number"!=typeof e.max||e.max<=0||e.max!==Math.round(e.max))throw new Error("Tarn: opt.max must be an integer > 0");if(e.min>e.max)throw new Error("Tarn: opt.max is smaller than opt.min");if(!Vs.checkOptionalTime(e.acquireTimeoutMillis))throw new Error("Tarn: invalid opt.acquireTimeoutMillis "+JSON.stringify(e.acquireTimeoutMillis));if(!Vs.checkOptionalTime(e.createTimeoutMillis))throw new Error("Tarn: invalid opt.createTimeoutMillis "+JSON.stringify(e.createTimeoutMillis));if(!Vs.checkOptionalTime(e.destroyTimeoutMillis))throw new Error("Tarn: invalid opt.destroyTimeoutMillis "+JSON.stringify(e.destroyTimeoutMillis));if(!Vs.checkOptionalTime(e.idleTimeoutMillis))throw new Error("Tarn: invalid opt.idleTimeoutMillis "+JSON.stringify(e.idleTimeoutMillis));if(!Vs.checkOptionalTime(e.reapIntervalMillis))throw new Error("Tarn: invalid opt.reapIntervalMillis "+JSON.stringify(e.reapIntervalMillis));if(!Vs.checkOptionalTime(e.createRetryIntervalMillis))throw new Error("Tarn: invalid opt.createRetryIntervalMillis "+JSON.stringify(e.createRetryIntervalMillis));const t={create:!0,validate:!0,destroy:!0,log:!0,min:!0,max:!0,acquireTimeoutMillis:!0,createTimeoutMillis:!0,destroyTimeoutMillis:!0,idleTimeoutMillis:!0,reapIntervalMillis:!0,createRetryIntervalMillis:!0,propagateCreateError:!0};for(const s of Object.keys(e))if(!t[s])throw new Error(`Tarn: unsupported option opt.${s}`);this.creator=e.create,this.destroyer=e.destroy,this.validate="function"==typeof e.validate?e.validate:()=>!0,this.log=e.log||(()=>{}),this.acquireTimeoutMillis=e.acquireTimeoutMillis||3e4,this.createTimeoutMillis=e.createTimeoutMillis||3e4,this.destroyTimeoutMillis=e.destroyTimeoutMillis||5e3,this.idleTimeoutMillis=e.idleTimeoutMillis||3e4,this.reapIntervalMillis=e.reapIntervalMillis||1e3,this.createRetryIntervalMillis=e.createRetryIntervalMillis||200,this.propagateCreateError=!!e.propagateCreateError,this.min=e.min,this.max=e.max,this.used=[],this.free=[],this.pendingCreates=[],this.pendingAcquires=[],this.pendingDestroys=[],this.pendingValidations=[],this.destroyed=!1,this.interval=null,this.eventId=1}numUsed(){return this.used.length}numFree(){return this.free.length}numPendingAcquires(){return this.pendingAcquires.length}numPendingValidations(){return this.pendingValidations.length}numPendingCreates(){return this.pendingCreates.length}acquire(){const e=this.eventId++;this._executeEventHandlers("acquireRequest",e);const t=new Ps.PendingOperation(this.acquireTimeoutMillis);return this.pendingAcquires.push(t),t.promise=t.promise.then(t=>(this._executeEventHandlers("acquireSuccess",e,t),t)).catch(s=>(this._executeEventHandlers("acquireFail",e,s),Fs(this.pendingAcquires,t),Promise.reject(s))),this._tryAcquireOrCreate(),t}release(e){this._executeEventHandlers("release",e);for(let t=0,s=this.used.length;t<s;++t){const s=this.used[t];if(s.resource===e)return this.used.splice(t,1),this.free.push(s.resolve()),this._tryAcquireOrCreate(),!0}return!1}isEmpty(){return 0===[this.numFree(),this.numUsed(),this.numPendingAcquires(),this.numPendingValidations(),this.numPendingCreates()].reduce((e,t)=>e+t)}check(){const e=Vs.now(),t=[],s=this.min-this.used.length,r=this.free.length-s;let i=0;this.free.forEach(s=>{Vs.duration(e,s.timestamp)>=this.idleTimeoutMillis&&i<r?(i++,this._destroy(s.resource)):t.push(s)}),this.free=t,this.isEmpty()&&this._stopReaping()}destroy(){const e=this.eventId++;return this._executeEventHandlers("poolDestroyRequest",e),this._stopReaping(),this.destroyed=!0,Vs.reflect(Promise.all(this.pendingCreates.map(e=>Vs.reflect(e.promise))).then(()=>new Promise((e,t)=>{if(0===this.numPendingValidations())return void e();const s=setInterval(()=>{0===this.numPendingValidations()&&(Bs.clearInterval(s),e())},100)})).then(()=>Promise.all(this.used.map(e=>Vs.reflect(e.promise)))).then(()=>Promise.all(this.pendingAcquires.map(e=>(e.abort(),Vs.reflect(e.promise))))).then(()=>Promise.all(this.free.map(e=>Vs.reflect(this._destroy(e.resource))))).then(()=>Promise.all(this.pendingDestroys.map(e=>e.promise))).then(()=>{this.free=[],this.pendingAcquires=[]})).then(t=>(this._executeEventHandlers("poolDestroySuccess",e),this.emitter.removeAllListeners(),t))}on(e,t){this.emitter.on(e,t)}removeListener(e,t){this.emitter.removeListener(e,t)}removeAllListeners(e){this.emitter.removeAllListeners(e)}_tryAcquireOrCreate(){this.destroyed||(this._hasFreeResources()?this._doAcquire():this._shouldCreateMoreResources()&&this._doCreate())}_hasFreeResources(){return this.free.length>0}_doAcquire(){for(;this._canAcquire();){const e=this.pendingAcquires.shift(),t=this.free.pop();if(void 0===t||void 0===e){const e="this.free was empty w