diff --git a/forward_engineering/api.js b/forward_engineering/api.js index 5f28bc0..885c71f 100644 --- a/forward_engineering/api.js +++ b/forward_engineering/api.js @@ -1,9 +1,5 @@ -var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Object.getOwnPropertyNames;var pp=Object.prototype.hasOwnProperty;var i=(t,e)=>kt(t,"name",{value:e,configurable:!0});var mp=(t,e)=>()=>(t&&(e=t(t=0)),e);var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),dp=(t,e)=>{for(var r in e)kt(t,r,{get:e[r],enumerable:!0})},fp=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lp(e))!pp.call(t,s)&&s!==r&&kt(t,s,{get:()=>e[s],enumerable:!(n=up(e,s))||n.enumerable});return t};var hp=t=>fp(kt({},"__esModule",{value:!0}),t);var Nr=C((BT,zi)=>{var gp=i(({title:t,logger:e,hiddenKeys:r})=>({info(n,s={}){e.log("info",{message:n,...s},t,r)},progress(n,s="",a=""){e.progress({message:n,containerName:s,entityName:a})},error(n){e.log("error",yp(n),t)}}),"createLogger"),yp=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");zi.exports={createLogger:gp}});var Zi=C((GT,Xi)=>{var ft=1e3,ht=ft*60,gt=ht*60,yt=gt*24,_p=yt*365.25;Xi.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return Ep(t);if(r==="number"&&isNaN(t)===!1)return e.long?Sp(t):Tp(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Ep(t){if(t=String(t),!(t.length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*_p;case"days":case"day":case"d":return r*yt;case"hours":case"hour":case"hrs":case"hr":case"h":return r*gt;case"minutes":case"minute":case"mins":case"min":case"m":return r*ht;case"seconds":case"second":case"secs":case"sec":case"s":return r*ft;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}i(Ep,"parse");function Tp(t){return t>=yt?Math.round(t/yt)+"d":t>=gt?Math.round(t/gt)+"h":t>=ht?Math.round(t/ht)+"m":t>=ft?Math.round(t/ft)+"s":t+"ms"}i(Tp,"fmtShort");function Sp(t){return $t(t,yt,"day")||$t(t,gt,"hour")||$t(t,ht,"minute")||$t(t,ft,"second")||t+" ms"}i(Sp,"fmtLong");function $t(t,e,r){if(!(t{H=Ji.exports=vr.debug=vr.default=vr;H.coerce=vp;H.disable=Np;H.enable=Ap;H.enabled=bp;H.humanize=Zi();H.names=[];H.skips=[];H.formatters={};var br;function Cp(t){var e=0,r;for(r in t)e=(e<<5)-e+t.charCodeAt(r),e|=0;return H.colors[Math.abs(e)%H.colors.length]}i(Cp,"selectColor");function vr(t){function e(){if(e.enabled){var r=e,n=+new Date,s=n-(br||n);r.diff=s,r.prev=br,r.curr=n,br=n;for(var a=new Array(arguments.length),o=0;o{de=ta.exports=Ir();de.log=Rp;de.formatArgs=Op;de.save=wp;de.load=ea;de.useColors=Ip;de.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:Dp();de.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function Ip(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}i(Ip,"useColors");de.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}};function Op(t){var e=this.useColors;if(t[0]=(e?"%c":"")+this.namespace+(e?" %c":" ")+t[0]+(e?"%c ":" ")+"+"+de.humanize(this.diff),!!e){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,function(a){a!=="%%"&&(n++,a==="%c"&&(s=n))}),t.splice(s,0,r)}}i(Op,"formatArgs");function Rp(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}i(Rp,"log");function wp(t){try{t==null?de.storage.removeItem("debug"):de.storage.debug=t}catch{}}i(wp,"save");function ea(){var t;try{t=de.storage.debug}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}i(ea,"load");de.enable(ea());function Dp(){try{return window.localStorage}catch{}}i(Dp,"localstorage")});var aa=C((oe,ia)=>{var na=require("tty"),_t=require("util");oe=ia.exports=Ir();oe.init=Up;oe.log=Lp;oe.formatArgs=Pp;oe.save=Mp;oe.load=sa;oe.useColors=xp;oe.colors=[6,2,3,4,5,1];oe.inspectOpts=Object.keys(process.env).filter(function(t){return/^debug_/i.test(t)}).reduce(function(t,e){var r=e.substring(6).toLowerCase().replace(/_([a-z])/g,function(s,a){return a.toUpperCase()}),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});var Xe=parseInt(process.env.DEBUG_FD,10)||2;Xe!==1&&Xe!==2&&_t.deprecate(function(){},"except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();var qp=Xe===1?process.stdout:Xe===2?process.stderr:Fp(Xe);function xp(){return"colors"in oe.inspectOpts?!!oe.inspectOpts.colors:na.isatty(Xe)}i(xp,"useColors");oe.formatters.o=function(t){return this.inspectOpts.colors=this.useColors,_t.inspect(t,this.inspectOpts).split(` -`).map(function(e){return e.trim()}).join(" ")};oe.formatters.O=function(t){return this.inspectOpts.colors=this.useColors,_t.inspect(t,this.inspectOpts)};function Pp(t){var e=this.namespace,r=this.useColors;if(r){var n=this.color,s=" \x1B[3"+n+";1m"+e+" \x1B[0m";t[0]=s+t[0].split(` -`).join(` -`+s),t.push("\x1B[3"+n+"m+"+oe.humanize(this.diff)+"\x1B[0m")}else t[0]=new Date().toUTCString()+" "+e+" "+t[0]}i(Pp,"formatArgs");function Lp(){return qp.write(_t.format.apply(_t,arguments)+` -`)}i(Lp,"log");function Mp(t){t==null?delete process.env.DEBUG:process.env.DEBUG=t}i(Mp,"save");function sa(){return process.env.DEBUG}i(sa,"load");function Fp(t){var e,r=process.binding("tty_wrap");switch(r.guessHandleType(t)){case"TTY":e=new na.WriteStream(t),e._type="tty",e._handle&&e._handle.unref&&e._handle.unref();break;case"FILE":var n=require("fs");e=new n.SyncWriteStream(t,{autoClose:!1}),e._type="fs";break;case"PIPE":case"TCP":var s=require("net");e=new s.Socket({fd:t,readable:!1,writable:!0}),e.readable=!1,e.read=null,e._type="pipe",e._handle&&e._handle.unref&&e._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return e.fd=t,e._isStdio=!0,e}i(Fp,"createWritableStdioStream");function Up(t){t.inspectOpts={};for(var e=Object.keys(oe.inspectOpts),r=0;r{typeof process<"u"&&process.type==="renderer"?Or.exports=ra():Or.exports=aa()});var oa=C(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.default=null});var ha=C((zT,fa)=>{var ua=9007199254740991,kp="[object Arguments]",$p="[object Function]",Bp="[object GeneratorFunction]",Kp=/^(?:0|[1-9]\d*)$/;function la(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}i(la,"apply");function Gp(t,e){for(var r=-1,n=Array(t);++r1?r[s-1]:void 0,o=s>2?r[2]:void 0;for(a=t.length>3&&typeof a=="function"?(s--,a):void 0,o&&Xp(r[0],r[1],o)&&(a=s<3?void 0:a,s=1),e=Object(e);++n-1&&t%1==0&&t-1&&t%1==0&&t<=ua}i(sm,"isLength");function xr(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}i(xr,"isObject");function im(t){return!!t&&typeof t=="object"}i(im,"isObjectLike");var am=zp(function(t,e,r,n){jp(e,cm(e),t,n)}),om=ma(function(t){return t.push(void 0,Wp),la(am,void 0,t)});function cm(t){return qr(t)?Hp(t,!0):Yp(t)}i(cm,"keysIn");fa.exports=om});var ya=C((ZT,ga)=>{var um=require("util"),lm=ha(),pm=Rr()("tunnel-ssh-config"),Pr=i(function(t,e){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t,this.extra=e},"ConfigError");um.inherits(Pr,Error);function mm(t){var e=process.env;if(lm(t||{},{username:e.TUNNELSSH_USER||e.USER||e.USERNAME||"root",port:22,host:null,srcPort:0,srcHost:"127.0.0.1",dstPort:null,dstHost:"127.0.0.1",localHost:"127.0.0.1",localPort:t.dstPort,agent:process.env.SSH_AUTH_SOCK}),!t.host)throw new Pr("host not set");if(!t.dstPort)throw new Pr("dstPort not set");return pm("ssh-config",function(){var r=["password","privateKey"];return Object.keys(t).reduce(function(n,s){return r.indexOf(s)===-1?n[s]=t[s]:n[s]="***HIDDEN***",n},{})}()),t}i(mm,"createConfig");ga.exports=mm});var Ea=C((eS,_a)=>{var dm=require("net"),Lr=Rr()("tunnel-ssh"),fm=oa().Client,hm=ya(),gm=require("events"),ym=i(function(){},"noop");function _m(t,e){var r=new fm;return e.on("close",r.end.bind(r)),r.on("ready",function(){Lr("sshConnection:ready"),e.emit("sshConnection",r,e),r.forwardOut(t.srcHost,t.srcPort,t.dstHost,t.dstPort,function(n,s){if(n){e.emit("error",n),Lr("Destination port:",n);return}Lr("sshStream:create"),e.emit("sshStream",s),e.pipe(s).pipe(e)})}),r}i(_m,"bindSSHConnection");function Em(t,e){return e.reduce(function(r,n){return delete r[n],r},Object.assign({},t))}i(Em,"omit");function Tm(t){var e,r=[],n=0;return e=dm.createServer(function(s){var a;n++,s.on("error",e.emit.bind(e,"error")),s.on("close",function(){n--,n===0&&(t.keepAlive||setTimeout(function(){n===0&&e.close()},2))}),e.emit("netConnection",s,e),a=_m(t,s),a.on("error",e.emit.bind(e,"error")),s.on("sshStream",function(o){o.on("error",function(){e.close()})}),r.push(a,s);try{a.connect(Em(t,["localPort","localHost"]))}catch(o){e.emit("error",o)}}),e.on("close",function(){r.forEach(function(s){s.end()})}),e}i(Tm,"createServer");function Sm(t,e){var r,n;e||(e=ym);try{n=hm(t),r=Tm(n),r.listen(n.localPort,n.localHost,function(s){e(s,r)})}catch(s){r=new gm.EventEmitter,setImmediate(function(){e(s),r.emit("error",s)})}return r}i(Sm,"tunnel");_a.exports=Sm});var Fr=C(Ta=>{"use strict";Ta.parse=function(t,e){return new Mr(t,e).parse()};var Bt=class Bt{constructor(e,r){this.source=e,this.transform=r||Cm,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new Bt(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(Bt,"ArrayParser");var Mr=Bt;function Cm(t){return t}i(Cm,"identity")});var Ur=C((sS,Sa)=>{var Am=Fr();Sa.exports={create:i(function(t,e){return{parse:i(function(){return Am.parse(t,e)},"parse")}},"create")}});var Na=C((aS,Aa)=>{"use strict";var Nm=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,bm=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,vm=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Im=/^-?infinity$/;Aa.exports=i(function(e){if(Im.test(e))return Number(e.replace("i","I"));var r=Nm.exec(e);if(!r)return Om(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=Ca(s));var a=parseInt(r[2],10)-1,o=r[3],c=parseInt(r[4],10),u=parseInt(r[5],10),l=parseInt(r[6],10),p=r[7];p=p?1e3*parseFloat(p):0;var m,d=Rm(e);return d!=null?(m=new Date(Date.UTC(s,a,o,c,u,l,p)),kr(s)&&m.setUTCFullYear(s),d!==0&&m.setTime(m.getTime()-d)):(m=new Date(s,a,o,c,u,l,p),kr(s)&&m.setFullYear(s)),m},"parseDate");function Om(t){var e=bm.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=Ca(r));var s=parseInt(e[2],10)-1,a=e[3],o=new Date(r,s,a);return kr(r)&&o.setFullYear(r),o}}i(Om,"getDate");function Rm(t){if(t.endsWith("+00"))return 0;var e=vm.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}i(Rm,"timeZoneOffset");function Ca(t){return-(t-1)}i(Ca,"bcYearToNegativeYear");function kr(t){return t>=0&&t<100}i(kr,"is0To99")});var va=C((cS,ba)=>{ba.exports=Dm;var wm=Object.prototype.hasOwnProperty;function Dm(t){for(var e=1;e{"use strict";var qm=va();Oa.exports=Ze;function Ze(t){if(!(this instanceof Ze))return new Ze(t);qm(this,Vm(t))}i(Ze,"PostgresInterval");var xm=["seconds","minutes","hours","days","months","years"];Ze.prototype.toPostgres=function(){var t=xm.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var Pm={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Lm=["years","months","days"],Mm=["hours","minutes","seconds"];Ze.prototype.toISOString=Ze.prototype.toISO=function(){var t=Lm.map(r,this).join(""),e=Mm.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+Pm[n]}};var $r="([+-]?\\d+)",Fm=$r+"\\s+years?",Um=$r+"\\s+mons?",km=$r+"\\s+days?",$m="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Bm=new RegExp([Fm,Um,km,$m].map(function(t){return"("+t+")?"}).join("\\s*")),Ia={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Km=["hours","minutes","seconds","milliseconds"];function Gm(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(Gm,"parseMilliseconds");function Vm(t){if(!t)return{};var e=Bm.exec(t),r=e[8]==="-";return Object.keys(Ia).reduce(function(n,s){var a=Ia[s],o=e[a];return!o||(o=s==="milliseconds"?Gm(o):parseInt(o,10),!o)||(r&&~Km.indexOf(s)&&(o*=-1),n[s]=o),n},{})}i(Vm,"parse")});var Da=C((mS,wa)=>{"use strict";wa.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",n=0;n{var St=Fr(),Ct=Ur(),Kt=Na(),xa=Ra(),Pa=Da();function Gt(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(Gt,"allowNull");function La(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(La,"parseBool");function Hm(t){return t?St.parse(t,La):null}i(Hm,"parseBoolArray");function Wm(t){return parseInt(t,10)}i(Wm,"parseBaseTenInt");function Br(t){return t?St.parse(t,Gt(Wm)):null}i(Br,"parseIntegerArray");function Qm(t){return t?St.parse(t,Gt(function(e){return Ma(e).trim()})):null}i(Qm,"parseBigIntegerArray");var Ym=i(function(t){if(!t)return null;var e=Ct.create(t,function(r){return r!==null&&(r=Hr(r)),r});return e.parse()},"parsePointArray"),Kr=i(function(t){if(!t)return null;var e=Ct.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),Ne=i(function(t){if(!t)return null;var e=Ct.create(t);return e.parse()},"parseStringArray"),Gr=i(function(t){if(!t)return null;var e=Ct.create(t,function(r){return r!==null&&(r=Kt(r)),r});return e.parse()},"parseDateArray"),jm=i(function(t){if(!t)return null;var e=Ct.create(t,function(r){return r!==null&&(r=xa(r)),r});return e.parse()},"parseIntervalArray"),zm=i(function(t){return t?St.parse(t,Gt(Pa)):null},"parseByteAArray"),Vr=i(function(t){return parseInt(t,10)},"parseInteger"),Ma=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),qa=i(function(t){return t?St.parse(t,Gt(JSON.parse)):null},"parseJsonArray"),Hr=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),Xm=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s{"use strict";var ge=1e6;function Jm(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",a,o,c,u,l,p;{if(a=e%ge,e=e/ge>>>0,o=4294967296*a+r,r=o/ge>>>0,c=""+(o-ge*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/ge>>>0,c=""+(o-ge*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/ge>>>0,c=""+(o-ge*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p{var ed=$a(),Y=i(function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(f,h,T){return f*Math.pow(2,T)+h};var a=r>>3,o=i(function(f){return n?~f&255:f},"inv"),c=255,u=8-r%8;e>r%8);var l=0;r%8+e>=8&&(l=s(0,o(t[a])&c,u));for(var p=e+r>>3,m=a+1;m0&&(l=s(l,o(t[p])>>8-d,d)),l},"parseBits"),Ga=i(function(t,e,r){var n=Math.pow(2,r-1)-1,s=Y(t,1),a=Y(t,r,1);if(a===0)return 0;var o=1,c=i(function(l,p,m){l===0&&(l=1);for(var d=1;d<=m;d++)o/=2,(p&1<0&&(l+=o);return l},"parsePrecisionBits"),u=Y(t,e,r+1,!1,c);return a==Math.pow(2,r+1)-1?u===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,a-n)*u},"parseFloatFromBits"),td=i(function(t){return Y(t,1)==1?-1*(Y(t,15,1,!0)+1):Y(t,15,1)},"parseInt16"),Ba=i(function(t){return Y(t,1)==1?-1*(Y(t,31,1,!0)+1):Y(t,31,1)},"parseInt32"),rd=i(function(t){return Ga(t,23,8)},"parseFloat32"),nd=i(function(t){return Ga(t,52,11)},"parseFloat64"),sd=i(function(t){var e=Y(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,Y(t,16,16)),n=0,s=[],a=Y(t,16),o=0;o>3,(s+=p<<3)>>3),m;console.log("ERROR: ElementType not implemented: "+l)},"parseElement"),u=i(function(l,p){var m=[],d;if(l.length>1){var f=l.shift();for(d=0;d0},"parseBool"),od=i(function(t){t(20,ed),t(21,td),t(23,Ba),t(26,Ba),t(1700,sd),t(700,rd),t(701,nd),t(16,ad),t(1114,Ka.bind(null,!1)),t(1184,Ka.bind(null,!0)),t(1e3,At),t(1007,At),t(1016,At),t(1008,At),t(1009,At),t(25,id)},"init");Va.exports={init:od}});var Qa=C((TS,Wa)=>{Wa.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var vt=C(bt=>{var cd=Ua(),ud=Ha(),ld=Ur(),pd=Qa();bt.getTypeParser=md;bt.setTypeParser=dd;bt.arrayParser=ld;bt.builtins=pd;var Nt={text:{},binary:{}};function Ya(t){return String(t)}i(Ya,"noParse");function md(t,e){return e=e||"text",Nt[e]&&Nt[e][t]||Ya}i(md,"getTypeParser");function dd(t,e,r){typeof e=="function"&&(r=e,e="text"),Nt[e][t]=r}i(dd,"setTypeParser");cd.init(function(t,e){Nt.text[t]=e});ud.init(function(t,e){Nt.binary[t]=e})});var It=C((AS,Wr)=>{"use strict";Wr.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Je=vt(),fd=Je.getTypeParser(20,"text"),hd=Je.getTypeParser(1016,"text");Wr.exports.__defineSetter__("parseInt8",function(t){Je.setTypeParser(20,"text",t?Je.getTypeParser(23,"text"):fd),Je.setTypeParser(1016,"text",t?Je.getTypeParser(1007,"text"):hd)})});var Ot=C((NS,za)=>{"use strict";var gd=It();function yd(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(yd,"escapeElement");function ja(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+ja(t[r]);else if(ArrayBuffer.isView(t[r])){var n=t[r];if(!(n instanceof Buffer)){var s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=yd(Vt(t[r]));return e=e+"}",e}i(ja,"arrayString");var Vt=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?gd.parseInputDatesAsUTC?Td(t):Ed(t):Array.isArray(t)?ja(t):typeof t=="object"?_d(t,e):t.toString()},"prepareValue");function _d(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Vt(t.toPostgres(Vt),e)}return JSON.stringify(t)}i(_d,"prepareObject");function pe(t,e){for(t=""+t;t.length{"use strict";var Rt=require("crypto");function Qr(t){return Rt.createHash("md5").update(t,"utf-8").digest("hex")}i(Qr,"md5");function Nd(t,e,r){var n=Qr(e+t),s=Qr(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(Nd,"postgresMd5PasswordHash");function bd(t){return Rt.createHash("sha256").update(t).digest()}i(bd,"sha256");function vd(t,e){return Rt.createHmac("sha256",t).update(e).digest()}i(vd,"hmacSha256");async function Id(t,e,r){return Rt.pbkdf2Sync(t,e,r,32,"sha256")}i(Id,"deriveKey");Xa.exports={postgresMd5PasswordHash:Nd,randomBytes:Rt.randomBytes,deriveKey:Id,sha256:bd,hmacSha256:vd,md5:Qr}});var ro=C((OS,to)=>{var Ja=require("crypto");to.exports={postgresMd5PasswordHash:Rd,randomBytes:Od,deriveKey:qd,sha256:wd,hmacSha256:Dd,md5:Yr};var eo=Ja.webcrypto||globalThis.crypto,et=eo.subtle,jr=new TextEncoder;function Od(t){return eo.getRandomValues(Buffer.alloc(t))}i(Od,"randomBytes");async function Yr(t){try{return Ja.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?jr.encode(t):t,n=await et.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}i(Yr,"md5");async function Rd(t,e,r){var n=await Yr(e+t),s=await Yr(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(Rd,"postgresMd5PasswordHash");async function wd(t){return await et.digest("SHA-256",t)}i(wd,"sha256");async function Dd(t,e){let r=await et.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await et.sign("HMAC",r,jr.encode(e))}i(Dd,"hmacSha256");async function qd(t,e,r){let n=await et.importKey("raw",jr.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await et.deriveBits(s,n,32*8,["deriveBits"])}i(qd,"deriveKey")});var Xr=C((wS,zr)=>{"use strict";var xd=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;xd?zr.exports=Za():zr.exports=ro()});var ao=C((DS,io)=>{"use strict";var We=Xr();function Pd(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=We.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Pd,"startSession");async function Ld(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let n=Ud(r);if(n.nonce.startsWith(t.clientNonce)){if(n.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var s="n=*,r="+t.clientNonce,a="r="+n.nonce+",s="+n.salt+",i="+n.iteration,o="c=biws,r="+n.nonce,c=s+","+a+","+o,u=Buffer.from(n.salt,"base64"),l=await We.deriveKey(e,u,n.iteration),p=await We.hmacSha256(l,"Client Key"),m=await We.sha256(p),d=await We.hmacSha256(m,c),f=$d(Buffer.from(p),Buffer.from(d)).toString("base64"),h=await We.hmacSha256(l,"Server Key"),T=await We.hmacSha256(h,c);t.message="SASLResponse",t.serverSignature=Buffer.from(T).toString("base64"),t.response=o+",p="+f}i(Ld,"continueSession");function Md(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=kd(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i(Md,"finalizeSession");function Fd(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(Fd,"isPrintableChars");function no(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(no,"isBase64");function so(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}i(so,"parseAttributePairs");function Ud(t){let e=so(t),r=e.get("r");if(r){if(!Fd(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!no(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let a=parseInt(s,10);return{nonce:r,salt:n,iteration:a}}i(Ud,"parseServerFirstMessage");function kd(t){let r=so(t).get("v");if(r){if(!no(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(kd,"parseServerFinalMessage");function $d(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}i($d,"xorBuffers");io.exports={startSession:Pd,continueSession:Ld,finalizeSession:Md}});var Zr=C((xS,oo)=>{"use strict";var Bd=vt();function Ht(t){this._types=t||Bd,this.text={},this.binary={}}i(Ht,"TypeOverrides");Ht.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Ht.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Ht.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};oo.exports=Ht});var uo=C((LS,co)=>{"use strict";function Jr(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,n=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),n=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let s=n?"":r.hostname;e.host?s&&/^%2f/i.test(s)&&(r.pathname=s+r.pathname):e.host=decodeURIComponent(s),e.port||(e.port=r.port);let a=r.pathname.slice(1)||null;e.database=a?decodeURI(a):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let o=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=o.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=o.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=o.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(Jr,"parse");co.exports=Jr;Jr.parse=Jr});var rn=C((FS,mo)=>{"use strict";var Kd=require("dns"),po=It(),lo=uo().parse,fe=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||po[t]},"val"),Gd=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return po.ssl},"readSSLConfigFromEnvironment"),tt=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),be=i(function(t,e,r){var n=e[r];n!=null&&t.push(r+"="+tt(n))},"add"),tn=class tn{constructor(e){e=typeof e=="string"?lo(e):e||{},e.connectionString&&(e=Object.assign({},e,lo(e.connectionString))),this.user=fe("user",e),this.database=fe("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(fe("port",e),10),this.host=fe("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:fe("password",e)}),this.binary=fe("binary",e),this.options=fe("options",e),this.ssl=typeof e.ssl>"u"?Gd():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=fe("client_encoding",e),this.replication=fe("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=fe("application_name",e,"PGAPPNAME"),this.fallback_application_name=fe("fallback_application_name",e,!1),this.statement_timeout=fe("statement_timeout",e,!1),this.lock_timeout=fe("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=fe("idle_in_transaction_session_timeout",e,!1),this.query_timeout=fe("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];be(r,this,"user"),be(r,this,"password"),be(r,this,"port"),be(r,this,"application_name"),be(r,this,"fallback_application_name"),be(r,this,"connect_timeout"),be(r,this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(be(r,n,"sslmode"),be(r,n,"sslca"),be(r,n,"sslkey"),be(r,n,"sslcert"),be(r,n,"sslrootcert"),this.database&&r.push("dbname="+tt(this.database)),this.replication&&r.push("replication="+tt(this.replication)),this.host&&r.push("host="+tt(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+tt(this.client_encoding)),Kd.lookup(this.host,function(s,a){return s?e(s,null):(r.push("hostaddr="+tt(a)),e(null,r.join(" ")))})}};i(tn,"ConnectionParameters");var en=tn;mo.exports=en});var go=C((kS,ho)=>{"use strict";var Vd=vt(),fo=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,sn=class sn{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=fo.exec(e.text):r=fo.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),n=0,s=e.length;n{"use strict";var{EventEmitter:Hd}=require("events"),yo=go(),_o=Ot(),on=class on extends Hd{constructor(e,r,n){super(),e=_o.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new yo(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new yo(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:_o.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(on,"Query");var an=on;Eo.exports=an});var Mn=C(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.NoticeMessage=F.DataRowMessage=F.CommandCompleteMessage=F.ReadyForQueryMessage=F.NotificationResponseMessage=F.BackendKeyDataMessage=F.AuthenticationMD5Password=F.ParameterStatusMessage=F.ParameterDescriptionMessage=F.RowDescriptionMessage=F.Field=F.CopyResponse=F.CopyDataMessage=F.DatabaseError=F.copyDone=F.emptyQuery=F.replicationStart=F.portalSuspended=F.noData=F.closeComplete=F.bindComplete=F.parseComplete=void 0;F.parseComplete={name:"parseComplete",length:5};F.bindComplete={name:"bindComplete",length:5};F.closeComplete={name:"closeComplete",length:5};F.noData={name:"noData",length:5};F.portalSuspended={name:"portalSuspended",length:5};F.replicationStart={name:"replicationStart",length:4};F.emptyQuery={name:"emptyQuery",length:4};F.copyDone={name:"copyDone",length:4};var Cn=class Cn extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};i(Cn,"DatabaseError");var cn=Cn;F.DatabaseError=cn;var An=class An{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(An,"CopyDataMessage");var un=An;F.CopyDataMessage=un;var Nn=class Nn{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};i(Nn,"CopyResponse");var ln=Nn;F.CopyResponse=ln;var bn=class bn{constructor(e,r,n,s,a,o,c){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=a,this.dataTypeModifier=o,this.format=c}};i(bn,"Field");var pn=bn;F.Field=pn;var vn=class vn{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(vn,"RowDescriptionMessage");var mn=vn;F.RowDescriptionMessage=mn;var In=class In{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(In,"ParameterDescriptionMessage");var dn=In;F.ParameterDescriptionMessage=dn;var On=class On{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};i(On,"ParameterStatusMessage");var fn=On;F.ParameterStatusMessage=fn;var Rn=class Rn{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(Rn,"AuthenticationMD5Password");var hn=Rn;F.AuthenticationMD5Password=hn;var wn=class wn{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};i(wn,"BackendKeyDataMessage");var gn=wn;F.BackendKeyDataMessage=gn;var Dn=class Dn{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};i(Dn,"NotificationResponseMessage");var yn=Dn;F.NotificationResponseMessage=yn;var qn=class qn{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(qn,"ReadyForQueryMessage");var _n=qn;F.ReadyForQueryMessage=_n;var xn=class xn{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(xn,"CommandCompleteMessage");var En=xn;F.CommandCompleteMessage=En;var Pn=class Pn{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(Pn,"DataRowMessage");var Tn=Pn;F.DataRowMessage=Tn;var Ln=class Ln{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(Ln,"NoticeMessage");var Sn=Ln;F.NoticeMessage=Sn});var So=C(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.Writer=void 0;var Un=class Un{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(s),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(Un,"Writer");var Fn=Un;Wt.Writer=Fn});var Ao=C(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.serialize=void 0;var kn=So(),j=new kn.Writer,Wd=i(t=>{j.addInt16(3).addInt16(0);for(let n of Object.keys(t))j.addCString(n).addCString(t[n]);j.addCString("client_encoding").addCString("UTF8");var e=j.addCString("").flush(),r=e.length+4;return new kn.Writer().addInt32(r).add(e).flush()},"startup"),Qd=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),Yd=i(t=>j.addCString(t).flush(112),"password"),jd=i(function(t,e){return j.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),j.flush(112)},"sendSASLInitialResponseMessage"),zd=i(function(t){return j.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),Xd=i(t=>j.addCString(t).flush(81),"query"),Co=[],Zd=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||Co;for(var n=r.length,s=j.addCString(e).addCString(t.text).addInt16(n),a=0;a{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||Co,a=s.length;return j.addCString(e).addCString(r),j.addInt16(a),Jd(s,t.valueMapper),j.addInt16(a),j.add(rt.flush()),j.addInt16(n?1:0),j.flush(66)},"bind"),tf=Buffer.from([69,0,0,0,9,0,0,0,0,0]),rf=i(t=>{if(!t||!t.portal&&!t.rows)return tf;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,a=Buffer.allocUnsafe(1+s);return a[0]=69,a.writeInt32BE(s,1),a.write(e,5,"utf-8"),a[n+5]=0,a.writeUInt32BE(r,a.length-4),a},"execute"),nf=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),$n=i((t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},"cstringMessage"),sf=j.addCString("P").flush(68),af=j.addCString("S").flush(68),of=i(t=>t.name?$n(68,`${t.type}${t.name||""}`):t.type==="P"?sf:af,"describe"),cf=i(t=>{let e=`${t.type}${t.name||""}`;return $n(67,e)},"close"),uf=i(t=>j.add(t).flush(100),"copyData"),lf=i(t=>$n(102,t),"copyFail"),Qt=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),pf=Qt(72),mf=Qt(83),df=Qt(88),ff=Qt(99),hf={startup:Wd,password:Yd,requestSsl:Qd,sendSASLInitialResponseMessage:jd,sendSCRAMClientFinalMessage:zd,query:Xd,parse:Zd,bind:ef,execute:rf,describe:of,close:cf,flush:i(()=>pf,"flush"),sync:i(()=>mf,"sync"),end:i(()=>df,"end"),copyData:uf,copyDone:i(()=>ff,"copyDone"),copyFail:lf,cancel:nf};Yt.serialize=hf});var No=C(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.BufferReader=void 0;var gf=Buffer.allocUnsafe(0),Kn=class Kn{constructor(e=0){this.offset=e,this.buffer=gf,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(Kn,"BufferReader");var Bn=Kn;jt.BufferReader=Bn});var Io=C(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Parser=void 0;var z=Mn(),yf=No(),Gn=1,_f=4,bo=Gn+_f,vo=Buffer.allocUnsafe(0),Hn=class Hn{constructor(e){if(this.buffer=vo,this.bufferLength=0,this.bufferOffset=0,this.reader=new yf.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+bo<=n;){let a=this.buffer[s],o=this.buffer.readUInt32BE(s+Gn),c=Gn+o;if(c+s<=n){let u=this.handlePacket(s+bo,a,o,this.buffer);r(u),s+=c}else break}s===n?(this.buffer=vo,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let a=this.buffer.byteLength*2;for(;r>=a;)a*=2;s=Buffer.allocUnsafe(a)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){switch(r){case 50:return z.bindComplete;case 49:return z.parseComplete;case 51:return z.closeComplete;case 110:return z.noData;case 115:return z.portalSuspended;case 99:return z.copyDone;case 87:return z.replicationStart;case 73:return z.emptyQuery;case 68:return this.parseDataRowMessage(e,n,s);case 67:return this.parseCommandCompleteMessage(e,n,s);case 90:return this.parseReadyForQueryMessage(e,n,s);case 65:return this.parseNotificationMessage(e,n,s);case 82:return this.parseAuthenticationResponse(e,n,s);case 83:return this.parseParameterStatusMessage(e,n,s);case 75:return this.parseBackendKeyData(e,n,s);case 69:return this.parseErrorMessage(e,n,s,"error");case 78:return this.parseErrorMessage(e,n,s,"notice");case 84:return this.parseRowDescriptionMessage(e,n,s);case 116:return this.parseParameterDescriptionMessage(e,n,s);case 71:return this.parseCopyInMessage(e,n,s);case 72:return this.parseCopyOutMessage(e,n,s);case 100:return this.parseCopyData(e,n,s);default:return new z.DatabaseError("received invalid response: "+r.toString(16),n,"error")}}parseReadyForQueryMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.string(1);return new z.ReadyForQueryMessage(r,s)}parseCommandCompleteMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.cstring();return new z.CommandCompleteMessage(r,s)}parseCopyData(e,r,n){let s=n.slice(e,e+(r-4));return new z.CopyDataMessage(r,s)}parseCopyInMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyInResponse")}parseCopyOutMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyOutResponse")}parseCopyMessage(e,r,n,s){this.reader.setBuffer(e,n);let a=this.reader.byte()!==0,o=this.reader.int16(),c=new z.CopyResponse(r,s,a,o);for(let u=0;u{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.DatabaseError=$e.serialize=$e.parse=void 0;var Ef=Mn();Object.defineProperty($e,"DatabaseError",{enumerable:!0,get:i(function(){return Ef.DatabaseError},"get")});var Tf=Ao();Object.defineProperty($e,"serialize",{enumerable:!0,get:i(function(){return Tf.serialize},"get")});var Sf=Io();function Cf(t,e){let r=new Sf.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}i(Cf,"parse");$e.parse=Cf});var Oo={};dp(Oo,{default:()=>Af});var Af,Ro=mp(()=>{Af={}});var wo=C((tC,Qn)=>{Qn.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:n}=(Ro(),hp(Oo));return new n(e)}},"getStream");Qn.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var zn=C((sC,Do)=>{"use strict";var nC=require("net"),Nf=require("events").EventEmitter,{parse:bf,serialize:ce}=Wn(),{getStream:vf,getSecureStream:If}=wo(),Of=ce.flush(),Rf=ce.sync(),wf=ce.end(),jn=class jn extends Nf{constructor(e){super(),e=e||{},this.stream=e.stream||vf(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=i(function(a){n._ending&&(a.code==="ECONNRESET"||a.code==="EPIPE")||n.emit("error",a)},"reportStreamError");if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(a){var o=a.toString("utf8");switch(o){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:n.stream};n.ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key));var u=require("net");u.isIP&&u.isIP(r)===0&&(c.servername=r);try{n.stream=If(c)}catch(l){return n.emit("error",l)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){bf(e,r=>{var n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(ce.requestSsl())}startup(e){this.stream.write(ce.startup(e))}cancel(e,r){this._send(ce.cancel(e,r))}password(e){this._send(ce.password(e))}sendSASLInitialResponseMessage(e,r){this._send(ce.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(ce.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(ce.query(e))}parse(e){this._send(ce.parse(e))}bind(e){this._send(ce.bind(e))}execute(e){this._send(ce.execute(e))}flush(){this.stream.writable&&this.stream.write(Of)}sync(){this._ending=!0,this._send(Rf)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(wf,()=>{this.stream.end()})}close(e){this._send(ce.close(e))}describe(e){this._send(ce.describe(e))}sendCopyFromChunk(e){this._send(ce.copyData(e))}endCopyFrom(){this._send(ce.copyDone())}sendCopyFail(e){this._send(ce.copyFail(e))}};i(jn,"Connection");var Yn=jn;Do.exports=Yn});var Lo=C((aC,Po)=>{"use strict";var{Transform:Df}=require("stream"),{StringDecoder:qf}=require("string_decoder"),Be=Symbol("last"),Xt=Symbol("decoder");function xf(t,e,r){let n;if(this.overflow){if(n=this[Xt].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[Be]+=this[Xt].write(t),n=this[Be].split(this.matcher);this[Be]=n.pop();for(let s=0;sthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(xf,"transform");function Pf(t){if(this[Be]+=this[Xt].end(),this[Be])try{xo(this,this.mapper(this[Be]))}catch(e){return t(e)}t()}i(Pf,"flush");function xo(t,e){e!==void 0&&t.push(e)}i(xo,"push");function qo(t){return t}i(qo,"noop");function Lf(t,e,r){switch(t=t||/\r?\n/,e=e||qo,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=qo)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=xf,r.flush=Pf,r.readableObjectMode=!0;let n=new Df(r);return n[Be]="",n[Xt]=new qf("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,a){this._writableState.errorEmitted=!1,a(s)},n}i(Lf,"split");Po.exports=Lf});var Uo=C((cC,Ue)=>{"use strict";var Mo=require("path"),Mf=require("stream").Stream,Ff=Lo(),Fo=require("util"),Uf=5432,Zt=process.platform==="win32",wt=process.stderr,kf=56,$f=7,Bf=61440,Kf=32768;function Gf(t){return(t&Bf)==Kf}i(Gf,"isRegFile");var nt=["host","port","database","user","password"],Xn=nt.length,Vf=nt[Xn-1];function Zn(){var t=wt instanceof Mf&&wt.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` -`);wt.write(Fo.format.apply(Fo,e))}}i(Zn,"warn");Object.defineProperty(Ue.exports,"isWin",{get:i(function(){return Zt},"get"),set:i(function(t){Zt=t},"set")});Ue.exports.warnTo=function(t){var e=wt;return wt=t,e};Ue.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(Zt?Mo.join(e.APPDATA||"./","postgresql","pgpass.conf"):Mo.join(e.HOME||"./",".pgpass"));return r};Ue.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Zt?!0:(e=e||"",Gf(t.mode)?t.mode&(kf|$f)?(Zn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Zn('WARNING: password file "%s" is not a plain file',e),!1))};var Hf=Ue.exports.match=function(t,e){return nt.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||Uf)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};Ue.exports.getPassword=function(t,e,r){var n,s=e.pipe(Ff());function a(u){var l=Wf(u);l&&Qf(l)&&Hf(t,l)&&(n=l[Vf],s.end())}i(a,"onLine");var o=i(function(){e.destroy(),r(n)},"onEnd"),c=i(function(u){e.destroy(),Zn("WARNING: error on reading file: %s",u),r(void 0)},"onErr");e.on("error",c),s.on("data",a).on("end",o).on("error",c)};var Wf=Ue.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,a=0,o={},c=!1,u=i(function(p,m,d){var f=t.substring(m,d);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(f=f.replace(/\\([:\\])/g,"$1")),o[nt[p]]=f},"addToObj"),l=0;l=0&&e==":"&&r!=="\\"&&(u(n,s,l+1),s=l+2,n+=1)}return o=Object.keys(o).length===Xn?o:null,o},Qf=Ue.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r{"use strict";var lC=require("path"),ko=require("fs"),Jt=Uo();Jn.exports=function(t,e){var r=Jt.getFileName();ko.stat(r,function(n,s){if(n||!Jt.usePgPass(s,r))return e(void 0);var a=ko.createReadStream(r);Jt.getPassword(t,a,e)})};Jn.exports.warnTo=Jt.warnTo});var Vo=C((mC,Go)=>{"use strict";var Yf=require("events").EventEmitter,Bo=Ot(),es=ao(),jf=Zr(),zf=rn(),Ko=To(),Xf=It(),Zf=zn(),Jf=Xr(),ts=class ts extends Yf{constructor(e){super(),this.connectionParameters=new zf(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new jf(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new Zf({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||Xf.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(n=>{process.nextTick(()=>{n.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{r.emit("error",n)});else if(this.password!==null)e();else try{$o()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await Jf.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=es.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await es.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{es.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Bo.escapeIdentifier(e)}escapeLiteral(e){return Bo.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,n){var s,a,o,c,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,a=s=e,typeof r=="function"&&(s.callback=s.callback||r)):(o=this.connectionParameters.query_timeout,s=new Ko(e,r,n),s.callback||(a=new this._Promise((l,p)=>{s.callback=(m,d)=>m?p(m):l(d)}).catch(l=>{throw Error.captureStackTrace(l),l}))),o&&(u=s.callback,c=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{s.handleError(l,this.connection)}),u(l),s.callback=()=>{};var p=this.queryQueue.indexOf(s);p>-1&&this.queryQueue.splice(p,1),this._pulseQueryQueue()},o),s.callback=(l,p)=>{clearTimeout(c),u(l,p)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),a):(this.queryQueue.push(s),this._pulseQueryQueue(),a):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),a)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(ts,"Client");var er=ts;er.Query=Ko;Go.exports=er});var Yo=C((fC,Qo)=>{"use strict";var eh=require("events").EventEmitter,Ho=i(function(){},"NOOP"),Wo=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),ss=class ss{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}};i(ss,"IdleItem");var rs=ss,is=class is{constructor(e){this.callback=e}};i(is,"PendingItem");var st=is;function th(){throw new Error("Release called on client which has already been released to the pool.")}i(th,"throwOnDoubleRelease");function tr(t,e){if(e)return{callback:e,result:void 0};let r,n,s=i(function(o,c){o?r(o):n(c)},"cb"),a=new t(function(o,c){n=o,r=c}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:a}}i(tr,"promisify");function rh(t,e){return i(function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)},"idleListener")}i(rh,"makeIdleListener");var as=class as extends eh{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||os().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=Wo(this._idle,n=>n.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=tr(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new st(r.callback)),n;let s=i((c,u,l)=>{clearTimeout(o),r.callback(c,u,l)},"queueCallback"),a=new st(s),o=setTimeout(()=>{Wo(this._pendingQueue,c=>c.callback===s),a.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(a),n}return this.newClient(new st(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=rh(this,r);this.log("checking client timeout");let s,a=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),a=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(s&&clearTimeout(s),r.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(c=>c!==r),a&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Ho);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(l=>l.client===r)!==-1&&this._acquireClient(r,new st((l,p,m)=>m()),n,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,n,!0)}})}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,a=>{if(a)return e.release(a),r.callback(a,void 0,Ho);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&th(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let a;this.options.idleTimeoutMillis&&(a=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&a.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new rs(e,r,a)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let a=tr(this.Promise,e);return setImmediate(function(){return a.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),a.result}typeof r=="function"&&(n=r,r=void 0);let s=tr(this.Promise,n);return n=s.callback,this.connect((a,o)=>{if(a)return n(a);let c=!1,u=i(l=>{c||(c=!0,o.release(l),n(l))},"onError");o.once("error",u),this.log("dispatching query");try{o.query(e,r,(l,p)=>{if(this.log("query dispatched"),o.removeListener("error",u),!c)return c=!0,o.release(l),l?n(l):n(void 0,p)})}catch(l){return o.release(l),n(l)}}),s.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let r=tr(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(as,"Pool");var ns=as;Qo.exports=ns});var Xo=C((gC,zo)=>{"use strict";var jo=require("events").EventEmitter,nh=require("util"),cs=Ot(),it=zo.exports=function(t,e,r){jo.call(this),t=cs.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};nh.inherits(it,jo);var sh={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};it.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var n=sh[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};it.prototype.then=function(t,e){return this._getPromise().then(t,e)};it.prototype.catch=function(t){return this._getPromise().catch(t)};it.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};it.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(a,o,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),a)return e.handleError(a);e._emitRowEvents&&(c.length>1?o.forEach((u,l)=>{u.forEach(p=>{e.emit("row",p,c[l])})}):o.forEach(function(u){e.emit("row",u,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var n=(this.values||[]).map(cs.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let a=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(a)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(a){return a?r(a):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let a=new Error("Query values must be an array");return r(a)}var s=this.values.map(cs.prepareValue);t.native.query(this.text,s,r)}else t.native.query(this.text,r)}});var rc=C((_C,tc)=>{"use strict";var Zo;try{Zo=require("pg-native")}catch(t){throw t}var ih=Zr(),Jo=require("events").EventEmitter,ah=require("util"),oh=rn(),ec=Xo(),ye=tc.exports=function(t){Jo.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new ih(t.types),this.native=new Zo({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new oh(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};ye.Query=ec;ah.inherits(ye,Jo);ye.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};ye.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(a){e._queryable=!1,e._errorAllQueries(a),e.emit("error",a)}),e.native.on("notification",function(a){e.emit("notification",{channel:a.relname,payload:a.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};ye.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e()})})};ye.prototype.query=function(t,e,r){var n,s,a,o,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")a=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(a=this.connectionParameters.query_timeout,n=new ec(t,e,r),!n.callback){let u,l;s=new this._Promise((p,m)=>{u=p,l=m}).catch(p=>{throw Error.captureStackTrace(p),p}),n.callback=(p,m)=>p?l(p):u(m)}return a&&(c=n.callback,o=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),c(u),n.callback=()=>{};var l=this._queryQueue.indexOf(n);l>-1&&this._queryQueue.splice(l,1),this._pulseQueryQueue()},a),n.callback=(u,l)=>{clearTimeout(o),c(u,l)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};ye.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(n,s){t=i(a=>a?s(a):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};ye.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};ye.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};ye.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};ye.prototype.ref=function(){};ye.prototype.unref=function(){};ye.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};ye.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var us=C((TC,nc)=>{"use strict";nc.exports=rc()});var os=C((SC,Dt)=>{"use strict";var ch=Vo(),uh=It(),lh=zn(),ph=Yo(),{DatabaseError:mh}=Wn(),{escapeIdentifier:dh,escapeLiteral:fh}=Ot(),hh=i(t=>{var e;return e=class extends ph{constructor(n){super(n,t)}},i(e,"BoundPool"),e},"poolFactory"),ls=i(function(t){this.defaults=uh,this.Client=t,this.Query=this.Client.Query,this.Pool=hh(this.Client),this._pools=[],this.Connection=lh,this.types=vt(),this.DatabaseError=mh,this.escapeIdentifier=dh,this.escapeLiteral=fh},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?Dt.exports=new ls(us()):(Dt.exports=new ls(ch),Object.defineProperty(Dt.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new ls(us())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Dt.exports,"native",{value:t}),t}}))});var ic=C((AC,sc)=>{var Qe=require("fs"),gh=Ea(),yh=os(),_h="The server does not support SSL connections",Eh="28000",Th=i(t=>{let e={username:t.ssh_user,host:t.ssh_host,port:t.ssh_port,dstHost:t.host,dstPort:t.port,localHost:"127.0.0.1",localPort:t.port,keepAlive:!0};return t.ssh_method==="privateKey"?Object.assign({},e,{privateKey:Qe.readFileSync(t.ssh_key_file),passphrase:t.ssh_key_passphrase}):Object.assign({},e,{password:t.ssh_password})},"getSshConfig"),Sh=i(t=>new Promise((e,r)=>{gh(Th(t),(n,s)=>{n?r(n):e({tunnel:s,info:Object.assign({},t,{host:"127.0.0.1"})})})}),"connectViaSsh"),Ch=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let n={checkServerIdentity(s,a){e.info("Certificate",{hostname:s,cert:{subject:a.subject,issuer:a.issuer,valid_from:a.valid_from,valid_to:a.valid_to}})}};return Qe.existsSync(t.certAuthority)&&(n.ca=Qe.readFileSync(t.certAuthority).toString()),Qe.existsSync(t.clientCert)&&(n.cert=Qe.readFileSync(t.clientCert).toString()),Qe.existsSync(t.clientPrivateKey)&&(n.key=Qe.readFileSync(t.clientPrivateKey).toString()),n},"getSslOptions"),Ah=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),Nh=i(async(t,e)=>{let r=null;if(t.ssh){let{info:a,tunnel:o}=await Sh(t);r=o,t=a}t=Object.assign({},t,{sslType:Ah(t.sslType)});let n={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:Ch(t,e),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await ps(n,e),sshTunnel:r}},"createClient"),bh=i((t,e,r)=>{var n;if(r.message===_h&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),ps({...t,isRetry:!0,ssl:!1},e);if(((n=r.code)==null?void 0:n.toString())===Eh&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),ps({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),ps=i((t,e)=>{let r=new yh.Pool(t);return r.connect().then(n=>(n.release(),r)).catch(async n=>{if(await r.end(),t.isRetry)throw n;return bh(t,e,n)})},"createConnectionPool");sc.exports={createClient:Nh}});var ds=C((bC,cc)=>{var ms=i(t=>` +"use strict";var Ot=Object.defineProperty;var yl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var El=Object.prototype.hasOwnProperty;var i=(t,e)=>Ot(t,"name",{value:e,configurable:!0});var Tl=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Sl=(t,e)=>{for(var r in e)Ot(t,r,{get:e[r],enumerable:!0})},Cl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _l(e))!El.call(t,s)&&s!==r&&Ot(t,s,{get:()=>e[s],enumerable:!(n=yl(e,s))||n.enumerable});return t};var Al=t=>Cl(Ot({},"__esModule",{value:!0}),t);var pr=N((K_,vi)=>{"use strict";var Nl=i(({title:t,logger:e,hiddenKeys:r})=>({info(n,s={}){e.log("info",{message:n,...s},t,r)},progress(n,s="",a=""){e.progress({message:n,containerName:s,entityName:a})},error(n){e.log("error",bl(n),t)}}),"createLogger"),bl=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");vi.exports={createLogger:Nl}});var dr=N(Oi=>{"use strict";Oi.parse=function(t,e){return new mr(t,e).parse()};var Rt=class Rt{constructor(e,r){this.source=e,this.transform=r||Il,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new Rt(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(Rt,"ArrayParser");var mr=Rt;function Il(t){return t}i(Il,"identity")});var fr=N((W_,Ri)=>{var vl=dr();Ri.exports={create:function(t,e){return{parse:function(){return vl.parse(t,e)}}}}});var Di=N((Q_,qi)=>{"use strict";var Ol=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,Rl=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,wl=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ql=/^-?infinity$/;qi.exports=i(function(e){if(ql.test(e))return Number(e.replace("i","I"));var r=Ol.exec(e);if(!r)return Dl(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=wi(s));var a=parseInt(r[2],10)-1,o=r[3],c=parseInt(r[4],10),u=parseInt(r[5],10),l=parseInt(r[6],10),d=r[7];d=d?1e3*parseFloat(d):0;var p,m=xl(e);return m!=null?(p=new Date(Date.UTC(s,a,o,c,u,l,d)),hr(s)&&p.setUTCFullYear(s),m!==0&&p.setTime(p.getTime()-m)):(p=new Date(s,a,o,c,u,l,d),hr(s)&&p.setFullYear(s)),p},"parseDate");function Dl(t){var e=Rl.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=wi(r));var s=parseInt(e[2],10)-1,a=e[3],o=new Date(r,s,a);return hr(r)&&o.setFullYear(r),o}}i(Dl,"getDate");function xl(t){if(t.endsWith("+00"))return 0;var e=wl.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}i(xl,"timeZoneOffset");function wi(t){return-(t-1)}i(wi,"bcYearToNegativeYear");function hr(t){return t>=0&&t<100}i(hr,"is0To99")});var Pi=N((j_,xi)=>{xi.exports=Ll;var Pl=Object.prototype.hasOwnProperty;function Ll(t){for(var e=1;e{"use strict";var Ml=Pi();Mi.exports=Qe;function Qe(t){if(!(this instanceof Qe))return new Qe(t);Ml(this,Yl(t))}i(Qe,"PostgresInterval");var Fl=["seconds","minutes","hours","days","months","years"];Qe.prototype.toPostgres=function(){var t=Fl.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var Ul={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},kl=["years","months","days"],$l=["hours","minutes","seconds"];Qe.prototype.toISOString=Qe.prototype.toISO=function(){var t=kl.map(r,this).join(""),e=$l.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+Ul[n]}};var gr="([+-]?\\d+)",Bl=gr+"\\s+years?",Kl=gr+"\\s+mons?",Gl=gr+"\\s+days?",Vl="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Hl=new RegExp([Bl,Kl,Gl,Vl].map(function(t){return"("+t+")?"}).join("\\s*")),Li={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Wl=["hours","minutes","seconds","milliseconds"];function Ql(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(Ql,"parseMilliseconds");function Yl(t){if(!t)return{};var e=Hl.exec(t),r=e[8]==="-";return Object.keys(Li).reduce(function(n,s){var a=Li[s],o=e[a];return!o||(o=s==="milliseconds"?Ql(o):parseInt(o,10),!o)||(r&&~Wl.indexOf(s)&&(o*=-1),n[s]=o),n},{})}i(Yl,"parse")});var ki=N((J_,Ui)=>{"use strict";Ui.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",n=0;n{var lt=dr(),pt=fr(),wt=Di(),Bi=Fi(),Ki=ki();function qt(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(qt,"allowNull");function Gi(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(Gi,"parseBool");function jl(t){return t?lt.parse(t,Gi):null}i(jl,"parseBoolArray");function zl(t){return parseInt(t,10)}i(zl,"parseBaseTenInt");function yr(t){return t?lt.parse(t,qt(zl)):null}i(yr,"parseIntegerArray");function Xl(t){return t?lt.parse(t,qt(function(e){return Vi(e).trim()})):null}i(Xl,"parseBigIntegerArray");var Zl=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=Sr(r)),r});return e.parse()},"parsePointArray"),_r=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),Se=i(function(t){if(!t)return null;var e=pt.create(t);return e.parse()},"parseStringArray"),Er=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=wt(r)),r});return e.parse()},"parseDateArray"),Jl=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=Bi(r)),r});return e.parse()},"parseIntervalArray"),ep=i(function(t){return t?lt.parse(t,qt(Ki)):null},"parseByteAArray"),Tr=i(function(t){return parseInt(t,10)},"parseInteger"),Vi=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),$i=i(function(t){return t?lt.parse(t,qt(JSON.parse)):null},"parseJsonArray"),Sr=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),tp=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s{"use strict";var de=1e6;function np(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",a,o,c,u,l,d;{if(a=e%de,e=e/de>>>0,o=4294967296*a+r,r=o/de>>>0,c=""+(o-de*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,d=0;d>>0,o=4294967296*a+r,r=o/de>>>0,c=""+(o-de*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,d=0;d>>0,o=4294967296*a+r,r=o/de>>>0,c=""+(o-de*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,d=0;d{var sp=Yi(),Q=i(function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(f,h,T){return f*Math.pow(2,T)+h};var a=r>>3,o=i(function(f){return n?~f&255:f},"inv"),c=255,u=8-r%8;e>r%8);var l=0;r%8+e>=8&&(l=s(0,o(t[a])&c,u));for(var d=e+r>>3,p=a+1;p0&&(l=s(l,o(t[d])>>8-m,m)),l},"parseBits"),Xi=i(function(t,e,r){var n=Math.pow(2,r-1)-1,s=Q(t,1),a=Q(t,r,1);if(a===0)return 0;var o=1,c=i(function(l,d,p){l===0&&(l=1);for(var m=1;m<=p;m++)o/=2,(d&1<0&&(l+=o);return l},"parsePrecisionBits"),u=Q(t,e,r+1,!1,c);return a==Math.pow(2,r+1)-1?u===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,a-n)*u},"parseFloatFromBits"),ip=i(function(t){return Q(t,1)==1?-1*(Q(t,15,1,!0)+1):Q(t,15,1)},"parseInt16"),ji=i(function(t){return Q(t,1)==1?-1*(Q(t,31,1,!0)+1):Q(t,31,1)},"parseInt32"),ap=i(function(t){return Xi(t,23,8)},"parseFloat32"),op=i(function(t){return Xi(t,52,11)},"parseFloat64"),cp=i(function(t){var e=Q(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,Q(t,16,16)),n=0,s=[],a=Q(t,16),o=0;o>3,(s+=d<<3)>>3),p;console.log("ERROR: ElementType not implemented: "+l)},"parseElement"),u=i(function(l,d){var p=[],m;if(l.length>1){var f=l.shift();for(m=0;m0},"parseBool"),pp=i(function(t){t(20,sp),t(21,ip),t(23,ji),t(26,ji),t(1700,cp),t(700,ap),t(701,op),t(16,lp),t(1114,zi.bind(null,!1)),t(1184,zi.bind(null,!0)),t(1e3,mt),t(1007,mt),t(1016,mt),t(1008,mt),t(1009,mt),t(25,up)},"init");Zi.exports={init:pp}});var ta=N((oE,ea)=>{ea.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var ht=N(ft=>{var mp=Wi(),dp=Ji(),fp=fr(),hp=ta();ft.getTypeParser=gp;ft.setTypeParser=yp;ft.arrayParser=fp;ft.builtins=hp;var dt={text:{},binary:{}};function ra(t){return String(t)}i(ra,"noParse");function gp(t,e){return e=e||"text",dt[e]&&dt[e][t]||ra}i(gp,"getTypeParser");function yp(t,e,r){typeof e=="function"&&(r=e,e="text"),dt[e][t]=r}i(yp,"setTypeParser");mp.init(function(t,e){dt.text[t]=e});dp.init(function(t,e){dt.binary[t]=e})});var gt=N((lE,Cr)=>{"use strict";Cr.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Ye=ht(),_p=Ye.getTypeParser(20,"text"),Ep=Ye.getTypeParser(1016,"text");Cr.exports.__defineSetter__("parseInt8",function(t){Ye.setTypeParser(20,"text",t?Ye.getTypeParser(23,"text"):_p),Ye.setTypeParser(1016,"text",t?Ye.getTypeParser(1007,"text"):Ep)})});var yt=N((pE,sa)=>{"use strict";var Tp=gt();function Sp(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(Sp,"escapeElement");function na(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+na(t[r]);else if(ArrayBuffer.isView(t[r])){var n=t[r];if(!(n instanceof Buffer)){var s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=Sp(Dt(t[r]));return e=e+"}",e}i(na,"arrayString");var Dt=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?Tp.parseInputDatesAsUTC?Np(t):Ap(t):Array.isArray(t)?na(t):typeof t=="object"?Cp(t,e):t.toString()},"prepareValue");function Cp(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Dt(t.toPostgres(Dt),e)}return JSON.stringify(t)}i(Cp,"prepareObject");function ue(t,e){for(t=""+t;t.length{"use strict";var _t=require("crypto");function Ar(t){return _t.createHash("md5").update(t,"utf-8").digest("hex")}i(Ar,"md5");function Op(t,e,r){var n=Ar(e+t),s=Ar(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(Op,"postgresMd5PasswordHash");function Rp(t){return _t.createHash("sha256").update(t).digest()}i(Rp,"sha256");function wp(t,e){return _t.createHmac("sha256",t).update(e).digest()}i(wp,"hmacSha256");async function qp(t,e,r){return _t.pbkdf2Sync(t,e,r,32,"sha256")}i(qp,"deriveKey");ia.exports={postgresMd5PasswordHash:Op,randomBytes:_t.randomBytes,deriveKey:qp,sha256:Rp,hmacSha256:wp,md5:Ar}});var la=N((hE,ua)=>{var oa=require("crypto");ua.exports={postgresMd5PasswordHash:xp,randomBytes:Dp,deriveKey:Mp,sha256:Pp,hmacSha256:Lp,md5:Nr};var ca=oa.webcrypto||globalThis.crypto,je=ca.subtle,br=new TextEncoder;function Dp(t){return ca.getRandomValues(Buffer.alloc(t))}i(Dp,"randomBytes");async function Nr(t){try{return oa.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?br.encode(t):t,n=await je.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}i(Nr,"md5");async function xp(t,e,r){var n=await Nr(e+t),s=await Nr(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(xp,"postgresMd5PasswordHash");async function Pp(t){return await je.digest("SHA-256",t)}i(Pp,"sha256");async function Lp(t,e){let r=await je.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await je.sign("HMAC",r,br.encode(e))}i(Lp,"hmacSha256");async function Mp(t,e,r){let n=await je.importKey("raw",br.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await je.deriveBits(s,n,32*8,["deriveBits"])}i(Mp,"deriveKey")});var vr=N((yE,Ir)=>{"use strict";var Fp=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;Fp?Ir.exports=aa():Ir.exports=la()});var fa=N((_E,da)=>{"use strict";var Ge=vr();function Up(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=Ge.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Up,"startSession");async function kp(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let n=Kp(r);if(n.nonce.startsWith(t.clientNonce)){if(n.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var s="n=*,r="+t.clientNonce,a="r="+n.nonce+",s="+n.salt+",i="+n.iteration,o="c=biws,r="+n.nonce,c=s+","+a+","+o,u=Buffer.from(n.salt,"base64"),l=await Ge.deriveKey(e,u,n.iteration),d=await Ge.hmacSha256(l,"Client Key"),p=await Ge.sha256(d),m=await Ge.hmacSha256(p,c),f=Vp(Buffer.from(d),Buffer.from(m)).toString("base64"),h=await Ge.hmacSha256(l,"Server Key"),T=await Ge.hmacSha256(h,c);t.message="SASLResponse",t.serverSignature=Buffer.from(T).toString("base64"),t.response=o+",p="+f}i(kp,"continueSession");function $p(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=Gp(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i($p,"finalizeSession");function Bp(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(Bp,"isPrintableChars");function pa(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(pa,"isBase64");function ma(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}i(ma,"parseAttributePairs");function Kp(t){let e=ma(t),r=e.get("r");if(r){if(!Bp(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!pa(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let a=parseInt(s,10);return{nonce:r,salt:n,iteration:a}}i(Kp,"parseServerFirstMessage");function Gp(t){let r=ma(t).get("v");if(r){if(!pa(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(Gp,"parseServerFinalMessage");function Vp(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}i(Vp,"xorBuffers");da.exports={startSession:Up,continueSession:kp,finalizeSession:$p}});var Or=N((TE,ha)=>{"use strict";var Hp=ht();function xt(t){this._types=t||Hp,this.text={},this.binary={}}i(xt,"TypeOverrides");xt.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};xt.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};xt.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};ha.exports=xt});var ya=N((CE,ga)=>{"use strict";function Rr(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,n=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),n=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let s=n?"":r.hostname;e.host?s&&/^%2f/i.test(s)&&(r.pathname=s+r.pathname):e.host=decodeURIComponent(s),e.port||(e.port=r.port);let a=r.pathname.slice(1)||null;e.database=a?decodeURI(a):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let o=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=o.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=o.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=o.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(Rr,"parse");ga.exports=Rr;Rr.parse=Rr});var Dr=N((NE,Ta)=>{"use strict";var Wp=require("dns"),Ea=gt(),_a=ya().parse,pe=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||Ea[t]},"val"),Qp=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return Ea.ssl},"readSSLConfigFromEnvironment"),ze=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),Ce=i(function(t,e,r){var n=e[r];n!=null&&t.push(r+"="+ze(n))},"add"),qr=class qr{constructor(e){e=typeof e=="string"?_a(e):e||{},e.connectionString&&(e=Object.assign({},e,_a(e.connectionString))),this.user=pe("user",e),this.database=pe("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(pe("port",e),10),this.host=pe("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:pe("password",e)}),this.binary=pe("binary",e),this.options=pe("options",e),this.ssl=typeof e.ssl>"u"?Qp():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=pe("client_encoding",e),this.replication=pe("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=pe("application_name",e,"PGAPPNAME"),this.fallback_application_name=pe("fallback_application_name",e,!1),this.statement_timeout=pe("statement_timeout",e,!1),this.lock_timeout=pe("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=pe("idle_in_transaction_session_timeout",e,!1),this.query_timeout=pe("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];Ce(r,this,"user"),Ce(r,this,"password"),Ce(r,this,"port"),Ce(r,this,"application_name"),Ce(r,this,"fallback_application_name"),Ce(r,this,"connect_timeout"),Ce(r,this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Ce(r,n,"sslmode"),Ce(r,n,"sslca"),Ce(r,n,"sslkey"),Ce(r,n,"sslcert"),Ce(r,n,"sslrootcert"),this.database&&r.push("dbname="+ze(this.database)),this.replication&&r.push("replication="+ze(this.replication)),this.host&&r.push("host="+ze(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+ze(this.client_encoding)),Wp.lookup(this.host,function(s,a){return s?e(s,null):(r.push("hostaddr="+ze(a)),e(null,r.join(" ")))})}};i(qr,"ConnectionParameters");var wr=qr;Ta.exports=wr});var Aa=N((IE,Ca)=>{"use strict";var Yp=ht(),Sa=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Pr=class Pr{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=Sa.exec(e.text):r=Sa.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),n=0,s=e.length;n{"use strict";var{EventEmitter:jp}=require("events"),Na=Aa(),ba=yt(),Mr=class Mr extends jp{constructor(e,r,n){super(),e=ba.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new Na(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new Na(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:ba.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(Mr,"Query");var Lr=Mr;Ia.exports=Lr});var mn=N(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.NoticeMessage=M.DataRowMessage=M.CommandCompleteMessage=M.ReadyForQueryMessage=M.NotificationResponseMessage=M.BackendKeyDataMessage=M.AuthenticationMD5Password=M.ParameterStatusMessage=M.ParameterDescriptionMessage=M.RowDescriptionMessage=M.Field=M.CopyResponse=M.CopyDataMessage=M.DatabaseError=M.copyDone=M.emptyQuery=M.replicationStart=M.portalSuspended=M.noData=M.closeComplete=M.bindComplete=M.parseComplete=void 0;M.parseComplete={name:"parseComplete",length:5};M.bindComplete={name:"bindComplete",length:5};M.closeComplete={name:"closeComplete",length:5};M.noData={name:"noData",length:5};M.portalSuspended={name:"portalSuspended",length:5};M.replicationStart={name:"replicationStart",length:4};M.emptyQuery={name:"emptyQuery",length:4};M.copyDone={name:"copyDone",length:4};var Xr=class Xr extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};i(Xr,"DatabaseError");var Fr=Xr;M.DatabaseError=Fr;var Zr=class Zr{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(Zr,"CopyDataMessage");var Ur=Zr;M.CopyDataMessage=Ur;var Jr=class Jr{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};i(Jr,"CopyResponse");var kr=Jr;M.CopyResponse=kr;var en=class en{constructor(e,r,n,s,a,o,c){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=a,this.dataTypeModifier=o,this.format=c}};i(en,"Field");var $r=en;M.Field=$r;var tn=class tn{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(tn,"RowDescriptionMessage");var Br=tn;M.RowDescriptionMessage=Br;var rn=class rn{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(rn,"ParameterDescriptionMessage");var Kr=rn;M.ParameterDescriptionMessage=Kr;var nn=class nn{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};i(nn,"ParameterStatusMessage");var Gr=nn;M.ParameterStatusMessage=Gr;var sn=class sn{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(sn,"AuthenticationMD5Password");var Vr=sn;M.AuthenticationMD5Password=Vr;var an=class an{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};i(an,"BackendKeyDataMessage");var Hr=an;M.BackendKeyDataMessage=Hr;var on=class on{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};i(on,"NotificationResponseMessage");var Wr=on;M.NotificationResponseMessage=Wr;var cn=class cn{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(cn,"ReadyForQueryMessage");var Qr=cn;M.ReadyForQueryMessage=Qr;var un=class un{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(un,"CommandCompleteMessage");var Yr=un;M.CommandCompleteMessage=Yr;var ln=class ln{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(ln,"DataRowMessage");var jr=ln;M.DataRowMessage=jr;var pn=class pn{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(pn,"NoticeMessage");var zr=pn;M.NoticeMessage=zr});var Oa=N(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Writer=void 0;var fn=class fn{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(s),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(fn,"Writer");var dn=fn;Pt.Writer=dn});var wa=N(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.serialize=void 0;var hn=Oa(),Y=new hn.Writer,zp=i(t=>{Y.addInt16(3).addInt16(0);for(let n of Object.keys(t))Y.addCString(n).addCString(t[n]);Y.addCString("client_encoding").addCString("UTF8");var e=Y.addCString("").flush(),r=e.length+4;return new hn.Writer().addInt32(r).add(e).flush()},"startup"),Xp=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),Zp=i(t=>Y.addCString(t).flush(112),"password"),Jp=i(function(t,e){return Y.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),Y.flush(112)},"sendSASLInitialResponseMessage"),em=i(function(t){return Y.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),tm=i(t=>Y.addCString(t).flush(81),"query"),Ra=[],rm=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||Ra;for(var n=r.length,s=Y.addCString(e).addCString(t.text).addInt16(n),a=0;a{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||Ra,a=s.length;return Y.addCString(e).addCString(r),Y.addInt16(a),nm(s,t.valueMapper),Y.addInt16(a),Y.add(Xe.flush()),Y.addInt16(n?1:0),Y.flush(66)},"bind"),im=Buffer.from([69,0,0,0,9,0,0,0,0,0]),am=i(t=>{if(!t||!t.portal&&!t.rows)return im;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,a=Buffer.allocUnsafe(1+s);return a[0]=69,a.writeInt32BE(s,1),a.write(e,5,"utf-8"),a[n+5]=0,a.writeUInt32BE(r,a.length-4),a},"execute"),om=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),gn=i((t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},"cstringMessage"),cm=Y.addCString("P").flush(68),um=Y.addCString("S").flush(68),lm=i(t=>t.name?gn(68,`${t.type}${t.name||""}`):t.type==="P"?cm:um,"describe"),pm=i(t=>{let e=`${t.type}${t.name||""}`;return gn(67,e)},"close"),mm=i(t=>Y.add(t).flush(100),"copyData"),dm=i(t=>gn(102,t),"copyFail"),Lt=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),fm=Lt(72),hm=Lt(83),gm=Lt(88),ym=Lt(99),_m={startup:zp,password:Zp,requestSsl:Xp,sendSASLInitialResponseMessage:Jp,sendSCRAMClientFinalMessage:em,query:tm,parse:rm,bind:sm,execute:am,describe:lm,close:pm,flush:()=>fm,sync:()=>hm,end:()=>gm,copyData:mm,copyDone:()=>ym,copyFail:dm,cancel:om};Mt.serialize=_m});var qa=N(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.BufferReader=void 0;var Em=Buffer.allocUnsafe(0),_n=class _n{constructor(e=0){this.offset=e,this.buffer=Em,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(_n,"BufferReader");var yn=_n;Ft.BufferReader=yn});var Pa=N(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Parser=void 0;var j=mn(),Tm=qa(),En=1,Sm=4,Da=En+Sm,xa=Buffer.allocUnsafe(0),Sn=class Sn{constructor(e){if(this.buffer=xa,this.bufferLength=0,this.bufferOffset=0,this.reader=new Tm.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+Da<=n;){let a=this.buffer[s],o=this.buffer.readUInt32BE(s+En),c=En+o;if(c+s<=n){let u=this.handlePacket(s+Da,a,o,this.buffer);r(u),s+=c}else break}s===n?(this.buffer=xa,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let a=this.buffer.byteLength*2;for(;r>=a;)a*=2;s=Buffer.allocUnsafe(a)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){switch(r){case 50:return j.bindComplete;case 49:return j.parseComplete;case 51:return j.closeComplete;case 110:return j.noData;case 115:return j.portalSuspended;case 99:return j.copyDone;case 87:return j.replicationStart;case 73:return j.emptyQuery;case 68:return this.parseDataRowMessage(e,n,s);case 67:return this.parseCommandCompleteMessage(e,n,s);case 90:return this.parseReadyForQueryMessage(e,n,s);case 65:return this.parseNotificationMessage(e,n,s);case 82:return this.parseAuthenticationResponse(e,n,s);case 83:return this.parseParameterStatusMessage(e,n,s);case 75:return this.parseBackendKeyData(e,n,s);case 69:return this.parseErrorMessage(e,n,s,"error");case 78:return this.parseErrorMessage(e,n,s,"notice");case 84:return this.parseRowDescriptionMessage(e,n,s);case 116:return this.parseParameterDescriptionMessage(e,n,s);case 71:return this.parseCopyInMessage(e,n,s);case 72:return this.parseCopyOutMessage(e,n,s);case 100:return this.parseCopyData(e,n,s);default:return new j.DatabaseError("received invalid response: "+r.toString(16),n,"error")}}parseReadyForQueryMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.string(1);return new j.ReadyForQueryMessage(r,s)}parseCommandCompleteMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.cstring();return new j.CommandCompleteMessage(r,s)}parseCopyData(e,r,n){let s=n.slice(e,e+(r-4));return new j.CopyDataMessage(r,s)}parseCopyInMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyInResponse")}parseCopyOutMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyOutResponse")}parseCopyMessage(e,r,n,s){this.reader.setBuffer(e,n);let a=this.reader.byte()!==0,o=this.reader.int16(),c=new j.CopyResponse(r,s,a,o);for(let u=0;u{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.DatabaseError=Fe.serialize=Fe.parse=void 0;var Cm=mn();Object.defineProperty(Fe,"DatabaseError",{enumerable:!0,get:function(){return Cm.DatabaseError}});var Am=wa();Object.defineProperty(Fe,"serialize",{enumerable:!0,get:function(){return Am.serialize}});var Nm=Pa();function bm(t,e){let r=new Nm.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}i(bm,"parse");Fe.parse=bm});var La={};Sl(La,{default:()=>Im});var Im,Ma=Tl(()=>{Im={}});var Fa=N((KE,An)=>{An.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:n}=(Ma(),Al(La));return new n(e)}},"getStream");An.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var In=N((HE,Ua)=>{"use strict";var VE=require("net"),vm=require("events").EventEmitter,{parse:Om,serialize:ae}=Cn(),{getStream:Rm,getSecureStream:wm}=Fa(),qm=ae.flush(),Dm=ae.sync(),xm=ae.end(),bn=class bn extends vm{constructor(e){super(),e=e||{},this.stream=e.stream||Rm(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=i(function(a){n._ending&&(a.code==="ECONNRESET"||a.code==="EPIPE")||n.emit("error",a)},"reportStreamError");if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(a){var o=a.toString("utf8");switch(o){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:n.stream};n.ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key));var u=require("net");u.isIP&&u.isIP(r)===0&&(c.servername=r);try{n.stream=wm(c)}catch(l){return n.emit("error",l)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){Om(e,r=>{var n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(ae.requestSsl())}startup(e){this.stream.write(ae.startup(e))}cancel(e,r){this._send(ae.cancel(e,r))}password(e){this._send(ae.password(e))}sendSASLInitialResponseMessage(e,r){this._send(ae.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(ae.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(ae.query(e))}parse(e){this._send(ae.parse(e))}bind(e){this._send(ae.bind(e))}execute(e){this._send(ae.execute(e))}flush(){this.stream.writable&&this.stream.write(qm)}sync(){this._ending=!0,this._send(Dm)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(xm,()=>{this.stream.end()})}close(e){this._send(ae.close(e))}describe(e){this._send(ae.describe(e))}sendCopyFromChunk(e){this._send(ae.copyData(e))}endCopyFrom(){this._send(ae.copyDone())}sendCopyFail(e){this._send(ae.copyFail(e))}};i(bn,"Connection");var Nn=bn;Ua.exports=Nn});var Ka=N((QE,Ba)=>{"use strict";var{Transform:Pm}=require("stream"),{StringDecoder:Lm}=require("string_decoder"),Ue=Symbol("last"),kt=Symbol("decoder");function Mm(t,e,r){let n;if(this.overflow){if(n=this[kt].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[Ue]+=this[kt].write(t),n=this[Ue].split(this.matcher);this[Ue]=n.pop();for(let s=0;sthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(Mm,"transform");function Fm(t){if(this[Ue]+=this[kt].end(),this[Ue])try{$a(this,this.mapper(this[Ue]))}catch(e){return t(e)}t()}i(Fm,"flush");function $a(t,e){e!==void 0&&t.push(e)}i($a,"push");function ka(t){return t}i(ka,"noop");function Um(t,e,r){switch(t=t||/\r?\n/,e=e||ka,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=ka)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Mm,r.flush=Fm,r.readableObjectMode=!0;let n=new Pm(r);return n[Ue]="",n[kt]=new Lm("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,a){this._writableState.errorEmitted=!1,a(s)},n}i(Um,"split");Ba.exports=Um});var Ha=N((jE,Le)=>{"use strict";var Ga=require("path"),km=require("stream").Stream,$m=Ka(),Va=require("util"),Bm=5432,$t=process.platform==="win32",Et=process.stderr,Km=56,Gm=7,Vm=61440,Hm=32768;function Wm(t){return(t&Vm)==Hm}i(Wm,"isRegFile");var Ze=["host","port","database","user","password"],vn=Ze.length,Qm=Ze[vn-1];function On(){var t=Et instanceof km&&Et.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` +`);Et.write(Va.format.apply(Va,e))}}i(On,"warn");Object.defineProperty(Le.exports,"isWin",{get:function(){return $t},set:function(t){$t=t}});Le.exports.warnTo=function(t){var e=Et;return Et=t,e};Le.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||($t?Ga.join(e.APPDATA||"./","postgresql","pgpass.conf"):Ga.join(e.HOME||"./",".pgpass"));return r};Le.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:$t?!0:(e=e||"",Wm(t.mode)?t.mode&(Km|Gm)?(On('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(On('WARNING: password file "%s" is not a plain file',e),!1))};var Ym=Le.exports.match=function(t,e){return Ze.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||Bm)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};Le.exports.getPassword=function(t,e,r){var n,s=e.pipe($m());function a(u){var l=jm(u);l&&zm(l)&&Ym(t,l)&&(n=l[Qm],s.end())}i(a,"onLine");var o=i(function(){e.destroy(),r(n)},"onEnd"),c=i(function(u){e.destroy(),On("WARNING: error on reading file: %s",u),r(void 0)},"onErr");e.on("error",c),s.on("data",a).on("end",o).on("error",c)};var jm=Le.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,a=0,o={},c=!1,u=i(function(d,p,m){var f=t.substring(p,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(f=f.replace(/\\([:\\])/g,"$1")),o[Ze[d]]=f},"addToObj"),l=0;l=0&&e==":"&&r!=="\\"&&(u(n,s,l+1),s=l+2,n+=1)}return o=Object.keys(o).length===vn?o:null,o},zm=Le.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r{"use strict";var XE=require("path"),Wa=require("fs"),Bt=Ha();Rn.exports=function(t,e){var r=Bt.getFileName();Wa.stat(r,function(n,s){if(n||!Bt.usePgPass(s,r))return e(void 0);var a=Wa.createReadStream(r);Bt.getPassword(t,a,e)})};Rn.exports.warnTo=Bt.warnTo});var Xa=N((JE,za)=>{"use strict";var Xm=require("events").EventEmitter,Ya=yt(),wn=fa(),Zm=Or(),Jm=Dr(),ja=va(),ed=gt(),td=In(),rd=vr(),qn=class qn extends Xm{constructor(e){super(),this.connectionParameters=new Jm(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new Zm(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new td({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||ed.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(n=>{process.nextTick(()=>{n.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{r.emit("error",n)});else if(this.password!==null)e();else try{Qa()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await rd.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=wn.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await wn.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{wn.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Ya.escapeIdentifier(e)}escapeLiteral(e){return Ya.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,n){var s,a,o,c,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,a=s=e,typeof r=="function"&&(s.callback=s.callback||r)):(o=this.connectionParameters.query_timeout,s=new ja(e,r,n),s.callback||(a=new this._Promise((l,d)=>{s.callback=(p,m)=>p?d(p):l(m)}).catch(l=>{throw Error.captureStackTrace(l),l}))),o&&(u=s.callback,c=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{s.handleError(l,this.connection)}),u(l),s.callback=()=>{};var d=this.queryQueue.indexOf(s);d>-1&&this.queryQueue.splice(d,1),this._pulseQueryQueue()},o),s.callback=(l,d)=>{clearTimeout(c),u(l,d)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),a):(this.queryQueue.push(s),this._pulseQueryQueue(),a):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),a)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(qn,"Client");var Kt=qn;Kt.Query=ja;za.exports=Kt});var to=N((tT,eo)=>{"use strict";var nd=require("events").EventEmitter,Za=i(function(){},"NOOP"),Ja=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),Pn=class Pn{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}};i(Pn,"IdleItem");var Dn=Pn,Ln=class Ln{constructor(e){this.callback=e}};i(Ln,"PendingItem");var Je=Ln;function sd(){throw new Error("Release called on client which has already been released to the pool.")}i(sd,"throwOnDoubleRelease");function Gt(t,e){if(e)return{callback:e,result:void 0};let r,n,s=i(function(o,c){o?r(o):n(c)},"cb"),a=new t(function(o,c){n=o,r=c}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:a}}i(Gt,"promisify");function id(t,e){return i(function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)},"idleListener")}i(id,"makeIdleListener");var Mn=class Mn extends nd{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||Fn().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=Ja(this._idle,n=>n.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=Gt(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new Je(r.callback)),n;let s=i((c,u,l)=>{clearTimeout(o),r.callback(c,u,l)},"queueCallback"),a=new Je(s),o=setTimeout(()=>{Ja(this._pendingQueue,c=>c.callback===s),a.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(a),n}return this.newClient(new Je(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=id(this,r);this.log("checking client timeout");let s,a=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),a=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(s&&clearTimeout(s),r.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(c=>c!==r),a&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Za);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(l=>l.client===r)!==-1&&this._acquireClient(r,new Je((l,d,p)=>p()),n,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,n,!0)}})}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,a=>{if(a)return e.release(a),r.callback(a,void 0,Za);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&sd(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let a;this.options.idleTimeoutMillis&&(a=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&a.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Dn(e,r,a)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let a=Gt(this.Promise,e);return setImmediate(function(){return a.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),a.result}typeof r=="function"&&(n=r,r=void 0);let s=Gt(this.Promise,n);return n=s.callback,this.connect((a,o)=>{if(a)return n(a);let c=!1,u=i(l=>{c||(c=!0,o.release(l),n(l))},"onError");o.once("error",u),this.log("dispatching query");try{o.query(e,r,(l,d)=>{if(this.log("query dispatched"),o.removeListener("error",u),!c)return c=!0,o.release(l),l?n(l):n(void 0,d)})}catch(l){return o.release(l),n(l)}}),s.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let r=Gt(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(Mn,"Pool");var xn=Mn;eo.exports=xn});var so=N((nT,no)=>{"use strict";var ro=require("events").EventEmitter,ad=require("util"),Un=yt(),et=no.exports=function(t,e,r){ro.call(this),t=Un.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};ad.inherits(et,ro);var od={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};et.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var n=od[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};et.prototype.then=function(t,e){return this._getPromise().then(t,e)};et.prototype.catch=function(t){return this._getPromise().catch(t)};et.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};et.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(a,o,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),a)return e.handleError(a);e._emitRowEvents&&(c.length>1?o.forEach((u,l)=>{u.forEach(d=>{e.emit("row",d,c[l])})}):o.forEach(function(u){e.emit("row",u,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var n=(this.values||[]).map(Un.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let a=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(a)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(a){return a?r(a):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let a=new Error("Query values must be an array");return r(a)}var s=this.values.map(Un.prepareValue);t.native.query(this.text,s,r)}else this.queryMode==="extended"?t.native.query(this.text,[],r):t.native.query(this.text,r)}});var uo=N((iT,co)=>{"use strict";var io;try{io=require("pg-native")}catch(t){throw t}var cd=Or(),ao=require("events").EventEmitter,ud=require("util"),ld=Dr(),oo=so(),fe=co.exports=function(t){ao.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new cd(t.types),this.native=new io({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new ld(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};fe.Query=oo;ud.inherits(fe,ao);fe.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};fe.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(a){e._queryable=!1,e._errorAllQueries(a),e.emit("error",a)}),e.native.on("notification",function(a){e.emit("notification",{channel:a.relname,payload:a.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};fe.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e()})})};fe.prototype.query=function(t,e,r){var n,s,a,o,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")a=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(a=this.connectionParameters.query_timeout,n=new oo(t,e,r),!n.callback){let u,l;s=new this._Promise((d,p)=>{u=d,l=p}).catch(d=>{throw Error.captureStackTrace(d),d}),n.callback=(d,p)=>d?l(d):u(p)}return a&&(c=n.callback,o=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),c(u),n.callback=()=>{};var l=this._queryQueue.indexOf(n);l>-1&&this._queryQueue.splice(l,1),this._pulseQueryQueue()},a),n.callback=(u,l)=>{clearTimeout(o),c(u,l)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};fe.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(n,s){t=i(a=>a?s(a):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};fe.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};fe.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};fe.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};fe.prototype.ref=function(){};fe.prototype.unref=function(){};fe.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};fe.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var kn=N((oT,lo)=>{"use strict";lo.exports=uo()});var Fn=N((cT,Tt)=>{"use strict";var pd=Xa(),md=gt(),dd=In(),fd=to(),{DatabaseError:hd}=Cn(),{escapeIdentifier:gd,escapeLiteral:yd}=yt(),_d=i(t=>{var e;return e=class extends fd{constructor(n){super(n,t)}},i(e,"BoundPool"),e},"poolFactory"),$n=i(function(t){this.defaults=md,this.Client=t,this.Query=this.Client.Query,this.Pool=_d(this.Client),this._pools=[],this.Connection=dd,this.types=ht(),this.DatabaseError=hd,this.escapeIdentifier=gd,this.escapeLiteral=yd},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?Tt.exports=new $n(kn()):(Tt.exports=new $n(pd),Object.defineProperty(Tt.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new $n(kn())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Tt.exports,"native",{value:t}),t}}))});var mo=N((lT,po)=>{"use strict";var tt=require("fs"),Ed=Fn(),Td="The server does not support SSL connections",Sd="28000",Cd=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let n={checkServerIdentity(s,a){e.info("Certificate",{hostname:s,cert:{subject:a.subject,issuer:a.issuer,valid_from:a.valid_from,valid_to:a.valid_to}})}};return tt.existsSync(t.certAuthority)&&(n.ca=tt.readFileSync(t.certAuthority).toString()),tt.existsSync(t.clientCert)&&(n.cert=tt.readFileSync(t.clientCert).toString()),tt.existsSync(t.clientPrivateKey)&&(n.key=tt.readFileSync(t.clientPrivateKey).toString()),n},"getSslOptions"),Ad=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),Nd=i(async(t,e,r)=>{let n=!1;if(t.ssh){let{options:o}=await e.openTunnel({sshAuthMethod:t.ssh_method==="privateKey"?"IDENTITY_FILE":"USER_PASSWORD",sshTunnelHostname:t.ssh_host,sshTunnelPort:t.ssh_port,sshTunnelUsername:t.ssh_user,sshTunnelPassword:t.ssh_password,sshTunnelIdentityFile:t.ssh_key_file,sshTunnelPassphrase:t.ssh_key_passphrase,host:t.host,port:t.port});t={...t,...o},n=!0}t=Object.assign({},t,{sslType:Ad(t.sslType)});let s={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:Cd(t,r),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await Bn(s,r),isSshTunnel:n}},"createClient"),bd=i((t,e,r)=>{var n;if(r.message===Td&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),Bn({...t,isRetry:!0,ssl:!1},e);if(((n=r.code)==null?void 0:n.toString())===Sd&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),Bn({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),Bn=i((t,e)=>{let r=new Ed.Pool(t);return r.connect().then(n=>(n.release(),r)).catch(async n=>{if(await r.end(),t.isRetry)throw n;return bd(t,e,n)})},"createConnectionPool");po.exports={createClient:Nd}});var Gn=N((mT,go)=>{"use strict";var Kn=i(t=>` SELECT indexname, index_method, index_unique, @@ -76,7 +72,7 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec number_of_keys, where_expression, tablespace_name; - `,"getGET_TABLE_INDEXES"),ac=i(t=>` + `,"getGET_TABLE_INDEXES"),fo=i(t=>` SELECT obj_description(oid, 'pg_proc') AS description, proname AS function_name, provolatile AS volatility, @@ -88,7 +84,7 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec prorows AS estimated_rows, prosrc AS body, ${t===10?"CASE WHEN proiswindow is true THEN 'w' ELSE '' END AS kind":"prokind AS kind"} - FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),oc={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` + FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),ho={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` SELECT tables.table_name, tables.table_type FROM information_schema.tables AS tables INNER JOIN (SELECT @@ -133,9 +129,9 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec FROM pg_catalog.pg_attribute AS pg_attribute LEFT JOIN pg_catalog.pg_description AS pg_description ON (pg_description.objsubid=pg_attribute.attnum AND pg_description.objoid = pg_attribute.attrelid) - WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1)",GET_ROWS_COUNT:i(t=>`SELECT COUNT(*) AS quantity FROM ${t};`,"GET_ROWS_COUNT"),GET_SAMPLED_DATA:i((t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,"GET_SAMPLED_DATA"),GET_SAMPLED_DATA_SIZE:i((t,e)=>` + WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1)",GET_ROWS_COUNT:t=>`SELECT COUNT(*) AS quantity FROM ${t};`,GET_SAMPLED_DATA:(t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,GET_SAMPLED_DATA_SIZE:(t,e)=>` SELECT sum(pg_column_size(_hackolade_tmp_sampling_tbl.*)) AS _hackolade_tmp_sampling_tbl_size - FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,"GET_SAMPLED_DATA_SIZE"),GET_INHERITS_PARENT_TABLE_NAME:` + FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,GET_INHERITS_PARENT_TABLE_NAME:` SELECT pc.relname AS parent_table_name FROM pg_catalog.pg_inherits AS pi INNER JOIN pg_catalog.pg_class AS pc ON pc.oid = pi.inhparent @@ -153,7 +149,7 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec ON pcon.conindid = pc.oid LEFT JOIN pg_catalog.pg_tablespace AS pt ON pc.reltablespace = pt.oid - WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:ms(),GET_TABLE_INDEXES_V_10:ms(10),GET_TABLE_INDEXES_V_15:ms(15),GET_TABLE_FOREIGN_KEYS:` + WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:Kn(),GET_TABLE_INDEXES_V_10:Kn(10),GET_TABLE_INDEXES_V_15:Kn(15),GET_TABLE_FOREIGN_KEYS:` SELECT pcon.conname AS relationship_name, pcon.conkey AS table_columns_positions, pcon.confdeltype AS relationship_on_delete, @@ -193,7 +189,7 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec udt_name FROM information_schema.parameters WHERE specific_name = $1 - ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:ac(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:ac(10),GET_USER_DEFINED_TYPES:` + ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:fo(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:fo(10),GET_USER_DEFINED_TYPES:` SELECT pg_type.typrelid AS pg_class_oid, pg_type.typname AS name, pg_type.typtype AS type, @@ -369,80 +365,80 @@ var kt=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var lp=Objec WHERE pg_class.relkind = 'S' AND information_schema."sequences".sequence_schema = $1 ORDER BY sequence_name, column_name; - `},vh=i(t=>(Object.entries(oc).find(([r,n])=>t===n)||[])[0]||"Custom query","getQueryName");cc.exports={getQueryName:vh,...oc}});var lc=C((IC,uc)=>{var Ih=ds(),Ye=null,rr=null;uc.exports={initializeClient(t,e){Ye=t,rr=e,Ye.on("error",r=>e.error(r))},isClientInitialized(){return!!Ye},releaseClient(){return Ye?new Promise(t=>{Ye.end(()=>{Ye=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let n=Ih.getQueryName(t);rr.info("Execute query",{queryName:n,params:e});let s=Date.now(),a=await Ye.query(t,e),o=Date.now()-s;rr.info("Query executed",{queryName:n,params:e,duration:o,rowsCount:a.rowCount});let c=a.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(n){return n.query=t,n.params=e,rr.error(n),null}}}});var dc=C((OC,mc)=>{var pc=i(t=>{let e=t.reduce((n,s)=>s.properties?{...n,[s.name]:{...s,...pc(s.properties)}}:{...n,[s.name]:s},{}),r=Object.entries(e).filter(([n,s])=>s.required).map(([n])=>n);return{properties:e,required:r}},"getJsonSchema");mc.exports={getJsonSchema:pc}});var fs=C((wC,fc)=>{var Ke=null,Oh=i(t=>{Ke=t.require("lodash")},"setDependencies"),qt={column_default:"default",is_nullable:{keyword:"required",values:{YES:!1,NO:!0}},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:i((t,e)=>e!==-1&&Fh(t.data_type),"check")},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:"length",description:"description",domain_name:"domain_name"},Rh=i((t,e,r)=>{var n;return(n=qt[e])!=null&&n.check?qt[e].check(t,r)?r:"":Ke.get(qt,`${e}.values.${r}`,r)},"getColumnValue"),wh=i(t=>e=>Ke.chain(e).toPairs().map(([r,n])=>{var s;return[((s=qt[r])==null?void 0:s.keyword)||qt[r],Rh(e,r,n)]}).filter(([r,n])=>r&&!Ke.isNil(n)).fromPairs().thru(Dh(t)).value(),"mapColumnData"),Dh=i(t=>e=>({...e,...qh(t,e)}),"setColumnType"),qh=i((t,e)=>e.type==="ARRAY"?xh(t,e):e.type==="USER-DEFINED"?nr(t,e.udt_name):e.domain_name?nr(t,e.domain_name):nr(t,e.type),"getType"),xh=i((t,e)=>({...nr(t,e.udt_name.slice(1)),array_type:Ke.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),nr=i((t,e)=>{switch(e){case"bigint":case"bigserial":case"smallint":case"integer":case"numeric":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"int8":return{type:"numeric",mode:"bigint"};case"int2":return{type:"numeric",mode:"smallint"};case"int4":return{type:"numeric",mode:"integer"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return Ke.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),Ph=i((t,e)=>{let r=Ke.first(e)||{};return t.map(n=>{if(n.type!=="json")return n;let s=r[n.name],a=Lh(s),o=Mh(a);return{...n,subtype:o}})},"setSubtypeFromSampledJsonValues"),Lh=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),Mh=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),Fh=i(t=>Ke.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");fc.exports={setDependencies:Oh,mapColumnData:wh,setSubtypeFromSampledJsonValues:Ph}});var xt=C((qC,hc)=>{var Uh=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],at=null,kh=i(t=>{at=t.require("lodash")},"setDependencies"),$h=i(t=>at.chain(t).toPairs().reject(([e,r])=>at.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),Bh=i(t=>e=>{var r;return(r=at.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),Kh=i(t=>/\s|\W/.test(t)||at.includes(Uh,at.toUpper(t))?`"${t}"`:t,"wrapInQuotes");hc.exports={clearEmptyPropertiesInObject:$h,setDependencies:kh,getColumnNameByPosition:Bh,wrapInQuotes:Kh}});var _c=C((PC,yc)=>{var{getColumnNameByPosition:Gh}=xt(),hs=null,Vh=i(t=>{hs=t.require("lodash")},"setDependencies"),gc=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Hh=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";case"p":return"PARTIAL";default:return""}},"prepareMatch"),Wh=i((t,e,r,n)=>hs.map(t,s=>({relationshipName:s.relationship_name,dbName:s.foreign_table_schema,parentCollection:s.foreign_table_name,parentField:s.foreign_columns,childDbName:r,childCollection:e,childField:hs.map(s.table_columns_positions,Gh(n)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:gc(s.relationship_on_delete),relationshipOnUpdate:gc(s.relationship_on_update),relationshipMatch:Hh(s.relationship_match)}})),"prepareForeignKeys");yc.exports={setDependencies:Vh,prepareForeignKeys:Wh}});var Sc=C((MC,Tc)=>{var sr=null,Qh=i(t=>{sr=t.require("lodash")},"setDependencies"),Ec=i(t=>sr.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:Yh(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),Yh=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),jh=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),zh=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),Xh=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Zh=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:Ec(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:sr.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:jh(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:Xh(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:zh(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),Jh=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:sr.toLower(t.external_language),inputArgs:Ec(e),body:t.routine_definition}),"mapProcedureData");Tc.exports={setDependencies:Qh,mapFunctionData:Zh,mapProcedureData:Jh}});var vc=C((UC,bc)=>{var{clearEmptyPropertiesInObject:Pt,getColumnNameByPosition:ir}=xt(),V=null,eg=i(t=>{V=t.require("lodash")},"setDependencies"),Ac=i((t,e)=>{if(!t&&!e)return null;let r=Cc(t),n=Cc(e==null?void 0:e.toast_options),s=r.fillfactor,a=r.parallel_workers,o=r.autovacuum_enabled,c=Pt({vacuum_index_cleanup:r.vacuum_index_cleanup,vacuum_truncate:r.vacuum_truncate,autovacuum_vacuum_threshold:r.autovacuum_vacuum_threshold,autovacuum_vacuum_scale_factor:r.autovacuum_vacuum_scale_factor,autovacuum_vacuum_insert_threshold:r.autovacuum_vacuum_insert_threshold,autovacuum_vacuum_insert_scale_factor:r.autovacuum_vacuum_insert_scale_factor,autovacuum_analyze_threshold:r.autovacuum_analyze_threshold,autovacuum_analyze_scale_factor:r.autovacuum_analyze_scale_factor,autovacuum_vacuum_cost_delay:r.autovacuum_vacuum_cost_delay,autovacuum_vacuum_cost_limit:r.autovacuum_vacuum_cost_limit,autovacuum_freeze_min_age:r.autovacuum_freeze_min_age,autovacuum_freeze_max_age:r.autovacuum_freeze_max_age,autovacuum_freeze_table_age:r.autovacuum_freeze_table_age,autovacuum_multixact_freeze_min_age:r.autovacuum_multixact_freeze_min_age,autovacuum_multixact_freeze_max_age:r.autovacuum_multixact_freeze_max_age,autovacuum_multixact_freeze_table_age:r.autovacuum_multixact_freeze_table_age,log_autovacuum_min_duration:r.log_autovacuum_min_duration}),u=r.user_catalog_table,l=n.autovacuum_enabled,p=Pt({toast_tuple_target:r.toast_tuple_target,toast_vacuum_index_cleanup:n.vacuum_index_cleanup,toast_vacuum_truncate:n.vacuum_truncate,toast_autovacuum_vacuum_threshold:n.autovacuum_vacuum_threshold,toast_autovacuum_vacuum_scale_factor:n.autovacuum_vacuum_scale_factor,toast_autovacuum_vacuum_insert_threshold:n.autovacuum_vacuum_insert_threshold,toast_autovacuum_vacuum_insert_scale_factor:n.autovacuum_vacuum_insert_scale_factor,toast_autovacuum_vacuum_cost_delay:n.autovacuum_vacuum_cost_delay,toast_autovacuum_vacuum_cost_limit:n.autovacuum_vacuum_cost_limit,toast_autovacuum_freeze_min_age:n.autovacuum_freeze_min_age,toast_autovacuum_freeze_max_age:n.autovacuum_freeze_max_age,toast_autovacuum_freeze_table_age:n.autovacuum_freeze_table_age,toast_autovacuum_multixact_freeze_min_age:n.autovacuum_multixact_freeze_min_age,toast_autovacuum_multixact_freeze_max_age:n.autovacuum_multixact_freeze_max_age,toast_autovacuum_multixact_freeze_table_age:n.autovacuum_multixact_freeze_table_age,toast_log_autovacuum_min_duration:n.log_autovacuum_min_duration}),m={fillfactor:s,parallel_workers:a,autovacuum_enabled:o,autovacuum:V.isEmpty(c)?null:c,toast_autovacuum_enabled:l,toast:V.isEmpty(p)?null:p,user_catalog_table:u};return Pt(m)},"prepareStorageParameters"),tg=i((t,e)=>{if(!t)return null;let r=rg(t),n=V.some(t.partition_attributes_positions,o=>o===0),s=n?"partitioning_expression":"compositePartitionKey",a=n?ng(t,e):V.map(t.partition_attributes_positions,ir(e));return[{partitionMethod:r,partitionBy:n?"expression":"keys",[s]:a}]},"prepareTablePartition"),rg=i(t=>{switch(t.partition_method){case"h":return"HASH";case"l":return"LIST";case"r":return"RANGE";default:return""}},"getPartitionMethod"),ng=i((t,e)=>{let r=0,n=V.split(t.expressions,",");return V.chain(t.partition_attributes_positions).map(s=>{if(s===0){let a=n[r];return r++,a}return ir(e)(s)}).join(",").value()},"getPartitionExpression"),Nc=i(t=>V.split(t,"="),"splitByEqualitySymbol"),sg=i(t=>V.find(t,{type:"json"}),"checkHaveJsonTypes"),ig=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),ag=i((t,e,r)=>V.reduce(t,(n,s)=>{switch(s.constraint_type){case"c":return{...n,chkConstr:[...n.chkConstr,ug(s)]};case"p":return{...n,primaryKey:[...n.primaryKey,og(s,e)]};case"u":return{...n,uniqueKey:[...n.uniqueKey,cg(s,e,r)]};default:return n}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),og=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:V.map(t.constraint_keys,ir(e)),indexStorageParameters:V.join(t.storage_parameters,","),indexTablespace:t.tablespace}),"getPrimaryKeyConstraint"),cg=i((t,e,r)=>{let n=V.find(r,a=>a.indexname===t.constraint_name),s=n!=null&&n.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"";return{constraintName:t.constraint_name,compositeUniqueKey:V.map(t.constraint_keys,ir(e)),indexStorageParameters:V.join(t.storage_parameters,","),indexTablespace:t.tablespace,indexComment:t.description,...s&&{nullsDistinct:s}}},"getUniqueKeyConstraint"),ug=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,noInherit:t.no_inherit,constrDescription:t.description}),"getCheckConstraint"),lg=i(t=>V.map(t,e=>{let r=pg(e),n=V.slice(r,0,e.number_of_keys),s=V.chain(r).slice(e.number_of_keys).map(c=>V.pick(c,"name")).value(),a=e.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"",o={indxName:e.indexname,index_method:e.index_method,unique:e.index_unique??!1,index_tablespace_name:e.tablespace_name||"",index_storage_parameter:dg(e.storage_parameters),where:e.where_expression||"",include:s,columns:e.index_method==="btree"?n:V.map(n,c=>V.omit(c,"sortOrder","nullsOrder")),...a&&{nullsDistinct:a}};return Pt(o)}),"prepareTableIndexes"),pg=i(t=>V.chain(t.columns).map((e,r)=>{if(!e)return;let n=V.get(t,`ascendings.${r}`,!1)?"ASC":"DESC",s=mg(V.get(t,`nulls_first.${r}`)),a=V.get(t,`opclasses.${r}`,""),o=V.get(t,`collations.${r}`,"");return{name:e,sortOrder:n,nullsOrder:s,opclass:a,collation:o}}).compact().value(),"mapIndexColumns"),mg=i(t=>V.isNil(t)?"":t?"NULLS FIRST":"NULLS LAST","getNullsOrder"),dg=i(t=>{if(!t)return null;let e=V.fromPairs(V.map(t,n=>Nc(n))),r={index_fillfactor:e.fillfactor,deduplicate_items:e.deduplicate_items,index_buffering:e.index_buffering,fastupdate:e.fastupdate,gin_pending_list_limit:e.gin_pending_list_limit,pages_per_range:e.pages_per_range,autosummarize:e.autosummarize};return Pt(r)},"getIndexStorageParameters"),fg=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",n=(t==null?void 0:t.relpersistence)==="u",s=Ac(t==null?void 0:t.reloptions,e),a=t==null?void 0:t.spcname,o=t.partition_expr;return{temporary:r,unlogged:n,storage_parameter:s,table_tablespace_name:a,partitionBounds:o}},"prepareTableLevelData"),hg=i(t=>{switch(gg(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),gg=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),Cc=i(t=>V.chain(t).map(Nc).map(([e,r])=>[e,hg(r)]).fromPairs().value()||{},"prepareOptions"),yg=i((t,e)=>V.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");bc.exports={prepareStorageParameters:Ac,prepareTablePartition:tg,setDependencies:eg,checkHaveJsonTypes:sg,prepareTableConstraints:ag,prepareTableLevelData:fg,prepareTableIndexes:lg,getSampleDocSize:ig,prepareTableInheritance:yg}});var Oc=C(($C,Ic)=>{var{mapColumnData:_g}=fs(),De=null,Eg=i(t=>{De=t.require("lodash")},"setDependencies"),Tg=i((t,e)=>De.chain(t).map(r=>{switch(r.type){case"e":return Sg(r);case"r":return Cg(r);case"c":return Ag(r);default:return null}}).compact().concat(De.map(e,bg)).value(),"getUserDefinedTypes"),Sg=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Cg=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Ag=i(t=>{let e=De.map(t.columns,_g([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),Ng=i(t=>t.type==="c","isTypeComposite"),bg=i(t=>{var e;return{name:t.domain_name,type:"domain",underlyingType:De.flow(Ig(t),Og(t),Rg(t),wg(t))(vg(t)),collation:t.collation_name||"",default:t.domain_default||"",required:(e=De.first(t.constraints))==null?void 0:e.not_null,checkConstraints:De.map(t.constraints,Dg)}},"mapDomainType"),vg=i(t=>t.data_type==="USER-DEFINED"?t.udt_name:t.data_type,"getUnderlyingType"),Ig=i(t=>e=>t.character_maximum_length?`${e}(${t.character_maximum_length})`:e,"setLength"),Og=i(t=>e=>e!=="numeric"?e:De.isNumber(t.numeric_precision)&&De.isNumber(t.numeric_scale)?`${e}(${t.numeric_precision},${t.numeric_scale})`:De.isNumber(t.numeric_precision)?`${e}(${t.numeric_precision})`:e,"setPrecisionAndScale"),Rg=i(t=>e=>t.interval_type?`${e} ${t.interval_type}`:e,"setIntervalType"),wg=i(t=>e=>De.isNumber(t.interval_precision)?`${e}(${t.interval_precision})`:e,"setIntervalPrecision"),Dg=i(t=>({name:t.constraint_name,expression:t.expression}),"mapDomainConstraint");Ic.exports={setDependencies:Eg,getUserDefinedTypes:Tg,isTypeComposite:Ng}});var wc=C((KC,Rc)=>{var{clearEmptyPropertiesInObject:qg,wrapInQuotes:xg}=xt(),ke=null,Pg=i(t=>{ke=t.require("lodash")},"setDependencies"),gs=" (v)",Lg=i(t=>t==="VIEW","isViewByTableType"),Mg=i(t=>ke.endsWith(t,gs),"isViewByName"),Fg=i(t=>t.slice(0,-gs.length),"removeViewNameSuffix"),Ug=i(t=>`${t}${gs}`,"setViewSuffix"),kg=i((t,e,r={})=>{let n=ke.trim(e.view_definition||r.definition||"");return n?`CREATE VIEW ${xg(t)} AS ${n}`:""},"generateCreateViewScript"),$g=i((t,e,r)=>{let n={withCheckOption:t.check_option!=="NONE"||ke.isNil(t.check_option),checkTestingScope:Bg(t.check_option),viewOptions:ke.fromPairs(ke.map(e==null?void 0:e.view_options,Gg)),temporary:(e==null?void 0:e.persistence)==="t",recursive:Kg(t),description:e==null?void 0:e.description,triggers:r};return qg(n)},"prepareViewData"),Bg=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),Kg=i(t=>ke.startsWith(ke.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),Gg=i(t=>ke.split(t,"="),"splitByEqualitySymbol");Rc.exports={setDependencies:Pg,isViewByTableType:Lg,isViewByName:Mg,removeViewNameSuffix:Fg,generateCreateViewScript:kg,setViewSuffix:Ug,prepareViewData:$g}});var qc=C((VC,Dc)=>{var ar=null,Vg=i(t=>{ar=t.require("lodash")},"setDependencies"),Hg=i((t,e)=>ar.chain(t).map(r=>({...r,...ar.find(e,{trigger_name:r.trigger_name})||{}})).map(Wg).value(),"getTriggers"),Wg=i(t=>{var e;return{name:t.trigger_name,triggerDescription:t.description,triggerConstraint:t.constraint,triggerTable:`${t.event_object_schema}.${t.event_object_table}`,triggerReferencedTable:t.referenced_table_name?[t.referenced_table_schema,t.referenced_table_name]:[],triggerType:t.action_timing,triggerEvents:Qg(t),triggerUpdateColumns:(e=t.update_attributes)==null?void 0:e.filter(Boolean),triggerDeferrable:t.deferrable,triggerTimeConstraintCheck:t.deferred?"INITIALLY DEFERRED":"INITIALLY IMMEDIATE",triggerReferencing:!!t.action_reference_old_table||!!t.action_reference_new_table,triggerBeforeImageTransitionRelation:t.action_reference_old_table||"",triggerAfterImageTransitionRelation:t.action_reference_new_table||"",triggerEachRowStatement:t.action_orientation==="ROW"?"FOR EACH ROW":"FOR EACH STATEMENT",triggerCondition:t.action_condition,triggerFunction:Yg(t.action_statement)}},"getTrigger"),Qg=i(t=>ar.map(t.trigger_events,e=>({triggerEvent:e})),"getTriggerEvents"),Yg=i(t=>{var e,r,n;return((n=(r=(e=/EXECUTE (?:FUNCTION|PROCEDURE)(?[\s\S]*)/.exec(t))==null?void 0:e.groups)==null?void 0:r.function)==null?void 0:n.trim())||""},"getFunctionFromTrigger");Dc.exports={setDependencies:Vg,getTriggers:Hg}});var Lc=C((WC,Pc)=>{var jg=i((t,e)=>[zg,Xg].reduce(({attributes:r,entityLevel:n},s)=>s(r,n),{attributes:t,entityLevel:e}),"reorganizeConstraints"),zg=i((t,e)=>{var a,o,c;if(((c=(o=(a=e.primaryKey)==null?void 0:a[0])==null?void 0:o.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let n=e.primaryKey[0],s=n.compositePrimaryKey[0];return{attributes:Zg(t,s,n),entityLevel:ry(e)}},"reorganizePrimaryKeys"),Xg=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:n},s)=>{if(!(s.compositeUniqueKey.length===1))return{attributes:r,entityLevel:n};let o=s.compositeUniqueKey[0];return{attributes:ey(r,o,s),entityLevel:ny(n,s)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Zg=i((t,e,r)=>t.map(n=>n.name!==e?n:Jg(n,r)),"setAttributesPrimaryKeyData"),Jg=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:xc(e)}),"setPrimaryKeyData"),ey=i((t,e,r)=>t.map(n=>n.name!==e?n:ty(n,r)),"setAttributesUniqueKeyData"),ty=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:xc(e)}),"setUniqueKeyData"),xc=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexComment:t.indexComment}],"getOptions"),ry=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),ny=i((t,e)=>{let r=t.uniqueKey.filter(n=>n.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Pc.exports={reorganizeConstraints:jg}});var or=C((YC,Mc)=>{var Es=class Es{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};i(Es,"Sequence");var ys=Es,Ts=class Ts{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};i(Ts,"SequenceDto");var _s=Ts;Mc.exports={Sequence:ys,SequenceDto:_s}});var Uc=C((ZC,Fc)=>{var{Sequence:zC,SequenceDto:XC}=or(),sy=i(({sequence:t})=>t.column_name?[{entity:t.table_name,name:t.column_name}]:[],"getOwnedByColumn"),iy=i(({sequence:t})=>({sequenceName:t.sequence_name,increment:Number(t.increment),start:Number(t.start_value),dataType:t.data_type,maxValue:Number(t.maximum_value),minValue:Number(t.minimum_value),cache:Number(t.cache_size),temporary:t.rel_persistance==="t",unlogged:t.rel_persistance==="u",cycle:t.cycle_option==="YES",ownedByColumn:sy({sequence:t}),ownedByNone:!t.column_name}),"mapSequenceData");Fc.exports={mapSequenceData:iy}});var Cs=C((eA,Bc)=>{var{createClient:ay}=ic(),k=lc(),{getJsonSchema:kc}=dc(),{setDependencies:oy,mapColumnData:cy,setSubtypeFromSampledJsonValues:uy}=fs(),{setDependencies:ly,clearEmptyPropertiesInObject:$c}=xt(),{setDependencies:py,prepareForeignKeys:my}=_c(),{setDependencies:dy,mapFunctionData:fy,mapProcedureData:hy}=Sc(),{setDependencies:gy,prepareTablePartition:yy,checkHaveJsonTypes:_y,prepareTableConstraints:Ey,getSampleDocSize:Ty,prepareTableLevelData:Sy,prepareTableIndexes:Cy,prepareTableInheritance:Ay}=vc(),{setDependencies:Ny,getUserDefinedTypes:by,isTypeComposite:vy}=Oc(),{setDependencies:Iy,isViewByTableType:Oy,isViewByName:Ry,removeViewNameSuffix:wy,generateCreateViewScript:Dy,setViewSuffix:qy,prepareViewData:xy}=wc(),{setDependencies:Py,getTriggers:Ly}=qc(),$=ds(),{reorganizeConstraints:My}=Lc(),{mapSequenceData:Fy}=Uc(),cr=null,ee=null,_e=null,Ss=14;Bc.exports={setDependencies(t){ee=t.require("lodash"),ly(t),gy(t),oy(t),py(t),Iy(t),dy(t),Ny(t),Py(t)},async connect(t,e){k.isClientInitialized()&&await this.disconnect();let{client:r,sshTunnel:n}=await ay(t,e);k.initializeClient(r,e),cr=n,_e=e,Ss=await this._getServerVersion()},async disconnect(){cr&&(cr.close(),cr=null),await k.releaseClient()},pingDb(){return k.query($.PING)},applyScript(t){return k.query(t)},async getDatabaseNames(){return ee.map(await k.query($.GET_DATABASES),"database_name")},async logVersion(){let t=await k.queryTolerant($.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved";_e.info(`PostgreSQL version: ${e}`)},async getAllSchemasNames(){return(await k.query($.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!Uy(e))},async getTablesNames(t){let e=await k.query($.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:n})=>!ee.includes(r,n)).map(({table_name:n,table_type:s})=>Oy(s)?qy(n):n)},async getDbLevelData(){var n,s,a;_e.progress("Get database data");let t=(n=await k.queryTolerant($.GET_DB_NAME,[],!0))==null?void 0:n.current_database,e=(s=await k.queryTolerant($.GET_DB_ENCODING,[],!0))==null?void 0:s.server_encoding,r=(a=await k.queryTolerant($.GET_DB_COLLATE_NAME,[],!0))==null?void 0:a.default_collate_name;return $c({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r,n=!1,s=!1){let a=await this._retrieveUserDefinedTypes(t),o=await k.queryTolerant($.GET_NAMESPACE_OID,[t],!0),c=o==null?void 0:o.oid,u=n?await k.queryTolerant($.GET_PARTITIONS,[c]):[],[l,p]=ee.partition(e,Ry),m=p.flatMap(h=>[{tableName:h},...ee.filter(u,{parent_name:h}).map(({child_name:T,is_parent_partitioned:_})=>({isParentPartitioned:_,tableName:T}))]),d=await ot(ee.uniq(m),ee.bind(this._retrieveSingleTableData,this,r,c,t,a,s));return{views:await ot(l,ee.bind(this._retrieveSingleViewData,this,c,t,s)),tables:d,modelDefinitions:kc(a)}},async retrieveSchemaLevelData(t,e){var m;if(e)return _e.info("Functions and procedures ignored"),{functions:[],procedures:[]};_e.progress("Get Functions and Procedures",t);let r=(m=await k.queryTolerant($.GET_NAMESPACE_OID,[t],!0))==null?void 0:m.oid,n=await k.queryTolerant($.GET_FUNCTIONS_WITH_PROCEDURES,[t]),s=await k.queryTolerant($y(Ss),[r]),[a,o]=ee.partition(ee.filter(n,"routine_type"),{routine_type:"FUNCTION"}),c=await ot(a,async d=>{let f=await k.queryTolerant($.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[d.specific_name]),h=ee.find(s,{function_name:d.name});return fy(d,f,h)}),u=await ot(o,async d=>{let f=await k.queryTolerant($.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[d.specific_name]),h=ee.find(s,{function_name:d.name});return hy(d,f,h)}),p=(await k.queryTolerant($.GET_SEQUENCES,[t])).map(d=>Fy({sequence:d}));return{functions:c,procedures:u,sequences:p}},async _retrieveUserDefinedTypes(t){_e.progress("Get User-Defined Types",t);let e=await k.queryTolerant($.GET_USER_DEFINED_TYPES,[t]),r=await k.queryTolerant($.GET_DOMAIN_TYPES,[t]),n=await ot(e,async a=>vy(a)?{...a,columns:await k.queryTolerant($.GET_COMPOSITE_TYPE_COLUMNS,[a.pg_class_oid])}:a),s=await ot(r,async a=>({...a,constraints:await k.queryTolerant($.GET_DOMAIN_TYPES_CONSTRAINTS,[a.domain_name,t])}));return by(n,s)},async _retrieveSingleTableData(t,e,r,n,s,{tableName:a,isParentPartitioned:o}){var Ie;_e.progress("Get table data",r,a);let c=await k.queryTolerant($.GET_TABLE_LEVEL_DATA,[a,e],!0),u=c==null?void 0:c.oid,l=await k.queryTolerant($.GET_TABLE_TOAST_OPTIONS,[a,e],!0),p=await k.queryTolerant($.GET_TABLE_PARTITION_DATA,[u],!0),m=await this._getTableColumns(a,r,u),d=await k.queryTolerant($.GET_DESCRIPTION_BY_OID,[u],!0),f=await k.queryTolerant($.GET_INHERITS_PARENT_TABLE_NAME,[u]),h=await k.queryTolerant($.GET_TABLE_CONSTRAINTS,[u]),T=await k.queryTolerant(ky(Ss),[u]),_=await k.queryTolerant($.GET_TABLE_FOREIGN_KEYS,[u]),y=await this._getTriggers(r,a,e,u,s);_e.info("Table data retrieved",{schemaName:r,tableName:a,columnTypes:m.map(A=>A.data_type)});let N=yy(p,m),S=Sy(c,l),b=By(d),I=Ay(r,f),R=Ey(h,m,T),M=Cy(T),v=my(_,a,r,m),D={partitioning:N,description:b,triggers:y,Indxs:M,...S,...R,...o?{partitionOf:(Ie=ee.first(I))==null?void 0:Ie.parentTable}:{inherits:I}},G=$c(D),P=m.map(cy(n)),X=_y(P),ve=[];X&&(ve=await this._getDocuments(r,a,P,t),P=uy(P,ve));let{attributes:me,entityLevel:U}=My(P,G);return{name:a,entityLevel:U,jsonSchema:kc(me),documents:ve,relationships:v}},async _getTriggers(t,e,r,n,s){if(s)return _e.info("Triggers ignored"),[];let a=await k.queryTolerant($.GET_TRIGGERS,[t,e]),o=await k.queryTolerant($.GET_TRIGGERS_ADDITIONAL_DATA,[r,n]);return Ly(a,o)},async _getTableColumns(t,e,r){_e.progress("Get columns",e,t);let n=await k.query($.GET_TABLE_COLUMNS,[t,e]),s=await k.queryTolerant($.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return ee.map(n,a=>({...a,...ee.find(s,{name:a.column_name})||{}}))},async _getDocuments(t,e,r,n){var p;_e.progress("Sampling table",t,e);let s=`${t}.${e}`,a=((p=await k.queryTolerant($.GET_ROWS_COUNT(s),[],!0))==null?void 0:p.quantity)||0,o=Ty(a,n),c=r.filter(({type:m})=>ee.includes(["json","jsonb"],m)),u=ee.map(c,"name").join(", "),l=await k.queryTolerant($.GET_SAMPLED_DATA_SIZE(s,u),[o],!0);return _e.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:l==null?void 0:l._hackolade_tmp_sampling_tbl_size}),await k.queryTolerant($.GET_SAMPLED_DATA(s,u),[o])},async _retrieveSingleViewData(t,e,r,n){_e.progress("Get view data",e,n),n=wy(n);let s=await k.query($.GET_VIEW_DATA,[n,e],!0),a=!s.view_definition&&await k.queryTolerant($.GET_VIEW_SELECT_STMT_FALLBACK,[n,e],!0),o=await k.queryTolerant($.GET_VIEW_OPTIONS,[n,t],!0),c=await this._getTriggers(e,n,t,o==null?void 0:o.oid,r),u=Dy(n,s,a),l=xy(s,o,c);return u?{name:n,data:l,ddl:{script:u,type:"postgres"}}:(_e.info("View select statement was not retrieved",{schemaName:e,viewName:n}),{name:n,data:l,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await k.queryTolerant($.GET_VERSION_AS_NUM,[],!0),e=ee.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var Uy=i(t=>!!(ee.startsWith(t,"pg_")||ee.includes(["information_schema"],t)),"isSystemSchema"),ky=i(t=>t===10?$.GET_TABLE_INDEXES_V_10:t>15?$.GET_TABLE_INDEXES_V_15:$.GET_TABLE_INDEXES,"getGetIndexesQuery"),$y=i(t=>t===10?$.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:$.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),By=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),ot=i((t,e)=>Promise.all(ee.map(t,e)),"mapPromises")});var Gc=C((rA,Kc)=>{"use strict";var{createLogger:ur}=Nr(),re=Cs();Kc.exports={async disconnect(t,e,r,n){await re.disconnect(),r()},async testConnection(t,e,r,n){try{As("Test connection",t,e);let s=ur({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});re.setDependencies(n),await re.connect(t,s),await re.pingDb(),await re.logVersion(),r()}catch(s){e.log("error",je(s),"Test connection instance log"),r(je(s))}finally{await re.disconnect()}},async getDatabases(t,e,r,n){try{As("Get databases",t,e);let s=ur({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});re.setDependencies(n),await re.connect(t,s),await re.logVersion();let a=await re.getDatabaseNames();return e.log("info",a,"All databases list",t.hiddenKeys),r(null,a)}catch(s){return e.log("error",s),r(je(s))}},getDocumentKinds:i(function(t,e,r){r(null,[])},"getDocumentKinds"),async getDbCollectionsNames(t,e,r,n){try{As("Get DB table names",t,e);let s=ur({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});re.setDependencies(n),await re.connect(t,s),await re.logVersion();let o=await(await re.getAllSchemasNames()).reduce(async(c,u)=>{let l=await c;try{let p=await re.getTablesNames(u);return l.concat({dbName:u,dbCollections:p,isEmpty:p.length===0})}catch(p){return s.info(`Error reading database "${u}"`),s.error(p),l.concat({dbName:u,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,o)}catch(s){e.log("error",je(s),"Get DB collections names"),r(je(s)),await re.disconnect()}},async getDbCollectionsData(t,e,r,n){try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let s=ur({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});s.progress("Start reverse engineering...");let a=t.collectionData.collections,o=t.collectionData.dataBaseNames,c=await re.getDbLevelData(),{packages:u,relationships:l}=await Promise.all(o.map(async p=>{let{tables:m,views:d,modelDefinitions:f}=await re.retrieveEntitiesData(p,a[p],t.recordSamplingSettings,t.includePartitions,t.ignoreUdfUdpTriggers),{functions:h,procedures:T,triggers:_,sequences:y}=await re.retrieveSchemaLevelData(p,t.ignoreUdfUdpTriggers);return s.progress("Schema data fetched successfully",p),{schemaName:p,tables:m,views:d,functions:h,procedures:T,modelDefinitions:f,triggers:_,sequences:y}})).then(p=>{let m=p.flatMap(({tables:f})=>f.map(h=>h.relationships)).flat();return{packages:p.flatMap(({schemaName:f,tables:h,views:T,functions:_,procedures:y,triggers:N,modelDefinitions:S,sequences:b})=>{let I={UDFs:_,Procedures:y,triggers:N,sequences:b},R=h.map(M=>({dbName:f,collectionName:M.name,documents:M.documents,views:[],emptyBucket:!1,entityLevel:M.entityLevel,validation:{jsonSchema:M.jsonSchema},bucketInfo:I,modelDefinitions:S})).sort(M=>n.require("lodash").isEmpty(M.entityLevel.inherits)?-1:1);if(T!=null&&T.length){let M={dbName:f,views:T,emptyBucket:!1};return[...R,M]}return R}),relationships:m}}).then(({packages:p,relationships:m})=>({packages:Ky(p),relationships:m}));s.info("The data is processed and sent to the application",{packagesLength:u==null?void 0:u.length,relationshipsLength:l==null?void 0:l.length}),r(null,u,c,l)}catch(s){e.log("error",je(s),"Retrieve tables data"),r(je(s))}finally{await re.disconnect()}}};var je=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),As=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),Ky=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages")});var Hc=C((sA,Vc)=>{var lr=Cs(),Gy=i(async(t,e,r)=>{try{lr.setDependencies(r),await lr.connect(t,e),await lr.logVersion(),await lr.applyScript(Vy(t.script))}catch(n){throw e.error(n),Hy(n)}},"applyToInstance"),Vy=i(t=>{let e=/CREATE DATABASE[^;]*;/gi;return t.replace(e,"")},"removeCreateDbScript"),Hy=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");Vc.exports={applyToInstance:Gy}});var ne=C((aA,Wc)=>{var vs=class vs{script;isDropScript};i(vs,"ModificationScript");var Ns=vs,Is=class Is{isActivated;scripts;static getInstances(e,r,n){return(e||[]).filter(Boolean).map(s=>({isActivated:r,scripts:[{isDropScript:n,script:s}]}))}static getInstance(e,r,n){var s;if((s=e==null?void 0:e.filter(Boolean))!=null&&s.length)return{isActivated:r,scripts:e.filter(Boolean).map(a=>({isDropScript:n,script:a}))}}static getDropAndRecreateInstance(e,r,n){let s=[];if(e&&s.push({isDropScript:!0,script:e}),r&&s.push({isDropScript:!1,script:r}),!!(s!=null&&s.length))return{isActivated:n,scripts:s}}};i(Is,"AlterScriptDto");var bs=Is;Wc.exports={ModificationScript:Ns,AlterScriptDto:bs}});var Ps=C((cA,Qc)=>{var Ds=class Ds{sortOrder;nullsOrder;isActivated;keyId;collation;opclass};i(Ds,"AlterIndexColumnDto");var Os=Ds,qs=class qs{keyId};i(qs,"AlterIndexIncludeColumnDto");var Rs=qs,xs=class xs{id;isActivated;index_method;ifNotExist;only;index_tablespace_name;indxName;columns;include;index_storage_parameter};i(xs,"AlterIndexDto");var ws=xs;Qc.exports={AlterIndexDto:ws,AlterIndexColumnDto:Os,AlterIndexIncludeColumnDto:Rs}});var Ge=C((pA,Yc)=>{var{AlterIndexDto:lA}=Ps(),Ks=class Ks{id;constraintName;indexStorageParameters;indexTablespace;indexInclude};i(Ks,"AlterCollectionColumnKeyOptionDto");var Lt=Ks,Gs=class Gs{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};i(Gs,"AlterCollectionColumnDto");var Ls=Gs,Vs=class Vs extends Lt{compositePrimaryKey};i(Vs,"AlterCollectionRoleCompModPKDto");var Ms=Vs,Hs=class Hs extends Lt{compositeUniqueKey};i(Hs,"AlterCollectionRoleCompModUniqueKeyDto");var Fs=Hs,Ws=class Ws{new;old};i(Ws,"AlterCollectionRoleCompModPrimaryKey");var Us=Ws,Qs=class Qs{new;old};i(Qs,"AlterCollectionRoleCompModUniqueKey");var ks=Qs,Ys=class Ys{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;table_tablespace_name;bucketId;compMod;name;roleType;patternProperties};i(Ys,"AlterCollectionRoleDto");var $s=Ys,js=class js{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(js,"AlterCollectionDto");var Bs=js;Yc.exports={AlterCollectionDto:Bs,AlterCollectionRoleDto:$s,AlterCollectionColumnDto:Ls,AlterCollectionColumnKeyOptionDto:Lt,AlterCollectionRoleCompModPrimaryKey:Us,AlterCollectionRoleCompModPKDto:Ms,AlterCollectionRoleCompModUniqueKeyDto:Fs,AlterCollectionRoleCompModUniqueKey:ks}});var zc=C((dA,jc)=>{var Wy=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),Qy=Object.values(Wy);jc.exports={ReservedWordsAsArray:Qy}});var L=C((gA,Xc)=>{var{AlterCollectionDto:fA,AlterCollectionRoleDto:hA}=Ge(),{ReservedWordsAsArray:Yy}=zc(),jy=/\t|\n|'|\f|\r/gm;Xc.exports=t=>{let e=i(A=>t.get(A,"[0].code")||t.get(A,"[0].name",""),"getDbName"),r=i(A=>A&&(A.code||A.collectionName)||"","getEntityName"),n=i(A=>A&&(A.code||A.name)||"","getViewName"),s=i(A=>Object.assign({},t.get(A,"[0]",{}),{name:e(A)}),"getDbData"),a=i(A=>t.get(A,"[0].viewOn"),"getViewOn"),o=i((A,q=" ")=>A.split(` -`).map(B=>q+B).join(` -`),"tab"),c=i((A,q)=>Object.keys(A).map(t.toLower).includes(t.toLower(q)),"hasType"),u=i(A=>({...A,...t.omit(A==null?void 0:A.role,"properties")||{}}),"getSchemaOfAlterCollection"),l=i(A=>{var W;let q=r(A),B=(W=A.compMod)==null?void 0:W.keyspaceName;return G(q,B)},"getFullCollectionName"),p=i(A=>Object.entries(A).filter(([q,B])=>!t.isNil(B)).reduce((q,[B,W])=>({...q,[B]:W}),{}),"clean"),m=i(A=>A.every(q=>t.get(q,"isActivated",!0)),"checkAllKeysActivated"),d=i(A=>A.length?A.every(q=>!t.get(q,"isActivated",!0)):!1,"checkAllKeysDeactivated"),f=i((A,q)=>{let B=A.filter(ie=>t.get(ie,"isActivated",!0)).map(q),W=A.filter(ie=>!t.get(ie,"isActivated",!0)).map(q);return{activatedItems:B,deactivatedItems:W}},"divideIntoActivatedAndDeactivated"),h=i((A,{isActivated:q,isPartOfLine:B,inlineComment:W="--"})=>A?q!==!1?A:B?"/* "+A+" */":A.includes(` + `},Id=i(t=>(Object.entries(ho).find(([r,n])=>t===n)||[])[0]||"Custom query","getQueryName");go.exports={getQueryName:Id,...ho}});var _o=N((fT,yo)=>{"use strict";var vd=Gn(),Ve=null,Vt=null;yo.exports={initializeClient(t,e){Ve=t,Vt=e,Ve.on("error",r=>e.error(r))},isClientInitialized(){return!!Ve},releaseClient(){return Ve?new Promise(t=>{Ve.end(()=>{Ve=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let n=vd.getQueryName(t);Vt.info("Execute query",{queryName:n,params:e});let s=Date.now(),a=await Ve.query(t,e),o=Date.now()-s;Vt.info("Query executed",{queryName:n,params:e,duration:o,rowsCount:a.rowCount});let c=a.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(n){return n.query=t,n.params=e,Vt.error(n),null}}}});var So=N((hT,To)=>{"use strict";var Eo=i(t=>{let e=t.reduce((n,s)=>s.properties?{...n,[s.name]:{...s,...Eo(s.properties)}}:{...n,[s.name]:s},{}),r=Object.entries(e).filter(([n,s])=>s.required).map(([n])=>n);return{properties:e,required:r}},"getJsonSchema");To.exports={getJsonSchema:Eo}});var Vn=N((yT,Co)=>{"use strict";var ke=null,Od=i(t=>{ke=t.require("lodash")},"setDependencies"),St={column_default:"default",is_nullable:{keyword:"required",values:{YES:!1,NO:!0}},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:(t,e)=>e!==-1&&Fd(t.data_type)},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:"length",description:"description",domain_name:"domain_name"},Rd=i((t,e,r)=>{var n;return(n=St[e])!=null&&n.check?St[e].check(t,r)?r:"":ke.get(St,`${e}.values.${r}`,r)},"getColumnValue"),wd=i(t=>e=>ke.chain(e).toPairs().map(([r,n])=>{var s;return[((s=St[r])==null?void 0:s.keyword)||St[r],Rd(e,r,n)]}).filter(([r,n])=>r&&!ke.isNil(n)).fromPairs().thru(qd(t)).value(),"mapColumnData"),qd=i(t=>e=>({...e,...Dd(t,e)}),"setColumnType"),Dd=i((t,e)=>e.type==="ARRAY"?xd(t,e):e.type==="USER-DEFINED"?Ht(t,e.udt_name):e.domain_name?Ht(t,e.domain_name):Ht(t,e.type),"getType"),xd=i((t,e)=>({...Ht(t,e.udt_name.slice(1)),array_type:ke.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),Ht=i((t,e)=>{switch(e){case"bigint":case"bigserial":case"smallint":case"integer":case"numeric":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"int8":return{type:"numeric",mode:"bigint"};case"int2":return{type:"numeric",mode:"smallint"};case"int4":return{type:"numeric",mode:"integer"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return ke.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),Pd=i((t,e)=>{let r=ke.first(e)||{};return t.map(n=>{if(n.type!=="json")return n;let s=r[n.name],a=Ld(s),o=Md(a);return{...n,subtype:o}})},"setSubtypeFromSampledJsonValues"),Ld=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),Md=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),Fd=i(t=>ke.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");Co.exports={setDependencies:Od,mapColumnData:wd,setSubtypeFromSampledJsonValues:Pd}});var Ct=N((ET,Ao)=>{"use strict";var Ud=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],rt=null,kd=i(t=>{rt=t.require("lodash")},"setDependencies"),$d=i(t=>rt.chain(t).toPairs().reject(([e,r])=>rt.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),Bd=i(t=>e=>{var r;return(r=rt.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),Kd=i(t=>/\s|\W/.test(t)||rt.includes(Ud,rt.toUpper(t))?`"${t}"`:t,"wrapInQuotes");Ao.exports={clearEmptyPropertiesInObject:$d,setDependencies:kd,getColumnNameByPosition:Bd,wrapInQuotes:Kd}});var Io=N((ST,bo)=>{"use strict";var{getColumnNameByPosition:Gd}=Ct(),Hn=null,Vd=i(t=>{Hn=t.require("lodash")},"setDependencies"),No=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Hd=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";case"p":return"PARTIAL";default:return""}},"prepareMatch"),Wd=i((t,e,r,n)=>Hn.map(t,s=>({relationshipName:s.relationship_name,dbName:s.foreign_table_schema,parentCollection:s.foreign_table_name,parentField:s.foreign_columns,childDbName:r,childCollection:e,childField:Hn.map(s.table_columns_positions,Gd(n)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:No(s.relationship_on_delete),relationshipOnUpdate:No(s.relationship_on_update),relationshipMatch:Hd(s.relationship_match)}})),"prepareForeignKeys");bo.exports={setDependencies:Vd,prepareForeignKeys:Wd}});var Ro=N((AT,Oo)=>{"use strict";var Wt=null,Qd=i(t=>{Wt=t.require("lodash")},"setDependencies"),vo=i(t=>Wt.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:Yd(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),Yd=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),jd=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),zd=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),Xd=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Zd=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:vo(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:Wt.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:jd(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:Xd(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:zd(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),Jd=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:Wt.toLower(t.external_language),inputArgs:vo(e),body:t.routine_definition}),"mapProcedureData");Oo.exports={setDependencies:Qd,mapFunctionData:Zd,mapProcedureData:Jd}});var Po=N((bT,xo)=>{"use strict";var{clearEmptyPropertiesInObject:At,getColumnNameByPosition:Qt}=Ct(),V=null,ef=i(t=>{V=t.require("lodash")},"setDependencies"),qo=i((t,e)=>{if(!t&&!e)return null;let r=wo(t),n=wo(e==null?void 0:e.toast_options),s=r.fillfactor,a=r.parallel_workers,o=r.autovacuum_enabled,c=At({vacuum_index_cleanup:r.vacuum_index_cleanup,vacuum_truncate:r.vacuum_truncate,autovacuum_vacuum_threshold:r.autovacuum_vacuum_threshold,autovacuum_vacuum_scale_factor:r.autovacuum_vacuum_scale_factor,autovacuum_vacuum_insert_threshold:r.autovacuum_vacuum_insert_threshold,autovacuum_vacuum_insert_scale_factor:r.autovacuum_vacuum_insert_scale_factor,autovacuum_analyze_threshold:r.autovacuum_analyze_threshold,autovacuum_analyze_scale_factor:r.autovacuum_analyze_scale_factor,autovacuum_vacuum_cost_delay:r.autovacuum_vacuum_cost_delay,autovacuum_vacuum_cost_limit:r.autovacuum_vacuum_cost_limit,autovacuum_freeze_min_age:r.autovacuum_freeze_min_age,autovacuum_freeze_max_age:r.autovacuum_freeze_max_age,autovacuum_freeze_table_age:r.autovacuum_freeze_table_age,autovacuum_multixact_freeze_min_age:r.autovacuum_multixact_freeze_min_age,autovacuum_multixact_freeze_max_age:r.autovacuum_multixact_freeze_max_age,autovacuum_multixact_freeze_table_age:r.autovacuum_multixact_freeze_table_age,log_autovacuum_min_duration:r.log_autovacuum_min_duration}),u=r.user_catalog_table,l=n.autovacuum_enabled,d=At({toast_tuple_target:r.toast_tuple_target,toast_vacuum_index_cleanup:n.vacuum_index_cleanup,toast_vacuum_truncate:n.vacuum_truncate,toast_autovacuum_vacuum_threshold:n.autovacuum_vacuum_threshold,toast_autovacuum_vacuum_scale_factor:n.autovacuum_vacuum_scale_factor,toast_autovacuum_vacuum_insert_threshold:n.autovacuum_vacuum_insert_threshold,toast_autovacuum_vacuum_insert_scale_factor:n.autovacuum_vacuum_insert_scale_factor,toast_autovacuum_vacuum_cost_delay:n.autovacuum_vacuum_cost_delay,toast_autovacuum_vacuum_cost_limit:n.autovacuum_vacuum_cost_limit,toast_autovacuum_freeze_min_age:n.autovacuum_freeze_min_age,toast_autovacuum_freeze_max_age:n.autovacuum_freeze_max_age,toast_autovacuum_freeze_table_age:n.autovacuum_freeze_table_age,toast_autovacuum_multixact_freeze_min_age:n.autovacuum_multixact_freeze_min_age,toast_autovacuum_multixact_freeze_max_age:n.autovacuum_multixact_freeze_max_age,toast_autovacuum_multixact_freeze_table_age:n.autovacuum_multixact_freeze_table_age,toast_log_autovacuum_min_duration:n.log_autovacuum_min_duration}),p={fillfactor:s,parallel_workers:a,autovacuum_enabled:o,autovacuum:V.isEmpty(c)?null:c,toast_autovacuum_enabled:l,toast:V.isEmpty(d)?null:d,user_catalog_table:u};return At(p)},"prepareStorageParameters"),tf=i((t,e)=>{if(!t)return null;let r=rf(t),n=V.some(t.partition_attributes_positions,o=>o===0),s=n?"partitioning_expression":"compositePartitionKey",a=n?nf(t,e):V.map(t.partition_attributes_positions,Qt(e));return[{partitionMethod:r,partitionBy:n?"expression":"keys",[s]:a}]},"prepareTablePartition"),rf=i(t=>{switch(t.partition_method){case"h":return"HASH";case"l":return"LIST";case"r":return"RANGE";default:return""}},"getPartitionMethod"),nf=i((t,e)=>{let r=0,n=V.split(t.expressions,",");return V.chain(t.partition_attributes_positions).map(s=>{if(s===0){let a=n[r];return r++,a}return Qt(e)(s)}).join(",").value()},"getPartitionExpression"),Do=i(t=>V.split(t,"="),"splitByEqualitySymbol"),sf=i(t=>V.find(t,{type:"json"}),"checkHaveJsonTypes"),af=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),of=i((t,e,r)=>V.reduce(t,(n,s)=>{switch(s.constraint_type){case"c":return{...n,chkConstr:[...n.chkConstr,lf(s)]};case"p":return{...n,primaryKey:[...n.primaryKey,cf(s,e)]};case"u":return{...n,uniqueKey:[...n.uniqueKey,uf(s,e,r)]};default:return n}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),cf=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:V.map(t.constraint_keys,Qt(e)),indexStorageParameters:V.join(t.storage_parameters,","),indexTablespace:t.tablespace}),"getPrimaryKeyConstraint"),uf=i((t,e,r)=>{let n=V.find(r,a=>a.indexname===t.constraint_name),s=n!=null&&n.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"";return{constraintName:t.constraint_name,compositeUniqueKey:V.map(t.constraint_keys,Qt(e)),indexStorageParameters:V.join(t.storage_parameters,","),indexTablespace:t.tablespace,indexComment:t.description,...s&&{nullsDistinct:s}}},"getUniqueKeyConstraint"),lf=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,noInherit:t.no_inherit,constrDescription:t.description}),"getCheckConstraint"),pf=i(t=>V.map(t,e=>{let r=mf(e),n=V.slice(r,0,e.number_of_keys),s=V.chain(r).slice(e.number_of_keys).map(c=>V.pick(c,"name")).value(),a=e.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"",o={indxName:e.indexname,index_method:e.index_method,unique:e.index_unique??!1,index_tablespace_name:e.tablespace_name||"",index_storage_parameter:ff(e.storage_parameters),where:e.where_expression||"",include:s,columns:e.index_method==="btree"?n:V.map(n,c=>V.omit(c,"sortOrder","nullsOrder")),...a&&{nullsDistinct:a}};return At(o)}),"prepareTableIndexes"),mf=i(t=>V.chain(t.columns).map((e,r)=>{if(!e)return;let n=V.get(t,`ascendings.${r}`,!1)?"ASC":"DESC",s=df(V.get(t,`nulls_first.${r}`)),a=V.get(t,`opclasses.${r}`,""),o=V.get(t,`collations.${r}`,"");return{name:e,sortOrder:n,nullsOrder:s,opclass:a,collation:o}}).compact().value(),"mapIndexColumns"),df=i(t=>V.isNil(t)?"":t?"NULLS FIRST":"NULLS LAST","getNullsOrder"),ff=i(t=>{if(!t)return null;let e=V.fromPairs(V.map(t,n=>Do(n))),r={index_fillfactor:e.fillfactor,deduplicate_items:e.deduplicate_items,index_buffering:e.index_buffering,fastupdate:e.fastupdate,gin_pending_list_limit:e.gin_pending_list_limit,pages_per_range:e.pages_per_range,autosummarize:e.autosummarize};return At(r)},"getIndexStorageParameters"),hf=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",n=(t==null?void 0:t.relpersistence)==="u",s=qo(t==null?void 0:t.reloptions,e),a=t==null?void 0:t.spcname,o=t.partition_expr;return{temporary:r,unlogged:n,storage_parameter:s,table_tablespace_name:a,partitionBounds:o}},"prepareTableLevelData"),gf=i(t=>{switch(yf(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),yf=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),wo=i(t=>V.chain(t).map(Do).map(([e,r])=>[e,gf(r)]).fromPairs().value()||{},"prepareOptions"),_f=i((t,e)=>V.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");xo.exports={prepareStorageParameters:qo,prepareTablePartition:tf,setDependencies:ef,checkHaveJsonTypes:sf,prepareTableConstraints:of,prepareTableLevelData:hf,prepareTableIndexes:pf,getSampleDocSize:af,prepareTableInheritance:_f}});var Mo=N((vT,Lo)=>{"use strict";var{mapColumnData:Ef}=Vn(),Oe=null,Tf=i(t=>{Oe=t.require("lodash")},"setDependencies"),Sf=i((t,e)=>Oe.chain(t).map(r=>{switch(r.type){case"e":return Cf(r);case"r":return Af(r);case"c":return Nf(r);default:return null}}).compact().concat(Oe.map(e,If)).value(),"getUserDefinedTypes"),Cf=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Af=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Nf=i(t=>{let e=Oe.map(t.columns,Ef([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),bf=i(t=>t.type==="c","isTypeComposite"),If=i(t=>{var e;return{name:t.domain_name,type:"domain",underlyingType:Oe.flow(Of(t),Rf(t),wf(t),qf(t))(vf(t)),collation:t.collation_name||"",default:t.domain_default||"",required:(e=Oe.first(t.constraints))==null?void 0:e.not_null,checkConstraints:Oe.map(t.constraints,Df)}},"mapDomainType"),vf=i(t=>t.data_type==="USER-DEFINED"?t.udt_name:t.data_type,"getUnderlyingType"),Of=i(t=>e=>t.character_maximum_length?`${e}(${t.character_maximum_length})`:e,"setLength"),Rf=i(t=>e=>e!=="numeric"?e:Oe.isNumber(t.numeric_precision)&&Oe.isNumber(t.numeric_scale)?`${e}(${t.numeric_precision},${t.numeric_scale})`:Oe.isNumber(t.numeric_precision)?`${e}(${t.numeric_precision})`:e,"setPrecisionAndScale"),wf=i(t=>e=>t.interval_type?`${e} ${t.interval_type}`:e,"setIntervalType"),qf=i(t=>e=>Oe.isNumber(t.interval_precision)?`${e}(${t.interval_precision})`:e,"setIntervalPrecision"),Df=i(t=>({name:t.constraint_name,expression:t.expression}),"mapDomainConstraint");Lo.exports={setDependencies:Tf,getUserDefinedTypes:Sf,isTypeComposite:bf}});var Uo=N((RT,Fo)=>{"use strict";var{clearEmptyPropertiesInObject:xf,wrapInQuotes:Pf}=Ct(),Me=null,Lf=i(t=>{Me=t.require("lodash")},"setDependencies"),Wn=" (v)",Mf=i(t=>t==="VIEW","isViewByTableType"),Ff=i(t=>Me.endsWith(t,Wn),"isViewByName"),Uf=i(t=>t.slice(0,-Wn.length),"removeViewNameSuffix"),kf=i(t=>`${t}${Wn}`,"setViewSuffix"),$f=i((t,e,r={})=>{let n=Me.trim(e.view_definition||r.definition||"");return n?`CREATE VIEW ${Pf(t)} AS ${n}`:""},"generateCreateViewScript"),Bf=i((t,e,r)=>{let n={withCheckOption:t.check_option!=="NONE"||Me.isNil(t.check_option),checkTestingScope:Kf(t.check_option),viewOptions:Me.fromPairs(Me.map(e==null?void 0:e.view_options,Vf)),temporary:(e==null?void 0:e.persistence)==="t",recursive:Gf(t),description:e==null?void 0:e.description,triggers:r};return xf(n)},"prepareViewData"),Kf=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),Gf=i(t=>Me.startsWith(Me.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),Vf=i(t=>Me.split(t,"="),"splitByEqualitySymbol");Fo.exports={setDependencies:Lf,isViewByTableType:Mf,isViewByName:Ff,removeViewNameSuffix:Uf,generateCreateViewScript:$f,setViewSuffix:kf,prepareViewData:Bf}});var $o=N((qT,ko)=>{"use strict";var Yt=null,Hf=i(t=>{Yt=t.require("lodash")},"setDependencies"),Wf=i((t,e)=>Yt.chain(t).map(r=>({...r,...Yt.find(e,{trigger_name:r.trigger_name})||{}})).map(Qf).value(),"getTriggers"),Qf=i(t=>{var e;return{name:t.trigger_name,triggerDescription:t.description,triggerConstraint:t.constraint,triggerTable:`${t.event_object_schema}.${t.event_object_table}`,triggerReferencedTable:t.referenced_table_name?[t.referenced_table_schema,t.referenced_table_name]:[],triggerType:t.action_timing,triggerEvents:Yf(t),triggerUpdateColumns:(e=t.update_attributes)==null?void 0:e.filter(Boolean),triggerDeferrable:t.deferrable,triggerTimeConstraintCheck:t.deferred?"INITIALLY DEFERRED":"INITIALLY IMMEDIATE",triggerReferencing:!!t.action_reference_old_table||!!t.action_reference_new_table,triggerBeforeImageTransitionRelation:t.action_reference_old_table||"",triggerAfterImageTransitionRelation:t.action_reference_new_table||"",triggerEachRowStatement:t.action_orientation==="ROW"?"FOR EACH ROW":"FOR EACH STATEMENT",triggerCondition:t.action_condition,triggerFunction:jf(t.action_statement)}},"getTrigger"),Yf=i(t=>Yt.map(t.trigger_events,e=>({triggerEvent:e})),"getTriggerEvents"),jf=i(t=>{var e,r,n;return((n=(r=(e=/EXECUTE (?:FUNCTION|PROCEDURE)(?[\s\S]*)/.exec(t))==null?void 0:e.groups)==null?void 0:r.function)==null?void 0:n.trim())||""},"getFunctionFromTrigger");ko.exports={setDependencies:Hf,getTriggers:Wf}});var Go=N((xT,Ko)=>{"use strict";var zf=i((t,e)=>[Xf,Zf].reduce(({attributes:r,entityLevel:n},s)=>s(r,n),{attributes:t,entityLevel:e}),"reorganizeConstraints"),Xf=i((t,e)=>{var a,o,c;if(((c=(o=(a=e.primaryKey)==null?void 0:a[0])==null?void 0:o.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let n=e.primaryKey[0],s=n.compositePrimaryKey[0];return{attributes:Jf(t,s,n),entityLevel:nh(e)}},"reorganizePrimaryKeys"),Zf=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:n},s)=>{if(!(s.compositeUniqueKey.length===1))return{attributes:r,entityLevel:n};let o=s.compositeUniqueKey[0];return{attributes:th(r,o,s),entityLevel:sh(n,s)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Jf=i((t,e,r)=>t.map(n=>n.name!==e?n:eh(n,r)),"setAttributesPrimaryKeyData"),eh=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:Bo(e)}),"setPrimaryKeyData"),th=i((t,e,r)=>t.map(n=>n.name!==e?n:rh(n,r)),"setAttributesUniqueKeyData"),rh=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:Bo(e)}),"setUniqueKeyData"),Bo=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexComment:t.indexComment}],"getOptions"),nh=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),sh=i((t,e)=>{let r=t.uniqueKey.filter(n=>n.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Ko.exports={reorganizeConstraints:zf}});var jt=N((LT,Vo)=>{"use strict";var jn=class jn{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};i(jn,"Sequence");var Qn=jn,zn=class zn{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};i(zn,"SequenceDto");var Yn=zn;Vo.exports={Sequence:Qn,SequenceDto:Yn}});var Wo=N((kT,Ho)=>{"use strict";var{Sequence:FT,SequenceDto:UT}=jt(),ih=i(({sequence:t})=>t.column_name?[{entity:t.table_name,name:t.column_name}]:[],"getOwnedByColumn"),ah=i(({sequence:t})=>({sequenceName:t.sequence_name,increment:Number(t.increment),start:Number(t.start_value),dataType:t.data_type,maxValue:Number(t.maximum_value),minValue:Number(t.minimum_value),cache:Number(t.cache_size),temporary:t.rel_persistance==="t",unlogged:t.rel_persistance==="u",cycle:t.cycle_option==="YES",ownedByColumn:ih({sequence:t}),ownedByNone:!t.column_name}),"mapSequenceData");Ho.exports={mapSequenceData:ah}});var Jn=N((BT,jo)=>{"use strict";var{createClient:oh}=mo(),U=_o(),{getJsonSchema:Qo}=So(),{setDependencies:ch,mapColumnData:uh,setSubtypeFromSampledJsonValues:lh}=Vn(),{setDependencies:ph,clearEmptyPropertiesInObject:Yo}=Ct(),{setDependencies:mh,prepareForeignKeys:dh}=Io(),{setDependencies:fh,mapFunctionData:hh,mapProcedureData:gh}=Ro(),{setDependencies:yh,prepareTablePartition:_h,checkHaveJsonTypes:Eh,prepareTableConstraints:Th,getSampleDocSize:Sh,prepareTableLevelData:Ch,prepareTableIndexes:Ah,prepareTableInheritance:Nh}=Po(),{setDependencies:bh,getUserDefinedTypes:Ih,isTypeComposite:vh}=Mo(),{setDependencies:Oh,isViewByTableType:Rh,isViewByName:wh,removeViewNameSuffix:qh,generateCreateViewScript:Dh,setViewSuffix:xh,prepareViewData:Ph}=Uo(),{setDependencies:Lh,getTriggers:Mh}=$o(),k=Gn(),{reorganizeConstraints:Fh}=Go(),{mapSequenceData:Uh}=Wo(),Xn=!1,J=null,he=null,Zn=14;jo.exports={setDependencies(t){J=t.require("lodash"),ph(t),yh(t),ch(t),mh(t),Oh(t),fh(t),bh(t),Lh(t)},async connect(t,e,r){U.isClientInitialized()&&await this.disconnect(e);let{client:n,isSshTunnel:s}=await oh(t,e,r);U.initializeClient(n,r),Xn=s,he=r,Zn=await this._getServerVersion()},async disconnect(t){Xn&&(Xn=!1,await t.closeConsumer()),await U.releaseClient()},pingDb(){return U.query(k.PING)},applyScript(t){return U.query(t)},async getDatabaseNames(){return J.map(await U.query(k.GET_DATABASES),"database_name")},async logVersion(){let t=await U.queryTolerant(k.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved";he.info(`PostgreSQL version: ${e}`)},async getAllSchemasNames(){return(await U.query(k.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!kh(e))},async getTablesNames(t){let e=await U.query(k.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:n})=>!J.includes(r,n)).map(({table_name:n,table_type:s})=>Rh(s)?xh(n):n)},async getDbLevelData(){var n,s,a;he.progress("Get database data");let t=(n=await U.queryTolerant(k.GET_DB_NAME,[],!0))==null?void 0:n.current_database,e=(s=await U.queryTolerant(k.GET_DB_ENCODING,[],!0))==null?void 0:s.server_encoding,r=(a=await U.queryTolerant(k.GET_DB_COLLATE_NAME,[],!0))==null?void 0:a.default_collate_name;return Yo({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r,n=!1,s=!1){let a=await this._retrieveUserDefinedTypes(t),o=await U.queryTolerant(k.GET_NAMESPACE_OID,[t],!0),c=o==null?void 0:o.oid,u=n?await U.queryTolerant(k.GET_PARTITIONS,[c]):[],[l,d]=J.partition(e,wh),p=d.flatMap(h=>[{tableName:h},...J.filter(u,{parent_name:h}).map(({child_name:T,is_parent_partitioned:_})=>({isParentPartitioned:_,tableName:T}))]),m=await nt(J.uniq(p),J.bind(this._retrieveSingleTableData,this,r,c,t,a,s));return{views:await nt(l,J.bind(this._retrieveSingleViewData,this,c,t,s)),tables:m,modelDefinitions:Qo(a)}},async retrieveSchemaLevelData(t,e){var p;if(e)return he.info("Functions and procedures ignored"),{functions:[],procedures:[]};he.progress("Get Functions and Procedures",t);let r=(p=await U.queryTolerant(k.GET_NAMESPACE_OID,[t],!0))==null?void 0:p.oid,n=await U.queryTolerant(k.GET_FUNCTIONS_WITH_PROCEDURES,[t]),s=await U.queryTolerant(Bh(Zn),[r]),[a,o]=J.partition(J.filter(n,"routine_type"),{routine_type:"FUNCTION"}),c=await nt(a,async m=>{let f=await U.queryTolerant(k.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[m.specific_name]),h=J.find(s,{function_name:m.name});return hh(m,f,h)}),u=await nt(o,async m=>{let f=await U.queryTolerant(k.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[m.specific_name]),h=J.find(s,{function_name:m.name});return gh(m,f,h)}),d=(await U.queryTolerant(k.GET_SEQUENCES,[t])).map(m=>Uh({sequence:m}));return{functions:c,procedures:u,sequences:d}},async _retrieveUserDefinedTypes(t){he.progress("Get User-Defined Types",t);let e=await U.queryTolerant(k.GET_USER_DEFINED_TYPES,[t]),r=await U.queryTolerant(k.GET_DOMAIN_TYPES,[t]),n=await nt(e,async a=>vh(a)?{...a,columns:await U.queryTolerant(k.GET_COMPOSITE_TYPE_COLUMNS,[a.pg_class_oid])}:a),s=await nt(r,async a=>({...a,constraints:await U.queryTolerant(k.GET_DOMAIN_TYPES_CONSTRAINTS,[a.domain_name,t])}));return Ih(n,s)},async _retrieveSingleTableData(t,e,r,n,s,{tableName:a,isParentPartitioned:o}){var Ne;he.progress("Get table data",r,a);let c=await U.queryTolerant(k.GET_TABLE_LEVEL_DATA,[a,e],!0),u=c==null?void 0:c.oid,l=await U.queryTolerant(k.GET_TABLE_TOAST_OPTIONS,[a,e],!0),d=await U.queryTolerant(k.GET_TABLE_PARTITION_DATA,[u],!0),p=await this._getTableColumns(a,r,u),m=await U.queryTolerant(k.GET_DESCRIPTION_BY_OID,[u],!0),f=await U.queryTolerant(k.GET_INHERITS_PARENT_TABLE_NAME,[u]),h=await U.queryTolerant(k.GET_TABLE_CONSTRAINTS,[u]),T=await U.queryTolerant($h(Zn),[u]),_=await U.queryTolerant(k.GET_TABLE_FOREIGN_KEYS,[u]),y=await this._getTriggers(r,a,e,u,s);he.info("Table data retrieved",{schemaName:r,tableName:a,columnTypes:p.map(C=>C.data_type)});let A=_h(d,p),S=Ch(c,l),I=Kh(m),v=Nh(r,f),w=Th(h,p,T),$=Ah(T),b=dh(_,a,r,p),q={partitioning:A,description:I,triggers:y,Indxs:$,...S,...w,...o?{partitionOf:(Ne=J.first(v))==null?void 0:Ne.parentTable}:{inherits:v}},G=Yo(q),P=p.map(uh(n)),z=Eh(P),Ae=[];z&&(Ae=await this._getDocuments(r,a,P,t),P=lh(P,Ae));let{attributes:le,entityLevel:F}=Fh(P,G);return{name:a,entityLevel:F,jsonSchema:Qo(le),documents:Ae,relationships:b}},async _getTriggers(t,e,r,n,s){if(s)return he.info("Triggers ignored"),[];let a=await U.queryTolerant(k.GET_TRIGGERS,[t,e]),o=await U.queryTolerant(k.GET_TRIGGERS_ADDITIONAL_DATA,[r,n]);return Mh(a,o)},async _getTableColumns(t,e,r){he.progress("Get columns",e,t);let n=await U.query(k.GET_TABLE_COLUMNS,[t,e]),s=await U.queryTolerant(k.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return J.map(n,a=>({...a,...J.find(s,{name:a.column_name})||{}}))},async _getDocuments(t,e,r,n){var d;he.progress("Sampling table",t,e);let s=`${t}.${e}`,a=((d=await U.queryTolerant(k.GET_ROWS_COUNT(s),[],!0))==null?void 0:d.quantity)||0,o=Sh(a,n),c=r.filter(({type:p})=>J.includes(["json","jsonb"],p)),u=J.map(c,"name").join(", "),l=await U.queryTolerant(k.GET_SAMPLED_DATA_SIZE(s,u),[o],!0);return he.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:l==null?void 0:l._hackolade_tmp_sampling_tbl_size}),await U.queryTolerant(k.GET_SAMPLED_DATA(s,u),[o])},async _retrieveSingleViewData(t,e,r,n){he.progress("Get view data",e,n),n=qh(n);let s=await U.query(k.GET_VIEW_DATA,[n,e],!0),a=!s.view_definition&&await U.queryTolerant(k.GET_VIEW_SELECT_STMT_FALLBACK,[n,e],!0),o=await U.queryTolerant(k.GET_VIEW_OPTIONS,[n,t],!0),c=await this._getTriggers(e,n,t,o==null?void 0:o.oid,r),u=Dh(n,s,a),l=Ph(s,o,c);return u?{name:n,data:l,ddl:{script:u,type:"postgres"}}:(he.info("View select statement was not retrieved",{schemaName:e,viewName:n}),{name:n,data:l,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await U.queryTolerant(k.GET_VERSION_AS_NUM,[],!0),e=J.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var kh=i(t=>!!(J.startsWith(t,"pg_")||J.includes(["information_schema"],t)),"isSystemSchema"),$h=i(t=>t===10?k.GET_TABLE_INDEXES_V_10:t>15?k.GET_TABLE_INDEXES_V_15:k.GET_TABLE_INDEXES,"getGetIndexesQuery"),Bh=i(t=>t===10?k.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:k.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),Kh=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),nt=i((t,e)=>Promise.all(J.map(t,e)),"mapPromises")});var Xo=N((GT,zo)=>{"use strict";var{createLogger:zt}=pr(),te=Jn();zo.exports={async disconnect(t,e,r,n){let s=n.require("@hackolade/ssh-service");await te.disconnect(s),r()},async testConnection(t,e,r,n){let s=n.require("@hackolade/ssh-service");try{es("Test connection",t,e);let a=zt({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});te.setDependencies(n),await te.connect(t,s,a),await te.pingDb(),await te.logVersion(),r()}catch(a){e.log("error",He(a),"Test connection instance log"),r(He(a))}finally{await te.disconnect(s)}},async getDatabases(t,e,r,n){let s=n.require("@hackolade/ssh-service");try{es("Get databases",t,e);let a=zt({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});te.setDependencies(n),await te.connect(t,s,a),await te.logVersion();let o=await te.getDatabaseNames();return e.log("info",o,"All databases list",t.hiddenKeys),r(null,o)}catch(a){return e.log("error",a),r(He(a))}},getDocumentKinds:function(t,e,r){r(null,[])},async getDbCollectionsNames(t,e,r,n){let s=n.require("@hackolade/ssh-service");try{es("Get DB table names",t,e);let a=zt({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});te.setDependencies(n),await te.connect(t,s,a),await te.logVersion();let c=await(await te.getAllSchemasNames()).reduce(async(u,l)=>{let d=await u;try{let p=await te.getTablesNames(l);return d.concat({dbName:l,dbCollections:p,isEmpty:p.length===0})}catch(p){return a.info(`Error reading database "${l}"`),a.error(p),d.concat({dbName:l,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,c)}catch(a){e.log("error",He(a),"Get DB collections names"),r(He(a)),await te.disconnect(s)}},async getDbCollectionsData(t,e,r,n){let s=n.require("@hackolade/ssh-service");try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let a=zt({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});a.progress("Start reverse engineering...");let o=t.collectionData.collections,c=t.collectionData.dataBaseNames,u=await te.getDbLevelData(),{packages:l,relationships:d}=await Promise.all(c.map(async p=>{let{tables:m,views:f,modelDefinitions:h}=await te.retrieveEntitiesData(p,o[p],t.recordSamplingSettings,t.includePartitions,t.ignoreUdfUdpTriggers),{functions:T,procedures:_,triggers:y,sequences:A}=await te.retrieveSchemaLevelData(p,t.ignoreUdfUdpTriggers);return a.progress("Schema data fetched successfully",p),{schemaName:p,tables:m,views:f,functions:T,procedures:_,modelDefinitions:h,triggers:y,sequences:A}})).then(p=>{let m=p.flatMap(({tables:h})=>h.map(T=>T.relationships)).flat();return{packages:p.flatMap(({schemaName:h,tables:T,views:_,functions:y,procedures:A,triggers:S,modelDefinitions:I,sequences:v})=>{let w={UDFs:y,Procedures:A,triggers:S,sequences:v},$=T.map(b=>({dbName:h,collectionName:b.name,documents:b.documents,views:[],emptyBucket:!1,entityLevel:b.entityLevel,validation:{jsonSchema:b.jsonSchema},bucketInfo:w,modelDefinitions:I})).sort(b=>n.require("lodash").isEmpty(b.entityLevel.inherits)?-1:1);if(_!=null&&_.length){let b={dbName:h,views:_,emptyBucket:!1};return[...$,b]}return $}),relationships:m}}).then(({packages:p,relationships:m})=>({packages:Gh(p),relationships:m}));a.info("The data is processed and sent to the application",{packagesLength:l==null?void 0:l.length,relationshipsLength:d==null?void 0:d.length}),r(null,l,u,d)}catch(a){e.log("error",He(a),"Retrieve tables data"),r(He(a))}finally{await te.disconnect(s)}}};var He=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),es=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),Gh=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages")});var Jo=N((HT,Zo)=>{"use strict";var Xt=Jn(),Vh=i(async(t,e,r)=>{try{let n=r.require("@hackolade/ssh-service");Xt.setDependencies(r),await Xt.connect(t,n,e),await Xt.logVersion(),await Xt.applyScript(Hh(t.script))}catch(n){throw e.error(n),Wh(n)}},"applyToInstance"),Hh=i(t=>{let e=/CREATE DATABASE[^;]*;/gi;return t.replace(e,"")},"removeCreateDbScript"),Wh=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");Zo.exports={applyToInstance:Vh}});var re=N((QT,ec)=>{"use strict";var ns=class ns{script;isDropScript};i(ns,"ModificationScript");var ts=ns,ss=class ss{isActivated;scripts;static getInstances(e,r,n){return(e||[]).filter(Boolean).map(s=>({isActivated:r,scripts:[{isDropScript:n,script:s}]}))}static getInstance(e,r,n){var s;if((s=e==null?void 0:e.filter(Boolean))!=null&&s.length)return{isActivated:r,scripts:e.filter(Boolean).map(a=>({isDropScript:n,script:a}))}}static getDropAndRecreateInstance(e,r,n){let s=[];if(e&&s.push({isDropScript:!0,script:e}),r&&s.push({isDropScript:!1,script:r}),!!(s!=null&&s.length))return{isActivated:n,scripts:s}}};i(ss,"AlterScriptDto");var rs=ss;ec.exports={ModificationScript:ts,AlterScriptDto:rs}});var ps=N((jT,tc)=>{"use strict";var cs=class cs{sortOrder;nullsOrder;isActivated;keyId;collation;opclass};i(cs,"AlterIndexColumnDto");var is=cs,us=class us{keyId};i(us,"AlterIndexIncludeColumnDto");var as=us,ls=class ls{id;isActivated;index_method;ifNotExist;only;index_tablespace_name;indxName;columns;include;index_storage_parameter};i(ls,"AlterIndexDto");var os=ls;tc.exports={AlterIndexDto:os,AlterIndexColumnDto:is,AlterIndexIncludeColumnDto:as}});var $e=N((ZT,rc)=>{"use strict";var{AlterIndexDto:XT}=ps(),Es=class Es{id;constraintName;indexStorageParameters;indexTablespace;indexInclude};i(Es,"AlterCollectionColumnKeyOptionDto");var Nt=Es,Ts=class Ts{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};i(Ts,"AlterCollectionColumnDto");var ms=Ts,Ss=class Ss extends Nt{compositePrimaryKey};i(Ss,"AlterCollectionRoleCompModPKDto");var ds=Ss,Cs=class Cs extends Nt{compositeUniqueKey};i(Cs,"AlterCollectionRoleCompModUniqueKeyDto");var fs=Cs,As=class As{new;old};i(As,"AlterCollectionRoleCompModPrimaryKey");var hs=As,Ns=class Ns{new;old};i(Ns,"AlterCollectionRoleCompModUniqueKey");var gs=Ns,bs=class bs{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;table_tablespace_name;bucketId;compMod;name;roleType;patternProperties};i(bs,"AlterCollectionRoleDto");var ys=bs,Is=class Is{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(Is,"AlterCollectionDto");var _s=Is;rc.exports={AlterCollectionDto:_s,AlterCollectionRoleDto:ys,AlterCollectionColumnDto:ms,AlterCollectionColumnKeyOptionDto:Nt,AlterCollectionRoleCompModPrimaryKey:hs,AlterCollectionRoleCompModPKDto:ds,AlterCollectionRoleCompModUniqueKeyDto:fs,AlterCollectionRoleCompModUniqueKey:gs}});var sc=N((eS,nc)=>{"use strict";var Qh=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),Yh=Object.values(Qh);nc.exports={ReservedWordsAsArray:Yh}});var L=N((nS,ic)=>{"use strict";var{AlterCollectionDto:tS,AlterCollectionRoleDto:rS}=$e(),{ReservedWordsAsArray:jh}=sc(),zh=/\t|\n|'|\f|\r/gm;ic.exports=t=>{let e=i(C=>t.get(C,"[0].code")||t.get(C,"[0].name",""),"getDbName"),r=i(C=>C&&(C.code||C.collectionName)||"","getEntityName"),n=i(C=>C&&(C.code||C.name)||"","getViewName"),s=i(C=>Object.assign({},t.get(C,"[0]",{}),{name:e(C)}),"getDbData"),a=i(C=>t.get(C,"[0].viewOn"),"getViewOn"),o=i((C,D=" ")=>C.split(` +`).map(B=>D+B).join(` +`),"tab"),c=i((C,D)=>Object.keys(C).map(t.toLower).includes(t.toLower(D)),"hasType"),u=i(C=>({...C,...t.omit(C==null?void 0:C.role,"properties")||{}}),"getSchemaOfAlterCollection"),l=i(C=>{var H;let D=r(C),B=(H=C.compMod)==null?void 0:H.keyspaceName;return G(D,B)},"getFullCollectionName"),d=i(C=>Object.entries(C).filter(([D,B])=>!t.isNil(B)).reduce((D,[B,H])=>({...D,[B]:H}),{}),"clean"),p=i(C=>C.every(D=>t.get(D,"isActivated",!0)),"checkAllKeysActivated"),m=i(C=>C.length?C.every(D=>!t.get(D,"isActivated",!0)):!1,"checkAllKeysDeactivated"),f=i((C,D)=>{let B=C.filter(se=>t.get(se,"isActivated",!0)).map(D),H=C.filter(se=>!t.get(se,"isActivated",!0)).map(D);return{activatedItems:B,deactivatedItems:H}},"divideIntoActivatedAndDeactivated"),h=i((C,{isActivated:D,isPartOfLine:B,inlineComment:H="--"})=>C?D!==!1?C:B?"/* "+C+" */":C.includes(` `)?`/* -`+A+` */ -`:W+" "+A:"","commentIfDeactivated"),T=i((A,q="'",B="'")=>{let W=A[0];return A[A.length-1]===q&&W===B?A:`${q}${A}${B}`},"wrap"),_=i((A,q)=>q.some(B=>(A==null?void 0:A.oldField[B])!==(A==null?void 0:A.newField[B])),"checkFieldPropertiesChanged"),y=i(A=>{let q={...A,...t.omit(A==null?void 0:A.role,"properties")||{}},B=r(q),W=N({collection:q});return G(B,W)},"getFullTableName"),N=i(({collection:A})=>{var q;return(q=A.compMod)==null?void 0:q.keyspaceName},"getSchemaNameFromCollection"),S=i((A,q)=>{let{wrapInQuotes:B}=L()(t);return`${y(A)}.${B(q)}`},"getFullColumnName"),b=i(A=>{var ie;let q={...A,...t.omit(A==null?void 0:A.role,"properties")||{}},B=n(q),W=(ie=q.compMod)==null?void 0:ie.keyspaceName;return G(B,W)},"getFullViewName"),I=i(A=>A.code||A.name,"getUdtName"),R=i((A="")=>{let q=A.match(/\d+/);return Number(t.get(q,[0],0))},"getDbVersion"),M=i((A="")=>A.replace(jy,q=>`\\${q}`),"prepareComment"),v=i(A=>`E'${M(JSON.stringify(A)).slice(1,-1)}'`,"wrapComment"),D=i(A=>t.map(A,q=>{let B=q.defaultExpression?`DEFAULT ${q.defaultExpression}`:"";return t.trim(`${q.argumentMode} ${q.argumentName||""} ${q.argumentType} ${B}`)}).join(", "),"getFunctionArguments"),G=i((A,q)=>q?`${P(q)}.${P(A)}`:P(A),"getNamePrefixedWithSchemaName"),P=i(A=>/\s|\W/.test(A)||t.includes(Yy,t.toUpper(A))?`"${A}"`:A,"wrapInQuotes"),X=i(({name:A})=>P(A),"columnMapToString"),ve=i((A,q,B,W=X)=>{var qe;let ie=f(A,W),Pe=(qe=ie==null?void 0:ie.deactivatedItems)!=null&&qe.length?h(ie.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!q&&B?" ("+ie.activatedItems.join(", ")+Pe+")":" ("+A.map(W).join(", ")+")"},"getColumnsList"),me=i(A=>A?A.alias?`${P(A.name)} as ${P(A.alias)}`:P(A.name):"","getKeyWithAlias");return{getDbName:e,getDbData:s,getEntityName:r,getViewName:n,getViewOn:a,tab:o,hasType:c,clean:p,checkAllKeysActivated:m,checkAllKeysDeactivated:d,divideIntoActivatedAndDeactivated:f,commentIfDeactivated:h,wrap:T,checkFieldPropertiesChanged:_,getFullTableName:y,getFullColumnName:S,getFullViewName:b,getUdtName:I,getDbVersion:R,wrapComment:v,getFunctionArguments:D,getNamePrefixedWithSchemaName:G,wrapInQuotes:P,getColumnsList:ve,getViewData:i(A=>Array.isArray(A)?A.reduce((q,B)=>{if(!B.tableName)return q.columns.push(me(B)),q;let W=`${P(B.dbName)}.${P(B.tableName)}`;return q.tables.includes(W)||q.tables.push(W),q.columns.push({statement:`${W}.${me(B)}`,isActivated:B.isActivated}),q},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:u,getFullCollectionName:l,getSchemaNameFromCollection:N,getGroupItemsByCompMode:i(({newItems:A=[],oldItems:q=[]})=>{let B=A.filter(Pe=>!q.some(qe=>qe.id===Pe.id)),W=[],ie=[];return q.forEach(Pe=>{let qe=A.find(Sr=>Sr.id===Pe.id);qe?t.isEqual(qe,Pe)||ie.push(qe):W.push(Pe)}),{added:B,removed:W,modified:ie}},"getGroupItemsByCompMode")}}});var tu=C((_A,eu)=>{var{AlterScriptDto:Zc}=ne(),Jc=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),zy=i((t,e)=>r=>{let{wrapComment:n,wrapInQuotes:s}=L()(t),a=Jc(r);if(a.new&&a.new!==a.old){let o=n(a.new),c=s(r.role.name),u=e.updateSchemaComment(c,o);return Zc.getInstance([u],!0,!1)}},"getUpsertCommentsScriptDto"),Xy=i((t,e)=>r=>{let{wrapInQuotes:n}=L()(t),s=Jc(r);if(s.old&&!s.new){let a=n(r.role.name),o=e.dropSchemaComment(a);return Zc.getInstance([o],!0,!0)}},"getDropCommentsScriptDto"),Zy=i((t,e)=>r=>{let n=zy(t,e)(r),s=Xy(t,e)(r);return[n,s].filter(Boolean)},"getModifySchemaCommentsScriptDtos");eu.exports={getModifySchemaCommentsScriptDtos:Zy}});var nu=C((TA,ru)=>{ru.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var iu=C((SA,su)=>{su.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var ou=C((CA,au)=>{au.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${locale}${collate}${characterClassification}${tablespace};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${noInherit}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}${tablespace}${deferrable}${deferrableConstraintCheckTime}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON${only} ${tableName}${using}${keys}${nullsDistinct}${options};\n",dropIndex:"DROP INDEX IF EXISTS ${indexName};\n",alterIndexRename:"ALTER INDEX IF EXISTS ${oldIndexName} RENAME TO ${newIndexName};\n",alterIndexTablespace:"ALTER INDEX IF EXISTS ${indexName} SET TABLESPACE ${tablespaceName};\n",alterIndexStorageParams:`ALTER INDEX IF EXISTS \${indexName} SET ( +`+C+` */ +`:H+" "+C:"","commentIfDeactivated"),T=i((C,D="'",B="'")=>{let H=C[0];return C[C.length-1]===D&&H===B?C:`${D}${C}${B}`},"wrap"),_=i((C,D)=>D.some(B=>(C==null?void 0:C.oldField[B])!==(C==null?void 0:C.newField[B])),"checkFieldPropertiesChanged"),y=i(C=>{let D={...C,...t.omit(C==null?void 0:C.role,"properties")||{}},B=r(D),H=A({collection:D});return G(B,H)},"getFullTableName"),A=i(({collection:C})=>{var D;return(D=C.compMod)==null?void 0:D.keyspaceName},"getSchemaNameFromCollection"),S=i((C,D)=>`${y(C)}.${P(D)}`,"getFullColumnName"),I=i(C=>{var se;let D={...C,...t.omit(C==null?void 0:C.role,"properties")||{}},B=n(D),H=(se=D.compMod)==null?void 0:se.keyspaceName;return G(B,H)},"getFullViewName"),v=i(C=>C.code||C.name,"getUdtName"),w=i((C="")=>{let D=C.match(/\d+/);return Number(t.get(D,[0],0))},"getDbVersion"),$=i((C="")=>C.replace(zh,D=>`\\${D}`),"prepareComment"),b=i(C=>`E'${$(JSON.stringify(C)).slice(1,-1)}'`,"wrapComment"),q=i(C=>t.map(C,D=>{let B=D.defaultExpression?`DEFAULT ${D.defaultExpression}`:"";return t.trim(`${D.argumentMode} ${D.argumentName||""} ${D.argumentType} ${B}`)}).join(", "),"getFunctionArguments"),G=i((C,D)=>D?`${P(D)}.${P(C)}`:P(C),"getNamePrefixedWithSchemaName"),P=i(C=>/\s|\W/.test(C)||t.includes(jh,t.toUpper(C))?`"${C}"`:C,"wrapInQuotes"),z=i(({name:C})=>P(C),"columnMapToString"),Ae=i((C,D,B,H=z)=>{var Re;let se=f(C,H),qe=(Re=se==null?void 0:se.deactivatedItems)!=null&&Re.length?h(se.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!D&&B?" ("+se.activatedItems.join(", ")+qe+")":" ("+C.map(H).join(", ")+")"},"getColumnsList"),le=i(C=>C?C.alias?`${P(C.name)} as ${P(C.alias)}`:P(C.name):"","getKeyWithAlias");return{getDbName:e,getDbData:s,getEntityName:r,getViewName:n,getViewOn:a,tab:o,hasType:c,clean:d,checkAllKeysActivated:p,checkAllKeysDeactivated:m,divideIntoActivatedAndDeactivated:f,commentIfDeactivated:h,wrap:T,checkFieldPropertiesChanged:_,getFullTableName:y,getFullColumnName:S,getFullViewName:I,getUdtName:v,getDbVersion:w,wrapComment:b,getFunctionArguments:q,getNamePrefixedWithSchemaName:G,wrapInQuotes:P,getColumnsList:Ae,getViewData:i(C=>Array.isArray(C)?C.reduce((D,B)=>{if(!B.tableName)return D.columns.push(le(B)),D;let H=`${P(B.dbName)}.${P(B.tableName)}`;return D.tables.includes(H)||D.tables.push(H),D.columns.push({statement:`${H}.${le(B)}`,isActivated:B.isActivated}),D},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:u,getFullCollectionName:l,getSchemaNameFromCollection:A,getGroupItemsByCompMode:i(({newItems:C=[],oldItems:D=[]})=>{let B=C.filter(qe=>!D.some(Re=>Re.id===qe.id)),H=[],se=[];return D.forEach(qe=>{let Re=C.find(cr=>cr.id===qe.id);Re?t.isEqual(Re,qe)||se.push(Re):H.push(qe)}),{added:B,removed:H,modified:se}},"getGroupItemsByCompMode")}}});var uc=N((iS,cc)=>{"use strict";var{AlterScriptDto:ac}=re(),oc=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),Xh=i((t,e)=>r=>{let{wrapComment:n,wrapInQuotes:s}=L()(t),a=oc(r);if(a.new&&a.new!==a.old){let o=n(a.new),c=s(r.role.name),u=e.updateSchemaComment(c,o);return ac.getInstance([u],!0,!1)}},"getUpsertCommentsScriptDto"),Zh=i((t,e)=>r=>{let{wrapInQuotes:n}=L()(t),s=oc(r);if(s.old&&!s.new){let a=n(r.role.name),o=e.dropSchemaComment(a);return ac.getInstance([o],!0,!0)}},"getDropCommentsScriptDto"),Jh=i((t,e)=>r=>{let n=Xh(t,e)(r),s=Zh(t,e)(r);return[n,s].filter(Boolean)},"getModifySchemaCommentsScriptDtos");cc.exports={getModifySchemaCommentsScriptDtos:Jh}});var pc=N((oS,lc)=>{"use strict";lc.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var dc=N((cS,mc)=>{"use strict";mc.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var hc=N((uS,fc)=>{"use strict";fc.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${locale}${collate}${characterClassification}${tablespace};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${noInherit}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}${tablespace}${deferrable}${deferrableConstraintCheckTime}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON${only} ${tableName}${using}${keys}${nullsDistinct}${options};\n",dropIndex:"DROP INDEX IF EXISTS ${indexName};\n",alterIndexRename:"ALTER INDEX IF EXISTS ${oldIndexName} RENAME TO ${newIndexName};\n",alterIndexTablespace:"ALTER INDEX IF EXISTS ${indexName} SET TABLESPACE ${tablespaceName};\n",alterIndexStorageParams:`ALTER INDEX IF EXISTS \${indexName} SET ( \${options} ); `,reindexIndex:"REINDEX INDEX ${indexName};\n",createView:"CREATE${orReplace}${temporary} VIEW ${name}${withOptions}\nAS ${selectStatement}${checkOption};\n\n${comment}\n",viewSelectStatement:"SELECT ${keys}\n FROM ${tableName}",dropView:"DROP VIEW IF EXISTS ${viewName};",createFunction:"CREATE${orReplace} FUNCTION ${name}\n (${parameters})\n RETURNS ${returnType}\n LANGUAGE ${language}\n${properties}AS $BODY$\n${definition}\n$BODY$;\n",createProcedure:"CREATE${orReplace} PROCEDURE ${name} (${parameters})\n LANGUAGE ${language}\nAS $BODY$\n${body}\n$BODY$;\n",createCompositeType:`CREATE TYPE \${name} AS ( \${columnDefinitions} ); -\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}",createTrigger:"CREATE${orReplace}${constraint} TRIGGER ${name} ${actionTiming} ${events}\n ON ${tableName}\n${options} EXECUTE ${functionKey} ${functionName};\n",createSequence:"CREATE${sequenceType} SEQUENCE${ifNotExists} ${name}${options};\n",dropSequence:"DROP SEQUENCE IF EXISTS ${name};\n",renameSequence:"ALTER SEQUENCE IF EXISTS ${name} RENAME TO ${newName};\n",setSequenceType:"ALTER SEQUENCE IF EXISTS ${name} SET ${sequenceType};\n",alterSequence:"ALTER SEQUENCE IF EXISTS ${name}${options};\n"}});var lu=C((AA,uu)=>{var cu=i((t="")=>new RegExp("\\$\\{(.*?)\\}",t),"template"),Jy=i(t=>t.match(cu("gi"))||[],"getAllTemplates"),e_=i(t=>(t.match(cu("i"))||[])[1],"parseTemplate"),t_=i((t,e)=>Jy(t).reduce((r,n)=>{let s=e_(n);return r.replace(n,()=>e[s]||e[s]===0?e[s]:"")},t),"assignTemplates");uu.exports=t_});var mu=C((bA,pu)=>{pu.exports=({_:t,commentIfDeactivated:e,checkAllKeysDeactivated:r,assignTemplates:n,wrapInQuotes:s,getColumnsList:a})=>({generateConstraintsString:i((d,f)=>{var y,N;let h=e(((d==null?void 0:d.deactivatedItems)||[]).join(`, - `),{isActivated:!f,isPartOfLine:!0}),T=(y=d==null?void 0:d.activatedItems)!=null&&y.length?`, - `+d.activatedItems.join(`, - `):"",_=(N=d==null?void 0:d.deactivatedItems)!=null&&N.length?` - `+h:"";return T+_},"generateConstraintsString"),foreignKeysToString:i(d=>{if(Array.isArray(d)){let f=d.filter(_=>t.get(_,"isActivated",!0)).map(_=>s(t.trim(_.name))),h=d.filter(_=>!t.get(_,"isActivated",!0)).map(_=>s(t.trim(_.name))),T=h.length?e(h,{isActivated:!1,isPartOfLine:!0}):"";return f.join(", ")+T}return d},"foreignKeysToString"),foreignActiveKeysToString:i(d=>d.map(f=>t.trim(f.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:i((d,f)=>h=>{let T=s(t.trim(h.name)),_=r(h.columns||[]),y=t.isEmpty(h.columns)?"":a(h.columns,_,f),N=h.include.length?` INCLUDE${a(h.include,_,f)}`:"",S=h.storageParameters?` WITH (${h.storageParameters})`:"",b=h.tablespace?` USING INDEX TABLESPACE ${s(h.tablespace)}`:"",I=h!=null&&h.deferrable?` ${h.deferrable}`:"",R=(h==null?void 0:h.deferrable)==="DEFERRABLE"&&(h!=null&&h.deferrableConstraintCheckTime)?` ${h==null?void 0:h.deferrableConstraintCheckTime}`:"";return{statement:n(d.createKeyConstraint,{constraintName:h.name?`CONSTRAINT ${T} `:"",keyType:h.keyType,columns:y,includeNonKey:N,storageParameters:S,tablespace:b,deferrable:I,deferrableConstraintCheckTime:R}),isActivated:!_}},"createKeyConstraint"),getConstraintsWarnings:i((d=[])=>t.isEmpty(d)?"":` - `+d.map(f=>{let h=f.name?` [constraint name: ${f.name}]`:"";return`-- ${f.errorMessage}${h}`}).join(` - `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:i(d=>{let f=t.get(d,"relationshipOnDelete",""),h=t.get(d,"relationshipOnUpdate",""),T=t.get(d,"relationshipMatch",""),_=t.get(d,"deferrable",""),y=t.get(d,"deferrableConstraintCheckTime","");return{foreignOnDelete:f,foreignOnUpdate:h,foreignMatch:T,deferrable:_,deferrableConstraintCheckTime:y}},"additionalPropertiesForForeignKey")})});var pr=C((IA,du)=>{du.exports=(t,e)=>{let r=i((_,y)=>Object.entries(_.properties).map(y),"mapProperties"),n=i(_=>_.compositeUniqueKey?!1:!!_.unique,"isUniqueKey"),s=i(_=>{var y,N;return n(_)&&(((y=_.uniqueKeyOptions)==null?void 0:y.length)===1&&!((N=t.first(_.uniqueKeyOptions))!=null&&N.constraintName)||t.isEmpty(_.uniqueKeyOptions))},"isInlineUnique"),a=i(_=>_.compositeUniqueKey||_.compositePrimaryKey?!1:!!_.primaryKey,"isPrimaryKey"),o=i(_=>{var y;return a(_)&&!((y=t.first(_.primaryKeyOptions))!=null&&y.constraintName)},"isInlinePrimaryKey"),c=i((_,y)=>{let N=_.nullsDistinct;return`UNIQUE${y>=15&&N?` ${N}`:""}`},"getUniqueKeyType"),u=i(({options:_,columnName:y,isActivated:N,jsonSchema:S,dbVersion:b})=>e({keyType:c(_,b),name:_.constraintName,columns:[{name:y,isActivated:N}],include:d(_.indexInclude||[],S),storageParameters:_.indexStorageParameters,comment:_.indexComment,tablespace:_.indexTablespace,nullsDistinct:_.nullsDistinct,deferrable:_.deferrable,deferrableConstraintCheckTime:_.deferrableConstraintCheckTime}),"hydrateUniqueOptions"),l=i((_,y,N,S)=>e({keyType:"PRIMARY KEY",name:_.constraintName,columns:[{name:y,isActivated:N}],include:d(_.indexInclude||[],S),storageParameters:_.indexStorageParameters,comment:_.indexComment,tablespace:_.indexTablespace,deferrable:_.deferrable,deferrableConstraintCheckTime:_.deferrableConstraintCheckTime}),"hydratePrimaryKeyOptions"),p=i((_,y)=>Object.keys(y).find(N=>y[N].GUID===_),"findName"),m=i((_,y)=>t.get(Object.values(y).find(N=>N.GUID===_),"isActivated",!0),"checkIfActivated"),d=i((_,y)=>t.map(_,N=>({name:p(N.keyId,y.properties),isActivated:m(N.keyId,y.properties)})),"getKeys"),f=i(_=>Array.isArray(_.primaryKey)?_.primaryKey.map(y=>t.isEmpty(y.compositePrimaryKey)?{name:y.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...l(y,null,null,_),columns:d(y.compositePrimaryKey,_)}):[],"getCompositePrimaryKeys"),h=i((_,y)=>Array.isArray(_.uniqueKey)?_.uniqueKey.map(N=>t.isEmpty(N.compositeUniqueKey)?{name:N.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...u({options:N,columnName:null,isActivated:null,jsonSchema:_,dbVersion:y}),columns:d(N.compositeUniqueKey,_)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:i((_,y)=>{if(!_.properties)return[];let N=r(_,([b,I])=>{if(!(!a(I)||o(I)))return l(t.first(I.primaryKeyOptions),b,I.isActivated,_)}).filter(Boolean),S=t.flatten(r(_,([b,I])=>!n(I)||s(I)?[]:(I.uniqueKeyOptions||[]).map(R=>u({options:R,columnName:b,isActivated:I.isActivated,jsonSchema:_,dbVersion:y})))).filter(Boolean);return[...N,...f(_),...S,...h(_,y)]},"getTableKeyConstraints"),isInlineUnique:s,isInlinePrimaryKey:o,getKeys:d,hydratePrimaryKeyOptions:l,hydrateUniqueOptions:u,getUniqueKeyType:c}}});var hu=C((RA,fu)=>{fu.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s,wrapComment:a})=>{let o=i((S,b)=>t.map(b,I=>{let R=I.functionOrReplace?" OR REPLACE":"",M=r(e.createFunction,{name:s(I.name,S),orReplace:R,parameters:n(I.functionArguments),returnType:I.functionReturnsSetOf?`SETOF ${I.functionReturnType}`:I.functionReturnType,language:I.functionLanguage,properties:c(I),definition:I.functionBody}),v=I.functionDescription?r(e.comment,{object:"FUNCTION",objectName:s(I.name,S),comment:a(I.functionDescription)}):"";return[M,v].filter(Boolean).join(` +\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}",createTrigger:"CREATE${orReplace}${constraint} TRIGGER ${name} ${actionTiming} ${events}\n ON ${tableName}\n${options} EXECUTE ${functionKey} ${functionName};\n",createSequence:"CREATE${sequenceType} SEQUENCE${ifNotExists} ${name}${options};\n",dropSequence:"DROP SEQUENCE IF EXISTS ${name};\n",renameSequence:"ALTER SEQUENCE IF EXISTS ${name} RENAME TO ${newName};\n",setSequenceType:"ALTER SEQUENCE IF EXISTS ${name} SET ${sequenceType};\n",alterSequence:"ALTER SEQUENCE IF EXISTS ${name}${options};\n"}});var _c=N((lS,yc)=>{"use strict";var gc=i((t="")=>new RegExp("\\$\\{(.*?)\\}",t),"template"),eg=i(t=>t.match(gc("gi"))||[],"getAllTemplates"),tg=i(t=>(t.match(gc("i"))||[])[1],"parseTemplate"),rg=i((t,e)=>eg(t).reduce((r,n)=>{let s=tg(n);return r.replace(n,()=>e[s]||e[s]===0?e[s]:"")},t),"assignTemplates");yc.exports=rg});var Tc=N((mS,Ec)=>{"use strict";Ec.exports=({_:t,commentIfDeactivated:e,checkAllKeysDeactivated:r,assignTemplates:n,wrapInQuotes:s,getColumnsList:a})=>({generateConstraintsString:i((m,f)=>{var y,A;let h=e(((m==null?void 0:m.deactivatedItems)||[]).join(`, + `),{isActivated:!f,isPartOfLine:!0}),T=(y=m==null?void 0:m.activatedItems)!=null&&y.length?`, + `+m.activatedItems.join(`, + `):"",_=(A=m==null?void 0:m.deactivatedItems)!=null&&A.length?` + `+h:"";return T+_},"generateConstraintsString"),foreignKeysToString:i(m=>{if(Array.isArray(m)){let f=m.filter(_=>t.get(_,"isActivated",!0)).map(_=>s(t.trim(_.name))),h=m.filter(_=>!t.get(_,"isActivated",!0)).map(_=>s(t.trim(_.name))),T=h.length?e(h,{isActivated:!1,isPartOfLine:!0}):"";return f.join(", ")+T}return m},"foreignKeysToString"),foreignActiveKeysToString:i(m=>m.map(f=>t.trim(f.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:i((m,f)=>h=>{let T=s(t.trim(h.name)),_=r(h.columns||[]),y=t.isEmpty(h.columns)?"":a(h.columns,_,f),A=h.include.length?` INCLUDE${a(h.include,_,f)}`:"",S=h.storageParameters?` WITH (${h.storageParameters})`:"",I=h.tablespace?` USING INDEX TABLESPACE ${s(h.tablespace)}`:"",v=h!=null&&h.deferrable?` ${h.deferrable}`:"",w=(h==null?void 0:h.deferrable)==="DEFERRABLE"&&(h!=null&&h.deferrableConstraintCheckTime)?` ${h==null?void 0:h.deferrableConstraintCheckTime}`:"";return{statement:n(m.createKeyConstraint,{constraintName:h.name?`CONSTRAINT ${T} `:"",keyType:h.keyType,columns:y,includeNonKey:A,storageParameters:S,tablespace:I,deferrable:v,deferrableConstraintCheckTime:w}),isActivated:!_}},"createKeyConstraint"),getConstraintsWarnings:i((m=[])=>t.isEmpty(m)?"":` + `+m.map(f=>{let h=f.name?` [constraint name: ${f.name}]`:"";return`-- ${f.errorMessage}${h}`}).join(` + `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:i(m=>{let f=t.get(m,"relationshipOnDelete",""),h=t.get(m,"relationshipOnUpdate",""),T=t.get(m,"relationshipMatch",""),_=t.get(m,"deferrable",""),y=t.get(m,"deferrableConstraintCheckTime","");return{foreignOnDelete:f,foreignOnUpdate:h,foreignMatch:T,deferrable:_,deferrableConstraintCheckTime:y}},"additionalPropertiesForForeignKey")})});var Zt=N((fS,Sc)=>{"use strict";Sc.exports=(t,e)=>{let r=i((_,y)=>Object.entries(_.properties).map(y),"mapProperties"),n=i(_=>_.compositeUniqueKey?!1:!!_.unique,"isUniqueKey"),s=i(_=>{var y,A;return n(_)&&(((y=_.uniqueKeyOptions)==null?void 0:y.length)===1&&!((A=t.first(_.uniqueKeyOptions))!=null&&A.constraintName)||t.isEmpty(_.uniqueKeyOptions))},"isInlineUnique"),a=i(_=>_.compositeUniqueKey||_.compositePrimaryKey?!1:!!_.primaryKey,"isPrimaryKey"),o=i(_=>{var y;return a(_)&&!((y=t.first(_.primaryKeyOptions))!=null&&y.constraintName)},"isInlinePrimaryKey"),c=i((_,y)=>{let A=_.nullsDistinct;return`UNIQUE${y>=15&&A?` ${A}`:""}`},"getUniqueKeyType"),u=i(({options:_,columnName:y,isActivated:A,jsonSchema:S,dbVersion:I})=>e({keyType:c(_,I),name:_.constraintName,columns:[{name:y,isActivated:A}],include:m(_.indexInclude||[],S),storageParameters:_.indexStorageParameters,comment:_.indexComment,tablespace:_.indexTablespace,nullsDistinct:_.nullsDistinct,deferrable:_.deferrable,deferrableConstraintCheckTime:_.deferrableConstraintCheckTime}),"hydrateUniqueOptions"),l=i((_,y,A,S)=>e({keyType:"PRIMARY KEY",name:_.constraintName,columns:[{name:y,isActivated:A}],include:m(_.indexInclude||[],S),storageParameters:_.indexStorageParameters,comment:_.indexComment,tablespace:_.indexTablespace,deferrable:_.deferrable,deferrableConstraintCheckTime:_.deferrableConstraintCheckTime}),"hydratePrimaryKeyOptions"),d=i((_,y)=>Object.keys(y).find(A=>y[A].GUID===_),"findName"),p=i((_,y)=>t.get(Object.values(y).find(A=>A.GUID===_),"isActivated",!0),"checkIfActivated"),m=i((_,y)=>t.map(_,A=>({name:d(A.keyId,y.properties),isActivated:p(A.keyId,y.properties)})),"getKeys"),f=i(_=>Array.isArray(_.primaryKey)?_.primaryKey.map(y=>t.isEmpty(y.compositePrimaryKey)?{name:y.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...l(y,null,null,_),columns:m(y.compositePrimaryKey,_)}):[],"getCompositePrimaryKeys"),h=i((_,y)=>Array.isArray(_.uniqueKey)?_.uniqueKey.map(A=>t.isEmpty(A.compositeUniqueKey)?{name:A.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...u({options:A,columnName:null,isActivated:null,jsonSchema:_,dbVersion:y}),columns:m(A.compositeUniqueKey,_)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:i((_,y)=>{if(!_.properties)return[];let A=r(_,([I,v])=>{if(!(!a(v)||o(v)))return l(t.first(v.primaryKeyOptions),I,v.isActivated,_)}).filter(Boolean),S=t.flatten(r(_,([I,v])=>!n(v)||s(v)?[]:(v.uniqueKeyOptions||[]).map(w=>u({options:w,columnName:I,isActivated:v.isActivated,jsonSchema:_,dbVersion:y})))).filter(Boolean);return[...A,...f(_),...S,...h(_,y)]},"getTableKeyConstraints"),isInlineUnique:s,isInlinePrimaryKey:o,getKeys:m,hydratePrimaryKeyOptions:l,hydrateUniqueOptions:u,getUniqueKeyType:c}}});var Ac=N((gS,Cc)=>{"use strict";Cc.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s,wrapComment:a})=>{let o=i((S,I)=>t.map(I,v=>{let w=v.functionOrReplace?" OR REPLACE":"",$=r(e.createFunction,{name:s(v.name,S),orReplace:w,parameters:n(v.functionArguments),returnType:v.functionReturnsSetOf?`SETOF ${v.functionReturnType}`:v.functionReturnType,language:v.functionLanguage,properties:c(v),definition:v.functionBody}),b=v.functionDescription?r(e.comment,{object:"FUNCTION",objectName:s(v.name,S),comment:a(v.functionDescription)}):"";return[$,b].filter(Boolean).join(` `)}).join(` -`),"getFunctionsScript"),c=i(S=>{let b=i(I=>I?` ${I} -`:"","wrap");return[{key:"functionWindow",getValue:u},{key:"functionVolatility",getValue:l},{key:"functionLeakProof",getValue:p},{key:"functionNullArgs",getValue:m},{key:"functionSqlSecurity",getValue:d},{key:"functionParallel",getValue:f},{key:"functionExecutionCost",getValue:h},{key:"functionExecutionRows",getValue:T},{key:"functionSupportFunction",getValue:_},{key:"functionConfigurationParameters",getValue:y}].map(I=>b(I.getValue(S[I.key],S))).filter(Boolean).join("")},"getProperties"),u=i((S,b)=>b.language!=="c"||!S?"":"WINDOW","getWindow"),l=i(S=>S,"getVolatility"),p=i(S=>S?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),m=i(S=>S,"getNullArgs"),d=i(S=>{if(S)return`SECURITY ${S}`},"getSqlSecurity"),f=i(S=>{if(S)return`PARALLEL ${S}`},"getParallel"),h=i(S=>{if(S)return`COST ${S}`},"getExecutionCost"),T=i((S,b)=>!S||!b.functionReturnsSetOf&&!N(b)?"":`ROWS ${S}`,"getExecutionRows"),_=i(S=>{if(S)return`SUPPORT ${S}`},"getSupportFunction"),y=i(S=>{if(S)return`SET ${S}`},"getConfigurationParameters"),N=i(S=>(S.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:o}}});var yu=C((DA,gu)=>{gu.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s})=>({getProceduresScript:i((o,c)=>t.map(c,u=>{let l=u.orReplace?" OR REPLACE":"";return r(e.createProcedure,{name:s(u.name,o),orReplace:l,parameters:n(u.inputArgs),language:u.language,body:u.body})}).join(` -`),"getProceduresScript")})});var Eu=C((PA,_u)=>{var{Sequence:xA}=or();_u.exports=({_:t,templates:e,assignTemplates:r,getNamePrefixedWithSchemaName:n,wrapInQuotes:s})=>{let a=i(({schemaName:S,sequences:b})=>t.map(b,I=>o({schemaName:S,sequence:I})).join(` -`),"getSequencesScript"),o=i(({schemaName:S,sequence:b})=>{let I=b.temporary?"":S,R=n(b.sequenceName,I),M=f({sequence:b}),v=h({sequence:b}),D=l({sequence:b,schemaName:S});return r(e.createSequence,{name:R,ifNotExists:M,sequenceType:v,options:D})},"createSequenceScript"),c=i(({schemaName:S,sequence:b,oldSequence:I})=>{let R=b.temporary?"":S,M=I.sequenceName||b.sequenceName,v=n(M,R),D=N({sequence:b,oldSequence:I}),G=l({schemaName:S,sequence:D}),P=T({sequence:D}),X=D.sequenceName;return[{key:"options",value:G,template:e.alterSequence},{key:"sequenceType",value:P,template:e.setSequenceType},{key:"newName",value:X,template:e.renameSequence}].filter(me=>me.value).map(me=>r(me.template,{[me.key]:me.value,name:v})).join(` -`)},"alterSequenceScript"),u=i(({schemaName:S,sequence:b})=>{let I=b.temporary?"":S,R=n(b.sequenceName,I);return r(e.dropSequence,{name:R})},"dropSequenceScript"),l=i(({schemaName:S,sequence:b})=>{let R=[{getOption:p,key:"dataType",clause:"AS"},{getOption:p,key:"increment",clause:"INCREMENT BY"},{getOption:p,key:"start",clause:"START WITH"},{getOption:p,key:"restart",clause:"RESTART WITH"},{getOption:p,key:"minValue",clause:"MINVALUE"},{getOption:p,key:"maxValue",clause:"MAXVALUE"},{getOption:p,key:"cache",clause:"CACHE"},{getOption:_,key:"cycle"},{getOption:y,key:"ownedByColumn"}].map(M=>{let v=M.getOption({sequence:b,schemaName:S,config:M});return m({option:v})}).filter(Boolean).join("");return R&&d({options:R})},"getSequenceOptions"),p=i(({sequence:S,config:b})=>{let I=S[b.key];return I||I===0?`${b.clause} ${I}`:""},"getOption"),m=i(({option:S})=>S?` ${S} -`:"","wrapOption"),d=i(({options:S})=>` -`+S.replace(/\n$/,""),"wrapOptionsBlock"),f=i(({sequence:S})=>S.ifNotExist?" IF NOT EXISTS":"","getIfNotExists"),h=i(({sequence:S})=>S.temporary?" TEMPORARY":S.unlogged?" UNLOGGED":"","getSequenceType"),T=i(({sequence:S})=>S.temporary?"":S.unlogged===!0?"UNLOGGED":S.unlogged===!1?"LOGGED":"","getAlterSequenceType"),_=i(({sequence:S})=>S.cycle===!0?"CYCLE":S.cycle===!1?"NO CYCLE":"","getCycle"),y=i(({sequence:S,schemaName:b})=>{var R,M;if(S.ownedByNone)return"OWNED BY NONE";let I=(R=S.ownedByColumn)==null?void 0:R[0];if(I){let[v,D]=((M=I.name)==null?void 0:M.split("."))||[];return`OWNED BY ${[b,v,D].filter(Boolean).map(s).join(".")}`}return""},"getOwnedBy"),N=i(({sequence:S,oldSequence:b})=>{let I=t.omitBy(S,(R,M)=>t.isEqual(R,b[M]));return S.minValue>b.minValue?{...I,restart:S.start}:I},"getModifiedSequence");return{getSequencesScript:a,createSequenceScript:o,dropSequenceScript:u,alterSequenceScript:c}}});var Su=C((MA,Tu)=>{Tu.exports=({_:t,getColumnsList:e,checkAllKeysDeactivated:r})=>{let n=i((m,d)=>m?" TEMPORARY":d?" UNLOGGED":"","getTableTemporaryValue"),s=i(m=>{let d=i(h=>h?`${h} -`:"","wrap"),f=[{key:"inherits",getValue:u("INHERITS")},{key:"partitionBounds",getValue:u("")},{key:"partitioning",getValue:a},{key:"usingMethod",getValue:u("USING")},{key:"storage_parameter",getValue:p},{key:"on_commit",getValue:c},{key:"table_tablespace_name",getValue:u("TABLESPACE")},{key:"selectStatement",getValue:u("AS")}].map(h=>d(h.getValue(m[h.key],m))).filter(Boolean).join("");return t.trim(f)?` ${t.trim(f)}`:""},"getTableOptions"),a=i((m,{isActivated:d})=>{if(m&&m.partitionMethod){let f=m.partitionBy==="keys"?o(m,d):` (${m.partitioning_expression})`;return`PARTITION BY ${m.partitionMethod}${f}`}},"getPartitioning"),o=i((m,d)=>{let f=r(m.compositePartitionKey);return e(m.compositePartitionKey,f,d)},"getPartitionKeys"),c=i((m,d)=>{if(m&&d.temporary)return`ON COMMIT ${m}`},"getOnCommit"),u=i(m=>d=>{if(d)return`${m} ${d}`},"getBasicValue"),l=["toast_autovacuum_enabled","toast_vacuum_index_cleanup","toast_vacuum_truncate","toast_autovacuum_vacuum_threshold","toast_autovacuum_vacuum_scale_factor","toast_autovacuum_vacuum_insert_threshold","toast_autovacuum_vacuum_insert_scale_factor","toast_autovacuum_vacuum_cost_delay","toast_autovacuum_vacuum_cost_limit","toast_autovacuum_freeze_min_age","toast_autovacuum_freeze_max_age","toast_autovacuum_freeze_table_age","toast_autovacuum_multixact_freeze_min_age","toast_autovacuum_multixact_freeze_max_age","toast_autovacuum_multixact_freeze_table_age","toast_log_autovacuum_min_duration"],p=i(m=>{if(t.isEmpty(m))return"";let d=["autovacuum","toast","id"];return t.chain(m).toPairs().flatMap(([f,h])=>f==="autovacuum"||f==="toast"?t.toPairs(h):[[f,h]]).reject(([f])=>t.includes(d,f)).map(([f,h])=>{if(!(!h&&h!==0))return t.includes(l,f)?`toast.${f.slice(6)}=${h}`:`${f}=${h}`}).compact().join(`, +`),"getFunctionsScript"),c=i(S=>{let I=i(v=>v?` ${v} +`:"","wrap");return[{key:"functionWindow",getValue:u},{key:"functionVolatility",getValue:l},{key:"functionLeakProof",getValue:d},{key:"functionNullArgs",getValue:p},{key:"functionSqlSecurity",getValue:m},{key:"functionParallel",getValue:f},{key:"functionExecutionCost",getValue:h},{key:"functionExecutionRows",getValue:T},{key:"functionSupportFunction",getValue:_},{key:"functionConfigurationParameters",getValue:y}].map(v=>I(v.getValue(S[v.key],S))).filter(Boolean).join("")},"getProperties"),u=i((S,I)=>I.language!=="c"||!S?"":"WINDOW","getWindow"),l=i(S=>S,"getVolatility"),d=i(S=>S?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),p=i(S=>S,"getNullArgs"),m=i(S=>{if(S)return`SECURITY ${S}`},"getSqlSecurity"),f=i(S=>{if(S)return`PARALLEL ${S}`},"getParallel"),h=i(S=>{if(S)return`COST ${S}`},"getExecutionCost"),T=i((S,I)=>!S||!I.functionReturnsSetOf&&!A(I)?"":`ROWS ${S}`,"getExecutionRows"),_=i(S=>{if(S)return`SUPPORT ${S}`},"getSupportFunction"),y=i(S=>{if(S)return`SET ${S}`},"getConfigurationParameters"),A=i(S=>(S.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:o}}});var bc=N((_S,Nc)=>{"use strict";Nc.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s})=>({getProceduresScript:i((o,c)=>t.map(c,u=>{let l=u.orReplace?" OR REPLACE":"";return r(e.createProcedure,{name:s(u.name,o),orReplace:l,parameters:n(u.inputArgs),language:u.language,body:u.body})}).join(` +`),"getProceduresScript")})});var vc=N((SS,Ic)=>{"use strict";var{Sequence:TS}=jt();Ic.exports=({_:t,templates:e,assignTemplates:r,getNamePrefixedWithSchemaName:n,wrapInQuotes:s})=>{let a=i(({schemaName:S,sequences:I})=>t.map(I,v=>o({schemaName:S,sequence:v})).join(` +`),"getSequencesScript"),o=i(({schemaName:S,sequence:I})=>{let v=I.temporary?"":S,w=n(I.sequenceName,v),$=f({sequence:I}),b=h({sequence:I}),q=l({sequence:I,schemaName:S});return r(e.createSequence,{name:w,ifNotExists:$,sequenceType:b,options:q})},"createSequenceScript"),c=i(({schemaName:S,sequence:I,oldSequence:v})=>{let w=I.temporary?"":S,$=v.sequenceName||I.sequenceName,b=n($,w),q=A({sequence:I,oldSequence:v}),G=l({schemaName:S,sequence:q}),P=T({sequence:q}),z=q.sequenceName;return[{key:"options",value:G,template:e.alterSequence},{key:"sequenceType",value:P,template:e.setSequenceType},{key:"newName",value:z,template:e.renameSequence}].filter(le=>le.value).map(le=>r(le.template,{[le.key]:le.value,name:b})).join(` +`)},"alterSequenceScript"),u=i(({schemaName:S,sequence:I})=>{let v=I.temporary?"":S,w=n(I.sequenceName,v);return r(e.dropSequence,{name:w})},"dropSequenceScript"),l=i(({schemaName:S,sequence:I})=>{let w=[{getOption:d,key:"dataType",clause:"AS"},{getOption:d,key:"increment",clause:"INCREMENT BY"},{getOption:d,key:"start",clause:"START WITH"},{getOption:d,key:"restart",clause:"RESTART WITH"},{getOption:d,key:"minValue",clause:"MINVALUE"},{getOption:d,key:"maxValue",clause:"MAXVALUE"},{getOption:d,key:"cache",clause:"CACHE"},{getOption:_,key:"cycle"},{getOption:y,key:"ownedByColumn"}].map($=>{let b=$.getOption({sequence:I,schemaName:S,config:$});return p({option:b})}).filter(Boolean).join("");return w&&m({options:w})},"getSequenceOptions"),d=i(({sequence:S,config:I})=>{let v=S[I.key];return v||v===0?`${I.clause} ${v}`:""},"getOption"),p=i(({option:S})=>S?` ${S} +`:"","wrapOption"),m=i(({options:S})=>` +`+S.replace(/\n$/,""),"wrapOptionsBlock"),f=i(({sequence:S})=>S.ifNotExist?" IF NOT EXISTS":"","getIfNotExists"),h=i(({sequence:S})=>S.temporary?" TEMPORARY":S.unlogged?" UNLOGGED":"","getSequenceType"),T=i(({sequence:S})=>S.temporary?"":S.unlogged===!0?"UNLOGGED":S.unlogged===!1?"LOGGED":"","getAlterSequenceType"),_=i(({sequence:S})=>S.cycle===!0?"CYCLE":S.cycle===!1?"NO CYCLE":"","getCycle"),y=i(({sequence:S,schemaName:I})=>{var w,$;if(S.ownedByNone)return"OWNED BY NONE";let v=(w=S.ownedByColumn)==null?void 0:w[0];if(v){let[b,q]=(($=v.name)==null?void 0:$.split("."))||[];return`OWNED BY ${[I,b,q].filter(Boolean).map(s).join(".")}`}return""},"getOwnedBy"),A=i(({sequence:S,oldSequence:I})=>{let v=t.omitBy(S,(w,$)=>t.isEqual(w,I[$]));return S.minValue>I.minValue?{...v,restart:S.start}:v},"getModifiedSequence");return{getSequencesScript:a,createSequenceScript:o,dropSequenceScript:u,alterSequenceScript:c}}});var Rc=N((AS,Oc)=>{"use strict";Oc.exports=({_:t,getColumnsList:e,checkAllKeysDeactivated:r})=>{let n=i((p,m)=>p?" TEMPORARY":m?" UNLOGGED":"","getTableTemporaryValue"),s=i(p=>{let m=i(h=>h?`${h} +`:"","wrap"),f=[{key:"inherits",getValue:u("INHERITS")},{key:"partitionBounds",getValue:u("")},{key:"partitioning",getValue:a},{key:"usingMethod",getValue:u("USING")},{key:"storage_parameter",getValue:d},{key:"on_commit",getValue:c},{key:"table_tablespace_name",getValue:u("TABLESPACE")},{key:"selectStatement",getValue:u("AS")}].map(h=>m(h.getValue(p[h.key],p))).filter(Boolean).join("");return t.trim(f)?` ${t.trim(f)}`:""},"getTableOptions"),a=i((p,{isActivated:m})=>{if(p&&p.partitionMethod){let f=p.partitionBy==="keys"?o(p,m):` (${p.partitioning_expression})`;return`PARTITION BY ${p.partitionMethod}${f}`}},"getPartitioning"),o=i((p,m)=>{let f=r(p.compositePartitionKey);return e(p.compositePartitionKey,f,m)},"getPartitionKeys"),c=i((p,m)=>{if(p&&m.temporary)return`ON COMMIT ${p}`},"getOnCommit"),u=i(p=>m=>{if(m)return`${p} ${m}`},"getBasicValue"),l=["toast_autovacuum_enabled","toast_vacuum_index_cleanup","toast_vacuum_truncate","toast_autovacuum_vacuum_threshold","toast_autovacuum_vacuum_scale_factor","toast_autovacuum_vacuum_insert_threshold","toast_autovacuum_vacuum_insert_scale_factor","toast_autovacuum_vacuum_cost_delay","toast_autovacuum_vacuum_cost_limit","toast_autovacuum_freeze_min_age","toast_autovacuum_freeze_max_age","toast_autovacuum_freeze_table_age","toast_autovacuum_multixact_freeze_min_age","toast_autovacuum_multixact_freeze_max_age","toast_autovacuum_multixact_freeze_table_age","toast_log_autovacuum_min_duration"],d=i(p=>{if(t.isEmpty(p))return"";let m=["autovacuum","toast","id"];return t.chain(p).toPairs().flatMap(([f,h])=>f==="autovacuum"||f==="toast"?t.toPairs(h):[[f,h]]).reject(([f])=>t.includes(m,f)).map(([f,h])=>{if(!(!h&&h!==0))return t.includes(l,f)?`toast.${f.slice(6)}=${h}`:`${f}=${h}`}).compact().join(`, `).trim().thru(f=>{if(f)return`WITH ( ${f} -)`}).value()},"getStorageParameters");return{getTableTemporaryValue:n,getTableOptions:s}}});var Au=C((UA,Cu)=>{Cu.exports=({_:t,commentIfDeactivated:e,assignTemplates:r,templates:n,getNamePrefixedWithSchemaName:s,wrapComment:a})=>{let o=["composite","enum","range_udt","domain"],c=i((f,h)=>{let T=s(f.name,f.schemaName),_=r(n.comment,{object:"TYPE",objectName:T,comment:a(f.comment)});switch(f.type){case"composite":return r(n.createCompositeType,{name:T,columnDefinitions:t.join(h,`, +)`}).value()},"getStorageParameters");return{getTableTemporaryValue:n,getTableOptions:s}}});var qc=N((bS,wc)=>{"use strict";wc.exports=({_:t,commentIfDeactivated:e,assignTemplates:r,templates:n,getNamePrefixedWithSchemaName:s,wrapComment:a})=>{let o=["composite","enum","range_udt","domain"],c=i((f,h)=>{let T=s(f.name,f.schemaName),_=r(n.comment,{object:"TYPE",objectName:T,comment:a(f.comment)});switch(f.type){case"composite":return r(n.createCompositeType,{name:T,columnDefinitions:t.join(h,`, `),comment:f.comment?_:""});case"enum":return r(n.createEnumType,{name:T,values:t.map(f.enum,y=>`'${y}'`).join(", "),comment:f.comment?_:""});case"range_udt":return r(n.createRangeType,{name:T,subtype:f.rangeSubtype,options:l(f),comment:f.comment?_:""});case"domain":{let y=r(n.comment,{object:"DOMAIN",objectName:T,comment:a(f.comment)});return r(n.createDomainType,{name:T,underlyingType:f.underlyingType,notNull:f.nullable?"":" NOT NULL",collate:f.collation?` COLLATE ${f.collation}`:"",default:f.default?` - DEFAULT ${f.default}`:"",constraints:p(f),comment:f.comment?y:""})}default:return""}},"getPlainUdt"),u=i(f=>o.includes(f.type),"isNotPlainType"),l=i(f=>{let h=i(_=>_?` ${_}`:"","wrap"),T=[{key:"operatorClass",getValue:m("SUBTYPE_OPCLASS")},{key:"collation",getValue:m("COLLATION")},{key:"canonicalFunction",getValue:m("CANONICAL")},{key:"subtypeDiffFunction",getValue:m("SUBTYPE_DIFF")},{key:"multiRangeType",getValue:m("MULTIRANGE_TYPE_NAME")}].map(_=>h(_.getValue(f[_.key]))).filter(Boolean).join(`, + DEFAULT ${f.default}`:"",constraints:d(f),comment:f.comment?y:""})}default:return""}},"getPlainUdt"),u=i(f=>o.includes(f.type),"isNotPlainType"),l=i(f=>{let h=i(_=>_?` ${_}`:"","wrap"),T=[{key:"operatorClass",getValue:p("SUBTYPE_OPCLASS")},{key:"collation",getValue:p("COLLATION")},{key:"canonicalFunction",getValue:p("CANONICAL")},{key:"subtypeDiffFunction",getValue:p("SUBTYPE_DIFF")},{key:"multiRangeType",getValue:p("MULTIRANGE_TYPE_NAME")}].map(_=>h(_.getValue(f[_.key]))).filter(Boolean).join(`, `);return t.trim(T)?`, - `+t.trim(T):""},"getRangeOptions"),p=i(f=>t.map(f.checkConstraints,h=>h.name?` + `+t.trim(T):""},"getRangeOptions"),d=i(f=>t.map(f.checkConstraints,h=>h.name?` CONSTRAINT ${h.name} CHECK (${h.expression})`:` - CHECK (${h.expression})`).join(""),"getDomainConstraints"),m=i(f=>h=>{if(h)return`${f}=${h}`},"getBasicValue");return{getUserDefinedType:i((f,h)=>e(c(f,h),{isActivated:f.isActivated}),"getUserDefinedType"),isNotPlainType:u}}});var bu=C(($A,Nu)=>{Nu.exports=({_:t,wrapInQuotes:e,checkAllKeysDeactivated:r,getColumnsList:n})=>{let s=i(({name:p,sortOrder:m,nullsOrder:d,collation:f,opclass:h})=>{let T=m?` ${m}`:"",_=d?` ${d}`:"",y=t.includes(f,'"')?f:`"${f}"`,N=f?` COLLATE ${y}`:"",S=h?` ${h}`:"";return`${e(p)}${N}${S}${T}${_}`},"mapIndexKey"),a=i((p=[],m)=>{let d=r(p);return n(p,d,m,s)},"getIndexKeys"),o=i((p,m)=>{var N;let d=n(p.include||[],r(p.include||[]),m),f=(N=p.include)!=null&&N.length?` INCLUDE ${t.trim(d)}`:"",h=u(p),T=h?` WITH ( - ${h})`:"",_=p.index_tablespace_name?` TABLESPACE ${p.index_tablespace_name}`:"",y=p.where?` WHERE ${p.where}`:"";return t.compact([" ",f,T,_,y]).join(` -`)},"getIndexOptions"),c={btree:{index_fillfactor:"fillfactor",deduplicate_items:"deduplicate_items"},hash:{index_fillfactor:"fillfactor"},spgist:{index_fillfactor:"fillfactor"},gist:{index_fillfactor:"fillfactor",index_buffering:"buffering"},gin:{fastupdate:"fastupdate",gin_pending_list_limit:"gin_pending_list_limit"},brin:{pages_per_range:"pages_per_range",autosummarize:"autosummarize"}},u=i(p=>{let m=c[p.index_method];return t.chain(m).toPairs().map(([d,f])=>{let h=(p.index_storage_parameter||{})[d];if(!(t.isNil(h)||h===""))return`${f}=${l(h)}`}).compact().join(`, - `).value()},"getWithOptions"),l=i(p=>t.isBoolean(p)?p?"ON":"OFF":p,"getValue");return{getIndexKeys:a,getIndexOptions:o,getWithOptions:u}}});var Iu=C((KA,vu)=>{vu.exports=({_:t,assignTemplates:e,templates:r,commentIfDeactivated:n,wrapComment:s,wrapInQuotes:a})=>{let o=i((v,D)=>`${v}(${D})`,"addLength"),c=i((v,D,G)=>t.isNumber(G)?`${v}(${D},${G})`:`${v}(${D})`,"addScalePrecision"),u=i((v,D)=>t.isNumber(D)?`${v}(${D})`:v,"addPrecision"),l=i((v,D)=>D?`${v} ${D}`:v,"addWithTimezone"),p=i(({type:v,typeModifier:D,srid:G})=>{let P=G?`, ${G}`:"";return D&&D!==""?`${v}(${D}${P})`:v},"addTypeModifier"),m=i((v,D)=>{let G=(D==null?void 0:D.map(P=>`[${(P==null?void 0:P.array_size_limit)??""}]`).join("").trim())||"";return`${v}${G}`},"addArrayDecorator"),d=i(v=>["char","varchar","bit","varbit"].includes(v),"canHaveLength"),f=i(v=>v==="numeric","canHavePrecision"),h=i(v=>["time","timestamp"].includes(v),"canHaveTimePrecision"),T=i(v=>v==="numeric","canHaveScale"),_=i(v=>["geography","geometry"].includes(v),"canHaveTypeModifier"),y=i((v,D)=>(d(v)&&t.isNumber(D.length)?v=o(v,D.length):f(v)&&T(v)&&t.isNumber(D.precision)?v=c(v,D.precision,D.scale):f(v)&&t.isNumber(D.precision)?v=u(v,D.precision):_(v)?v=p({type:v,typeModifier:D.typeModifier,srid:D.srid}):h(v)&&(t.isNumber(D.timePrecision)||D.timezone)&&(v=l(u(v,D.timePrecision),D.timezone)),m(v,D.array_type)),"decorateType"),N=i(v=>["char","varchar","text","bit","varbit"].includes(v),"isString"),S=i(v=>["date","time","timestamp","interval"].includes(v),"isDateTime"),b=i((v,D,G)=>{let P=["current_timestamp","null"];return(N(v)||S(v))&&!P.includes(t.toLower(D))&&!G?s(D):D},"decorateDefault"),I=i((v,D)=>t.chain(D).filter("comment").map(G=>{let P=e(r.comment,{object:"COLUMN",objectName:`${v}.${a(G.name)}`,comment:s(G.comment)});return n(P,G)}).join(` -`).value(),"getColumnComments"),R={"v13.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v12.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v11.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v10.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"}};return{decorateType:y,decorateDefault:b,getColumnComments:I,replaceTypeByVersion:i((v,D)=>{let G=R[D];return t.get(G,v)||v},"replaceTypeByVersion")}}});var Ru=C((VA,Ou)=>{Ou.exports=({_:t,assignTemplates:e,templates:r,getNamePrefixedWithSchemaName:n,wrap:s,commentIfDeactivated:a})=>{let o=i(({dbVersion:m,triggers:d,tableName:f})=>t.map(d,c(m,f)).join(` -`).trim(),"getTriggersScript"),c=i((m,d)=>f=>{let h=u(f),T=l(f);return e(r.createTrigger,{orReplace:f.triggerOrReplace?" OR REPLACE":"",constraint:f.triggerConstraint?" CONSTRAINT":"",actionTiming:f.triggerType??"",functionKey:m==="v10.x"?"PROCEDURE":"FUNCTION",functionName:f.triggerFunction,name:f.name,tableName:d,events:h,options:T})},"getTriggerScript"),u=i(m=>{var d;return(d=m.triggerEvents)==null?void 0:d.map(f=>{if(f.triggerEvent!=="UPDATE"||t.isEmpty(m.triggerUpdateColumns))return f.triggerEvent;let h=t.chain(m.triggerUpdateColumns).filter("isActivated").map(({name:y})=>y).join(", ").thru(y=>y&&`OF ${y}`).value(),T=t.chain(m.triggerUpdateColumns).reject("isActivated").map(({name:y})=>y).join(", ").thru(y=>!h&&y?`OF ${y}`:y).value(),_=T&&a(T,{isActivated:!1,isPartOfLine:!0});return`UPDATE ${h} ${_}`}).join(" OR ")},"getTriggerEvents"),l=i(m=>{let d="";if(m.triggerConstraint&&(m.triggerReferencedTable&&(d+=s(`FROM ${m.triggerReferencedTable}`," ",` -`)),d+=s(m.triggerDeferrable?"DEFERRABLE":"NOT DEFERRABLE"," ",` -`),m.triggerDeferrable&&m.triggerTimeConstraintCheck&&(d+=s(m.triggerTimeConstraintCheck," ",` -`))),m.triggerReferencing){let f="REFERENCING";m.triggerBeforeImageTransitionRelation&&(f+=` OLD TABLE ${m.triggerBeforeImageTransitionRelation}`),m.triggerAfterImageTransitionRelation&&(f+=` NEW TABLE ${m.triggerAfterImageTransitionRelation}`),d+=s(f," ",` -`)}return d+=s(m.triggerConstraint||m.triggerType==="INSTEAD OF"?"FOR EACH ROW":m.triggerEachRowStatement||"FOR EACH STATEMENT"," ",` -`),m.triggerCondition&&(d+=s(`WHEN ${m.triggerCondition}`," ",` -`)),d},"getTriggerOptions");return{getTriggersScript:o,hydrateTriggers:i((m,d={})=>{var f;return(((f=t.find(m,"triggers"))==null?void 0:f.triggers)||[]).map(h=>{let T=d[h.triggerReferencedTable];if(!T)return{...h,triggerReferencedTable:""};let _=n(T.code||T.collectionName,T.bucketName);return{...h,triggerReferencedTable:_}})},"hydrateTriggers")}}});var Du=C((WA,wu)=>{wu.exports=()=>({getLocaleProperties:i(e=>{let r=["v13.x","v14.x","v15.x"].includes(e.dbVersion);return r&&e.locale?{locale:e.locale}:!r&&e.locale?{collate:e.locale,characterClassification:e.locale}:{collate:e.collate,characterClassification:e.characterClassification}},"getLocaleProperties")})});var se=C((jA,xu)=>{var r_=nu(),qu=iu(),x=ou(),{Sequence:YA}=or();xu.exports=(t,e,r)=>{let n=r.require("lodash"),{tab:s,commentIfDeactivated:a,checkAllKeysDeactivated:o,divideIntoActivatedAndDeactivated:c,hasType:u,wrap:l,clean:p,wrapComment:m,getFunctionArguments:d,wrapInQuotes:f,getNamePrefixedWithSchemaName:h,getColumnsList:T,getViewData:_}=L()(n),y=lu(),{generateConstraintsString:N,foreignKeysToString:S,foreignActiveKeysToString:b,createKeyConstraint:I,getConstraintsWarnings:R,additionalPropertiesForForeignKey:M}=mu()({_:n,commentIfDeactivated:a,checkAllKeysDeactivated:o,assignTemplates:y,getColumnsList:T,wrapInQuotes:f}),v=pr()(n,p),{getFunctionsScript:D}=hu()({_:n,templates:x,assignTemplates:y,getFunctionArguments:d,getNamePrefixedWithSchemaName:h,wrapComment:m}),{getProceduresScript:G}=yu()({_:n,templates:x,assignTemplates:y,getFunctionArguments:d,getNamePrefixedWithSchemaName:h}),{getSequencesScript:P,createSequenceScript:X,dropSequenceScript:ve,alterSequenceScript:me}=Eu()({_:n,templates:x,assignTemplates:y,getNamePrefixedWithSchemaName:h,wrapInQuotes:f}),{getTableTemporaryValue:U,getTableOptions:Ie}=Su()({_:n,checkAllKeysDeactivated:o,getColumnsList:T}),{getUserDefinedType:A,isNotPlainType:q}=Au()({_:n,commentIfDeactivated:a,assignTemplates:y,templates:x,getNamePrefixedWithSchemaName:h,wrapComment:m}),{getIndexKeys:B,getIndexOptions:W,getWithOptions:ie}=bu()({_:n,wrapInQuotes:f,checkAllKeysDeactivated:o,getColumnsList:T}),{decorateType:Pe,decorateDefault:qe,getColumnComments:Sr,replaceTypeByVersion:Jl}=Iu()({_:n,wrap:l,assignTemplates:y,templates:x,commentIfDeactivated:a,wrapInQuotes:f,wrapComment:m}),{getTriggersScript:Vi,hydrateTriggers:Hi}=Ru()({_:n,wrap:l,assignTemplates:y,templates:x,getNamePrefixedWithSchemaName:h,commentIfDeactivated:a}),{getLocaleProperties:ep}=Du()();return{createDatabase(g){if(!g.databaseName)return"";let{locale:E,collate:O,characterClassification:w}=ep(g);return y(x.createDatabase,{name:f(g.databaseName),template:g.template?` + CHECK (${h.expression})`).join(""),"getDomainConstraints"),p=i(f=>h=>{if(h)return`${f}=${h}`},"getBasicValue");return{getUserDefinedType:i((f,h)=>e(c(f,h),{isActivated:f.isActivated}),"getUserDefinedType"),isNotPlainType:u}}});var xc=N((vS,Dc)=>{"use strict";Dc.exports=({_:t,wrapInQuotes:e,checkAllKeysDeactivated:r,getColumnsList:n})=>{let s=i(({name:d,sortOrder:p,nullsOrder:m,collation:f,opclass:h})=>{let T=p?` ${p}`:"",_=m?` ${m}`:"",y=t.includes(f,'"')?f:`"${f}"`,A=f?` COLLATE ${y}`:"",S=h?` ${h}`:"";return`${e(d)}${A}${S}${T}${_}`},"mapIndexKey"),a=i((d=[],p)=>{let m=r(d);return n(d,m,p,s)},"getIndexKeys"),o=i((d,p)=>{var A;let m=n(d.include||[],r(d.include||[]),p),f=(A=d.include)!=null&&A.length?` INCLUDE ${t.trim(m)}`:"",h=u(d),T=h?` WITH ( + ${h})`:"",_=d.index_tablespace_name?` TABLESPACE ${d.index_tablespace_name}`:"",y=d.where?` WHERE ${d.where}`:"";return t.compact([" ",f,T,_,y]).join(` +`)},"getIndexOptions"),c={btree:{index_fillfactor:"fillfactor",deduplicate_items:"deduplicate_items"},hash:{index_fillfactor:"fillfactor"},spgist:{index_fillfactor:"fillfactor"},gist:{index_fillfactor:"fillfactor",index_buffering:"buffering"},gin:{fastupdate:"fastupdate",gin_pending_list_limit:"gin_pending_list_limit"},brin:{pages_per_range:"pages_per_range",autosummarize:"autosummarize"}},u=i(d=>{let p=c[d.index_method];return t.chain(p).toPairs().map(([m,f])=>{let h=(d.index_storage_parameter||{})[m];if(!(t.isNil(h)||h===""))return`${f}=${l(h)}`}).compact().join(`, + `).value()},"getWithOptions"),l=i(d=>t.isBoolean(d)?d?"ON":"OFF":d,"getValue");return{getIndexKeys:a,getIndexOptions:o,getWithOptions:u}}});var Lc=N((RS,Pc)=>{"use strict";Pc.exports=({_:t,assignTemplates:e,templates:r,commentIfDeactivated:n,wrapComment:s,wrapInQuotes:a})=>{let o=i((b,q)=>`${b}(${q})`,"addLength"),c=i((b,q,G)=>t.isNumber(G)?`${b}(${q},${G})`:`${b}(${q})`,"addScalePrecision"),u=i((b,q)=>t.isNumber(q)?`${b}(${q})`:b,"addPrecision"),l=i((b,q)=>q?`${b} ${q}`:b,"addWithTimezone"),d=i(({type:b,typeModifier:q,srid:G})=>{let P=G?`, ${G}`:"";return q&&q!==""?`${b}(${q}${P})`:b},"addTypeModifier"),p=i((b,q)=>{let G=(q==null?void 0:q.map(P=>`[${(P==null?void 0:P.array_size_limit)??""}]`).join("").trim())||"";return`${b}${G}`},"addArrayDecorator"),m=i(b=>["char","varchar","bit","varbit"].includes(b),"canHaveLength"),f=i(b=>b==="numeric","canHavePrecision"),h=i(b=>["time","timestamp"].includes(b),"canHaveTimePrecision"),T=i(b=>b==="numeric","canHaveScale"),_=i(b=>["geography","geometry"].includes(b),"canHaveTypeModifier"),y=i((b,q)=>(m(b)&&t.isNumber(q.length)?b=o(b,q.length):f(b)&&T(b)&&t.isNumber(q.precision)?b=c(b,q.precision,q.scale):f(b)&&t.isNumber(q.precision)?b=u(b,q.precision):_(b)?b=d({type:b,typeModifier:q.typeModifier,srid:q.srid}):h(b)&&(t.isNumber(q.timePrecision)||q.timezone)&&(b=l(u(b,q.timePrecision),q.timezone)),p(b,q.array_type)),"decorateType"),A=i(b=>["char","varchar","text","bit","varbit"].includes(b),"isString"),S=i(b=>["date","time","timestamp","interval"].includes(b),"isDateTime"),I=i((b,q,G)=>{let P=["current_timestamp","null"];return(A(b)||S(b))&&!P.includes(t.toLower(q))&&!G?s(q):q},"decorateDefault"),v=i((b,q)=>t.chain(q).filter("comment").map(G=>{let P=e(r.comment,{object:"COLUMN",objectName:`${b}.${a(G.name)}`,comment:s(G.comment)});return n(P,G)}).join(` +`).value(),"getColumnComments"),w={"v13.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v12.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v11.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v10.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"}};return{decorateType:y,decorateDefault:I,getColumnComments:v,replaceTypeByVersion:i((b,q)=>{let G=w[q];return t.get(G,b)||b},"replaceTypeByVersion")}}});var Fc=N((qS,Mc)=>{"use strict";Mc.exports=({_:t,assignTemplates:e,templates:r,getNamePrefixedWithSchemaName:n,wrap:s,commentIfDeactivated:a})=>{let o=i(({dbVersion:p,triggers:m,tableName:f})=>t.map(m,c(p,f)).join(` +`).trim(),"getTriggersScript"),c=i((p,m)=>f=>{let h=u(f),T=l(f);return e(r.createTrigger,{orReplace:f.triggerOrReplace?" OR REPLACE":"",constraint:f.triggerConstraint?" CONSTRAINT":"",actionTiming:f.triggerType??"",functionKey:p==="v10.x"?"PROCEDURE":"FUNCTION",functionName:f.triggerFunction,name:f.name,tableName:m,events:h,options:T})},"getTriggerScript"),u=i(p=>{var m;return(m=p.triggerEvents)==null?void 0:m.map(f=>{if(f.triggerEvent!=="UPDATE"||t.isEmpty(p.triggerUpdateColumns))return f.triggerEvent;let h=t.chain(p.triggerUpdateColumns).filter("isActivated").map(({name:y})=>y).join(", ").thru(y=>y&&`OF ${y}`).value(),T=t.chain(p.triggerUpdateColumns).reject("isActivated").map(({name:y})=>y).join(", ").thru(y=>!h&&y?`OF ${y}`:y).value(),_=T&&a(T,{isActivated:!1,isPartOfLine:!0});return`UPDATE ${h} ${_}`}).join(" OR ")},"getTriggerEvents"),l=i(p=>{let m="";if(p.triggerConstraint&&(p.triggerReferencedTable&&(m+=s(`FROM ${p.triggerReferencedTable}`," ",` +`)),m+=s(p.triggerDeferrable?"DEFERRABLE":"NOT DEFERRABLE"," ",` +`),p.triggerDeferrable&&p.triggerTimeConstraintCheck&&(m+=s(p.triggerTimeConstraintCheck," ",` +`))),p.triggerReferencing){let f="REFERENCING";p.triggerBeforeImageTransitionRelation&&(f+=` OLD TABLE ${p.triggerBeforeImageTransitionRelation}`),p.triggerAfterImageTransitionRelation&&(f+=` NEW TABLE ${p.triggerAfterImageTransitionRelation}`),m+=s(f," ",` +`)}return m+=s(p.triggerConstraint||p.triggerType==="INSTEAD OF"?"FOR EACH ROW":p.triggerEachRowStatement||"FOR EACH STATEMENT"," ",` +`),p.triggerCondition&&(m+=s(`WHEN ${p.triggerCondition}`," ",` +`)),m},"getTriggerOptions");return{getTriggersScript:o,hydrateTriggers:i((p,m={})=>{var f;return(((f=t.find(p,"triggers"))==null?void 0:f.triggers)||[]).map(h=>{let T=m[h.triggerReferencedTable];if(!T)return{...h,triggerReferencedTable:""};let _=n(T.code||T.collectionName,T.bucketName);return{...h,triggerReferencedTable:_}})},"hydrateTriggers")}}});var kc=N((xS,Uc)=>{"use strict";Uc.exports=()=>({getLocaleProperties:i(e=>{let r=["v13.x","v14.x","v15.x"].includes(e.dbVersion);return r&&e.locale?{locale:e.locale}:!r&&e.locale?{collate:e.locale,characterClassification:e.locale}:{collate:e.collate,characterClassification:e.characterClassification}},"getLocaleProperties")})});var ne=N((MS,Bc)=>{"use strict";var ng=pc(),$c=dc(),x=hc(),{Sequence:LS}=jt();Bc.exports=(t,e,r)=>{let n=r.require("lodash"),{tab:s,commentIfDeactivated:a,checkAllKeysDeactivated:o,divideIntoActivatedAndDeactivated:c,hasType:u,wrap:l,clean:d,wrapComment:p,getFunctionArguments:m,wrapInQuotes:f,getNamePrefixedWithSchemaName:h,getColumnsList:T,getViewData:_}=L()(n),y=_c(),{generateConstraintsString:A,foreignKeysToString:S,foreignActiveKeysToString:I,createKeyConstraint:v,getConstraintsWarnings:w,additionalPropertiesForForeignKey:$}=Tc()({_:n,commentIfDeactivated:a,checkAllKeysDeactivated:o,assignTemplates:y,getColumnsList:T,wrapInQuotes:f}),b=Zt()(n,d),{getFunctionsScript:q}=Ac()({_:n,templates:x,assignTemplates:y,getFunctionArguments:m,getNamePrefixedWithSchemaName:h,wrapComment:p}),{getProceduresScript:G}=bc()({_:n,templates:x,assignTemplates:y,getFunctionArguments:m,getNamePrefixedWithSchemaName:h}),{getSequencesScript:P,createSequenceScript:z,dropSequenceScript:Ae,alterSequenceScript:le}=vc()({_:n,templates:x,assignTemplates:y,getNamePrefixedWithSchemaName:h,wrapInQuotes:f}),{getTableTemporaryValue:F,getTableOptions:Ne}=Rc()({_:n,checkAllKeysDeactivated:o,getColumnsList:T}),{getUserDefinedType:C,isNotPlainType:D}=qc()({_:n,commentIfDeactivated:a,assignTemplates:y,templates:x,getNamePrefixedWithSchemaName:h,wrapComment:p}),{getIndexKeys:B,getIndexOptions:H,getWithOptions:se}=xc()({_:n,wrapInQuotes:f,checkAllKeysDeactivated:o,getColumnsList:T}),{decorateType:qe,decorateDefault:Re,getColumnComments:cr,replaceTypeByVersion:ol}=Lc()({_:n,wrap:l,assignTemplates:y,templates:x,commentIfDeactivated:a,wrapInQuotes:f,wrapComment:p}),{getTriggersScript:Si,hydrateTriggers:Ci}=Fc()({_:n,wrap:l,assignTemplates:y,templates:x,getNamePrefixedWithSchemaName:h,commentIfDeactivated:a}),{getLocaleProperties:cl}=kc()();return{createDatabase(g){if(!g.databaseName)return"";let{locale:E,collate:O,characterClassification:R}=cl(g);return y(x.createDatabase,{name:f(g.databaseName),template:g.template?` TEMPLATE ${g.template}`:"",encoding:g.encoding?` ENCODING ${g.encoding}`:"",locale:E?` LOCALE '${g.locale}'`:"",collate:O?` - LC_COLLATE '${g.collate}'`:"",characterClassification:w?` - LC_CTYPE '${w}'`:"",tablespace:g.tablespace?` - TABLESPACE '${g.tablespace}'`:""})},createSchema({schemaName:g,ifNotExist:E,comments:O,udfs:w,procedures:K,sequences:Z}){let Q=y(x.comment,{object:"SCHEMA",objectName:f(g),comment:m(O)}),te=y(x.createSchema,{name:f(g),ifNotExist:E?" IF NOT EXISTS":"",comment:O?Q:""}),ae=D(g,w),ue=G(g,K);return n.chain([te,ae,ue]).compact().map(n.trim).join(` + LC_COLLATE '${g.collate}'`:"",characterClassification:R?` + LC_CTYPE '${R}'`:"",tablespace:g.tablespace?` + TABLESPACE '${g.tablespace}'`:""})},createSchema({schemaName:g,ifNotExist:E,comments:O,udfs:R,procedures:K,sequences:X}){let W=y(x.comment,{object:"SCHEMA",objectName:f(g),comment:p(O)}),ee=y(x.createSchema,{name:f(g),ifNotExist:E?" IF NOT EXISTS":"",comment:O?W:""}),ie=q(g,R),oe=G(g,K);return n.chain([ee,ie,oe]).compact().map(n.trim).join(` -`).trim().value()},createTable({name:g,columns:E,checkConstraints:O,foreignKeyConstraints:w,schemaData:K,columnDefinitions:Z,keyConstraints:Q,inherits:te,description:ae,ifNotExist:ue,usingMethod:Ce,on_commit:he,partitioning:J,storage_parameter:Oe,table_tablespace_name:Re,temporary:Se,unlogged:we,selectStatement:Le,triggers:xe,partitionOf:le,partitionBounds:Me},Fe){let Ut=ue?" IF NOT EXISTS":"",Ve=h(g,K.schemaName),Ae=y(x.comment,{object:"TABLE",objectName:Ve,comment:m(ae)}),Cr=c(Q.filter(({errorMessage:He})=>!He).map(I(x,Fe)),He=>He.statement),Ar=R(Q.filter(({errorMessage:He})=>He)),dt=`${N(Cr,Fe)}${Ar}`,Wi=le?dt==null?void 0:dt.slice(1):dt,tp=c(w,He=>He.statement),Qi=N(tp,Fe),rp=` -`+Sr(Ve,Z),np=le?x.createTablePartitionOf:x.createTable,sp=le&&!dt?` +`).trim().value()},createTable({name:g,columns:E,checkConstraints:O,foreignKeyConstraints:R,schemaData:K,columnDefinitions:X,keyConstraints:W,inherits:ee,description:ie,ifNotExist:oe,usingMethod:Ee,on_commit:me,partitioning:Z,storage_parameter:be,table_tablespace_name:Ie,temporary:_e,unlogged:ve,selectStatement:De,triggers:we,partitionOf:ce,partitionBounds:xe},Pe){let vt=oe?" IF NOT EXISTS":"",Be=h(g,K.schemaName),Te=y(x.comment,{object:"TABLE",objectName:Be,comment:p(ie)}),ur=c(W.filter(({errorMessage:Ke})=>!Ke).map(v(x,Pe)),Ke=>Ke.statement),lr=w(W.filter(({errorMessage:Ke})=>Ke)),ut=`${A(ur,Pe)}${lr}`,Ai=ce?ut==null?void 0:ut.slice(1):ut,ul=c(R,Ke=>Ke.statement),Ni=A(ul,Pe),ll=` +`+cr(Be,X),pl=ce?x.createTablePartitionOf:x.createTable,ml=ce&&!ut?` `:`, - `,Yi=n.isEmpty(O)?"":l(n.join(O,`, - `),sp,""),ji=le&&!Wi&&!Yi&&!Qi,ip=ji?"":"(",ap=ji?"":")",op=y(np,{temporary:U(Se,we),ifNotExist:Ut,name:Ve,columnDefinitions:le?"":" "+n.join(E,`, - `),keyConstraints:Wi,checkConstraints:Yi,foreignKeyConstraints:Qi,options:Ie({inherits:te,partitioning:J,usingMethod:Ce,on_commit:he,storage_parameter:Oe,table_tablespace_name:Re,selectStatement:Le,partitionBounds:Me}),comment:ae?Ae:"",partitionOf:le?` PARTITION OF ${le} `:"",columnDescriptions:rp,openParenthesis:ip,closeParenthesis:ap}),cp=Vi({dbVersion:K.dbVersion,tableName:Ve,triggers:xe});return a([op,cp].map(n.trim).join(` + `,bi=n.isEmpty(O)?"":l(n.join(O,`, + `),ml,""),Ii=ce&&!Ai&&!bi&&!Ni,dl=Ii?"":"(",fl=Ii?"":")",hl=y(pl,{temporary:F(_e,ve),ifNotExist:vt,name:Be,columnDefinitions:ce?"":" "+n.join(E,`, + `),keyConstraints:Ai,checkConstraints:bi,foreignKeyConstraints:Ni,options:Ne({inherits:ee,partitioning:Z,usingMethod:Ee,on_commit:me,storage_parameter:be,table_tablespace_name:Ie,selectStatement:De,partitionBounds:xe}),comment:ie?Te:"",partitionOf:ce?` PARTITION OF ${ce} `:"",columnDescriptions:ll,openParenthesis:dl,closeParenthesis:fl}),gl=Si({dbVersion:K.dbVersion,tableName:Be,triggers:we});return a([hl,gl].map(n.trim).join(` `).trim()+` -`,{isActivated:Fe})},convertColumnDefinition(g){let E=Jl(g.type,g.dbVersion),O=g.nullable?"":" NOT NULL",w=g.primaryKey?" "+I(x,!0)(g.primaryKeyOptions).statement:"",K=g.unique?" "+I(x,!0)(g.uniqueKeyOptions).statement:"",Z=g.collationRule?` COLLATE "${g.collationRule}"`:"",Q=Array.isArray(g.array_type)&&g.array_type.length>0,te=n.isUndefined(g.default)?"":" DEFAULT "+qe(E,g.default,Q),ae=g.dbVersion>=12&&g.generatedColumn&&g.columnGenerationExpression?y(x.generatedColumnClause,{generationExpression:g.columnGenerationExpression}):"";return a(y(x.columnDefinition,{name:f(g.name),type:Pe(E,g),generatedColumnClause:ae,notNull:O,primaryKey:w,uniqueKey:K,collation:Z,defaultValue:te}),{isActivated:g.isActivated})},createIndex(g,E,O,w=!0){let K=E.unique&&E.index_method==="btree",Z=f(E.indxName),Q=K?" UNIQUE":"",te=E.concurrently?" CONCURRENTLY":"",ae=E.ifNotExist?" IF NOT EXISTS":"",ue=E.only?" ONLY":"",Ce=E.index_method?` USING ${n.toUpper(E.index_method)}`:"",{getDbVersion:he}=L()(n),J=he(n.get(O,"dbVersion","")),Oe=K&&E.nullsDistinct&&J>=15?` - ${E.nullsDistinct}`:"",Re=B(E.index_method==="btree"?E.columns:n.map(E.columns,we=>n.omit(we,"sortOrder","nullsOrder")),w),Se=W(E,w);return a(y(x.index,{unique:Q,concurrently:te,ifNotExist:ae,name:Z,only:ue,using:Ce,keys:Re,options:Se,nullsDistinct:Oe,tableName:h(g,E.schemaName)}),{isActivated:E.isActivated})},createCheckConstraint(g){return y(x.checkConstraint,{name:g.name?`CONSTRAINT ${f(g.name)}`:"",expression:n.trim(g.expression).replace(/^\(([\s\S]*)\)$/,"$1"),noInherit:g.noInherit?" NO INHERIT":""})},createForeignKeyConstraint({name:g,foreignKey:E,primaryTable:O,primaryKey:w,primaryTableActivated:K,foreignTableActivated:Z,foreignSchemaName:Q,primarySchemaName:te,customProperties:ae,isActivated:ue},Ce,he){let J=o(w),Oe=o(E),Re=!J&&!Oe&&K&&Z,{foreignOnDelete:Se,foreignOnUpdate:we,foreignMatch:Le,deferrable:xe,deferrableConstraintCheckTime:le}=M(ae),Me=y(x.createForeignKeyConstraint,{primaryTable:h(O,te||he.schemaName),name:g?`CONSTRAINT ${f(g)}`:"",foreignKey:Re?S(E):b(E),primaryKey:Re?S(w):b(w),onDelete:Se?` ON DELETE ${Se}`:"",onUpdate:we?` ON UPDATE ${we}`:"",match:Le?` MATCH ${Le}`:"",deferrable:xe?` ${xe}`:"",deferrableConstraintCheckTime:xe==="DEFERRABLE"&&le?` ${le}`:""});return{statement:n.trim(Me),isActivated:Re&&ue}},createForeignKey({name:g,foreignTable:E,foreignKey:O,primaryTable:w,primaryKey:K,primaryTableActivated:Z,foreignTableActivated:Q,foreignSchemaName:te,primarySchemaName:ae,customProperties:ue,isActivated:Ce},he,J){let Oe=o(K),Re=o(O),Se=!Oe&&!Re&&Z&&Q,{foreignOnDelete:we,foreignOnUpdate:Le,foreignMatch:xe,deferrable:le,deferrableConstraintCheckTime:Me}=M(ue),Fe=y(x.createForeignKey,{primaryTable:h(w,ae||J.schemaName),foreignTable:h(E,te||J.schemaName),name:g?f(g):"",foreignKey:Se?S(O):b(O),primaryKey:Se?S(K):b(K),onDelete:we?` ON DELETE ${we}`:"",onUpdate:Le?` ON UPDATE ${Le}`:"",match:xe?` MATCH ${xe}`:"",deferrable:le?` ${le}`:"",deferrableConstraintCheckTime:le==="DEFERRABLE"&&Me?` ${Me}`:""});return{statement:n.trim(Fe),isActivated:Se&&Ce}},createView(g,E,O){var Me,Fe,Ut,Ve;let w=h(g.name,g.schemaName),K=y(x.comment,{object:"VIEW",objectName:w,comment:m(g.comment)}),Q=o(g.keys||[])||!O,{columns:te,tables:ae}=_(g.keys),ue=te.map(Ae=>Ae.statement).join(`, - `);if(!Q){let Ae=c(te,Ar=>Ar.statement),Cr=Ae.deactivatedItems.length?a(Ae.deactivatedItems.join(`, - `),{isActivated:!1,isPartOfLine:!0}):"";ue=Ae.activatedItems.join(`, - `)+Cr}let Ce=n.trim(g.selectStatement)?n.trim(s(g.selectStatement)):y(x.viewSelectStatement,{tableName:ae.join(", "),keys:ue}),he=(Me=g.viewOptions)!=null&&Me.check_option?`check_option=${(Fe=g.viewOptions)==null?void 0:Fe.check_option}`:"",J=(Ut=g.viewOptions)!=null&&Ut.security_barrier?"security_barrier":"",Oe=15,{getDbVersion:Re}=L()(n),Se=(Ve=g.viewOptions)!=null&&Ve.security_invoker&&Re(E.dbVersion)>=Oe?"security_invoker":"",we=he||J||Se?` - WITH (${n.compact([he,J,Se]).join(",")})`:"",Le=i(Ae=>Ae.withCheckOption&&Ae.checkTestingScope?` - WITH ${Ae.checkTestingScope} CHECK OPTION`:Ae.withCheckOption?` - WITH CHECK OPTION`:"","getCheckOption"),xe=a(y(x.createView,{name:w,orReplace:g.orReplace?" OR REPLACE":"",temporary:g.temporary?" TEMPORARY":"",checkOption:Le(g),comment:g.comment?K:"",withOptions:we,selectStatement:Ce}),{isActivated:!Q}),le=Vi({dbVersion:g.dbVersion,tableName:w,triggers:g.triggers});return[xe,le].map(n.trim).join(` +`,{isActivated:Pe})},convertColumnDefinition(g){let E=ol(g.type,g.dbVersion),O=g.nullable?"":" NOT NULL",R=g.primaryKey?" "+v(x,!0)(g.primaryKeyOptions).statement:"",K=g.unique?" "+v(x,!0)(g.uniqueKeyOptions).statement:"",X=g.collationRule?` COLLATE "${g.collationRule}"`:"",W=Array.isArray(g.array_type)&&g.array_type.length>0,ee=n.isUndefined(g.default)?"":" DEFAULT "+Re(E,g.default,W),ie=g.dbVersion>=12&&g.generatedColumn&&g.columnGenerationExpression?y(x.generatedColumnClause,{generationExpression:g.columnGenerationExpression}):"";return a(y(x.columnDefinition,{name:f(g.name),type:qe(E,g),generatedColumnClause:ie,notNull:O,primaryKey:R,uniqueKey:K,collation:X,defaultValue:ee}),{isActivated:g.isActivated})},createIndex(g,E,O,R=!0){let K=E.unique&&E.index_method==="btree",X=f(E.indxName),W=K?" UNIQUE":"",ee=E.concurrently?" CONCURRENTLY":"",ie=E.ifNotExist?" IF NOT EXISTS":"",oe=E.only?" ONLY":"",Ee=E.index_method?` USING ${n.toUpper(E.index_method)}`:"",{getDbVersion:me}=L()(n),Z=me(n.get(O,"dbVersion","")),be=K&&E.nullsDistinct&&Z>=15?` + ${E.nullsDistinct}`:"",Ie=B(E.index_method==="btree"?E.columns:n.map(E.columns,ve=>n.omit(ve,"sortOrder","nullsOrder")),R),_e=H(E,R);return a(y(x.index,{unique:W,concurrently:ee,ifNotExist:ie,name:X,only:oe,using:Ee,keys:Ie,options:_e,nullsDistinct:be,tableName:h(g,E.schemaName)}),{isActivated:E.isActivated})},createCheckConstraint(g){return y(x.checkConstraint,{name:g.name?`CONSTRAINT ${f(g.name)}`:"",expression:n.trim(g.expression).replace(/^\(([\s\S]*)\)$/,"$1"),noInherit:g.noInherit?" NO INHERIT":""})},createForeignKeyConstraint({name:g,foreignKey:E,primaryTable:O,primaryKey:R,primaryTableActivated:K,foreignTableActivated:X,foreignSchemaName:W,primarySchemaName:ee,customProperties:ie,isActivated:oe},Ee,me){let Z=o(R),be=o(E),Ie=!Z&&!be&&K&&X,{foreignOnDelete:_e,foreignOnUpdate:ve,foreignMatch:De,deferrable:we,deferrableConstraintCheckTime:ce}=$(ie),xe=y(x.createForeignKeyConstraint,{primaryTable:h(O,ee||me.schemaName),name:g?`CONSTRAINT ${f(g)}`:"",foreignKey:Ie?S(E):I(E),primaryKey:Ie?S(R):I(R),onDelete:_e?` ON DELETE ${_e}`:"",onUpdate:ve?` ON UPDATE ${ve}`:"",match:De?` MATCH ${De}`:"",deferrable:we?` ${we}`:"",deferrableConstraintCheckTime:we==="DEFERRABLE"&&ce?` ${ce}`:""});return{statement:n.trim(xe),isActivated:Ie&&oe}},createForeignKey({name:g,foreignTable:E,foreignKey:O,primaryTable:R,primaryKey:K,primaryTableActivated:X,foreignTableActivated:W,foreignSchemaName:ee,primarySchemaName:ie,customProperties:oe,isActivated:Ee},me,Z){let be=o(K),Ie=o(O),_e=!be&&!Ie&&X&&W,{foreignOnDelete:ve,foreignOnUpdate:De,foreignMatch:we,deferrable:ce,deferrableConstraintCheckTime:xe}=$(oe),Pe=y(x.createForeignKey,{primaryTable:h(R,ie||Z.schemaName),foreignTable:h(E,ee||Z.schemaName),name:g?f(g):"",foreignKey:_e?S(O):I(O),primaryKey:_e?S(K):I(K),onDelete:ve?` ON DELETE ${ve}`:"",onUpdate:De?` ON UPDATE ${De}`:"",match:we?` MATCH ${we}`:"",deferrable:ce?` ${ce}`:"",deferrableConstraintCheckTime:ce==="DEFERRABLE"&&xe?` ${xe}`:""});return{statement:n.trim(Pe),isActivated:_e&&Ee}},createView(g,E,O){var xe,Pe,vt,Be;let R=h(g.name,g.schemaName),K=y(x.comment,{object:"VIEW",objectName:R,comment:p(g.comment)}),W=o(g.keys||[])||!O,{columns:ee,tables:ie}=_(g.keys),oe=ee.map(Te=>Te.statement).join(`, + `);if(!W){let Te=c(ee,lr=>lr.statement),ur=Te.deactivatedItems.length?a(Te.deactivatedItems.join(`, + `),{isActivated:!1,isPartOfLine:!0}):"";oe=Te.activatedItems.join(`, + `)+ur}let Ee=n.trim(g.selectStatement)?n.trim(s(g.selectStatement)):y(x.viewSelectStatement,{tableName:ie.join(", "),keys:oe}),me=(xe=g.viewOptions)!=null&&xe.check_option?`check_option=${(Pe=g.viewOptions)==null?void 0:Pe.check_option}`:"",Z=(vt=g.viewOptions)!=null&&vt.security_barrier?"security_barrier":"",be=15,{getDbVersion:Ie}=L()(n),_e=(Be=g.viewOptions)!=null&&Be.security_invoker&&Ie(E.dbVersion)>=be?"security_invoker":"",ve=me||Z||_e?` + WITH (${n.compact([me,Z,_e]).join(",")})`:"",De=i(Te=>Te.withCheckOption&&Te.checkTestingScope?` + WITH ${Te.checkTestingScope} CHECK OPTION`:Te.withCheckOption?` + WITH CHECK OPTION`:"","getCheckOption"),we=a(y(x.createView,{name:R,orReplace:g.orReplace?" OR REPLACE":"",temporary:g.temporary?" TEMPORARY":"",checkOption:De(g),comment:g.comment?K:"",withOptions:ve,selectStatement:Ee}),{isActivated:!W}),ce=Si({dbVersion:g.dbVersion,tableName:R,triggers:g.triggers});return[we,ce].map(n.trim).join(` `).trim()+` -`},dropView(g){let E={viewName:g};return y(x.dropView,E)},createViewIndex(){return""},createUdt(g){let E=n.map(g.properties,this.convertColumnDefinition);return A(g,E)},getDefaultType(g){return r_[g]},getTypesDescriptors(){return qu},hasType(g){return u(qu,g)},hydrateDatabase({modelData:g}){return g=n.get(g,"0",{}),{databaseName:g.database_name,tablespace:g.tablespace_name,encoding:g.encoding,template:g.template,collate:g.LC_COLLATE,characterClassification:g.LC_CTYPE,dbVersion:g.dbVersion,locale:g.locale}},hydrateColumn({columnDefinition:g,jsonSchema:E,schemaData:O,definitionJsonSchema:w={},parentJsonSchema:K}){let Z=n.includes(["char","varchar","text"],g.type)?E.collationRule:"",Q=["time","timestamp"],te=n.includes(Q,g.type)?E.timePrecision:"",ae=n.includes(Q,g.type)?E.timezone:"",ue=g.type==="interval"?E.intervalOptions:"",{getDbVersion:Ce}=L()(n),he=Ce(O.dbVersion),J=n.omit(v.hydratePrimaryKeyOptions(n.first(E.primaryKeyOptions)||{},g.name,g.isActivated,K),"columns"),Oe=n.omit(v.hydrateUniqueOptions({options:n.first(E.uniqueKeyOptions)||{},columnName:g.name,isActivated:g.isActivated,jsonSchema:K,dbVersion:he}),"columns");return{name:g.name,type:g.type,primaryKey:v.isInlinePrimaryKey(E),primaryKeyOptions:J,unique:v.isInlineUnique(E),uniqueKeyOptions:Oe,nullable:g.nullable,default:g.default,comment:E.refDescription||E.description||w.description,isActivated:g.isActivated,scale:g.scale,precision:g.precision,length:g.length,enum:E.enum,array_type:E.array_type,unit:E.unit,rangeSubtype:E.rangeSubtype,operatorClass:E.operatorClass,collation:E.collation,canonicalFunction:E.canonicalFunction,subtypeDiffFunction:E.subtypeDiffFunction,multiRangeType:E.multiRangeType,schemaName:O.schemaName,underlyingType:E.underlyingType,checkConstraints:E.checkConstraints,typeModifier:E.typeModifier,srid:E.srid,collationRule:Z,timePrecision:te,timezone:ae,intervalOptions:ue,dbVersion:he,generatedColumn:!!E.generatedColumn,columnGenerationExpression:E.columnGenerationExpression}},hydrateJsonSchemaColumn(g,E){return!g.$ref||n.isEmpty(E)||q(E)?g:(g=n.omit(g,"$ref"),{...E,...g})},hydrateIndex(g,E,O){return{...g,schemaName:O.schemaName}},hydrateViewIndex(g){return{}},hydrateCheckConstraint(g){return{name:g.chkConstrName,expression:g.constrExpression,noInherit:g.noInherit}},hydrateSchema(g,E){let O=n.get(E,"modelData.0.dbVersion");return{schemaName:g.name,ifNotExist:g.ifNotExist,comments:g.description,udfs:(E==null?void 0:E.udfs)||[],procedures:(E==null?void 0:E.procedures)||[],sequences:(E==null?void 0:E.sequences)||[],dbVersion:O}},hydrateTable({tableData:g,entityData:E,jsonSchema:O}){let w=E[0],K=n.chain(w.inherits).map(({parentTable:J})=>n.get(g,`relatedSchemas[${J}]`,"")).compact().map(J=>J.code||J.collectionName).join(", ").thru(J=>J?`(${J})`:"").value(),Z=n.first(w.partitioning)||{},Q=v.getKeys(Z.compositePartitionKey,O),te=n.get(g,`relatedSchemas[${w.partitionOf}]`),ae=te?h(te.collectionName,te.bucketName):"",ue=Hi(E,g.relatedSchemas),{getDbVersion:Ce}=L()(n),he=Ce(n.get(g,"dbData.dbVersion",""));return{...g,triggers:ue,partitionOf:ae,keyConstraints:v.getTableKeyConstraints(O,he),inherits:K,selectStatement:n.trim(w.selectStatement),partitioning:n.assign({},Z,{compositePartitionKey:Q}),...n.pick(w,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","table_tablespace_name","partitionBounds")}},hydrateViewColumn(g){return{name:g.name,tableName:g.entityName,alias:g.alias,isActivated:g.isActivated,dbName:g.dbName}},hydrateView({viewData:g,entityData:E,relatedSchemas:O}){let w=E[0],K=Hi(E,O);return{name:g.name,keys:g.keys,comment:w.description,orReplace:w.orReplace,temporary:w.temporary,recursive:w.recursive,viewOptions:w.viewOptions,selectStatement:w.selectStatement,withCheckOption:w.withCheckOption,checkTestingScope:w.withCheckOption?w.checkTestingScope:"",schemaName:g.schemaData.schemaName,triggers:K}},commentIfDeactivated(g,E,O){return g},alterColumnType(g,E,O,w){let K=O;return w.length?K+=`(${w.length})`:w.precision&&w.scale?K+=`(${w.precision},${w.scale})`:w.precision&&(K+=`(${w.precision})`),y(x.alterColumnType,{tableName:g,columnName:E,dataType:K})},setNotNullConstraint(g,E){return y(x.addNotNullConstraint,{tableName:g,columnName:E})},dropNotNullConstraint(g,E){return y(x.dropNotNullConstraint,{tableName:g,columnName:E})},renameColumn(g,E,O){return y(x.renameColumn,{tableName:g,oldColumnName:E,newColumnName:O})},addCheckConstraint(g,E,O){let w={tableName:g,constraintName:E,expression:O};return y(x.addCheckConstraint,w)},dropConstraint(g,E){let O={tableName:g,constraintName:E};return y(x.dropConstraint,O)},updateTableComment(g,E){let O={tableName:g,comment:E};return y(x.updateCommentOnTable,O)},dropTableComment(g){let E={tableName:g,comment:"NULL"};return y(x.updateCommentOnTable,E)},updateColumnComment(g,E){let O={columnName:g,comment:E};return y(x.updateCommentOnColumn,O)},dropColumnComment(g){let E={columnName:g,comment:"NULL"};return y(x.updateCommentOnColumn,E)},updateSchemaComment(g,E){let O={schemaName:g,comment:E};return y(x.updateCommentOnSchema,O)},dropSchemaComment(g){let E={schemaName:g,comment:"NULL"};return y(x.updateCommentOnSchema,E)},updateViewComment(g,E){let O={viewName:g,comment:E};return y(x.updateCommentOnView,O)},dropViewComment(g){let E={viewName:g,comment:"NULL"};return y(x.updateCommentOnView,E)},createSchemaOnly(g){let E={schemaName:g};return y(x.createSchemaOnly,E)},dropSchema(g){let E={schemaName:g};return y(x.dropSchema,E)},dropTable(g){let E={tableName:g};return y(x.dropTable,E)},addColumn(g,E){let O={tableName:g,columnDefinition:E};return y(x.addColumn,O)},dropColumn(g,E){let O={tableName:g,columnName:E};return y(x.dropColumn,O)},dropDomain(g){let E={udtName:g};return y(x.dropDomain,E)},dropType(g){let E={udtName:g};return y(x.dropType,E)},alterTypeAddAttribute(g,E){let O={udtName:g,columnDefinition:E};return y(x.alterTypeAddAttribute,O)},alterTypeDropAttribute(g,E){let O={udtName:g,attributeName:E};return y(x.alterTypeDropAttribute,O)},alterTypeRenameAttribute(g,E,O){let w={udtName:g,oldAttributeName:E,newAttributeName:O};return y(x.alterTypeRenameAttribute,w)},alterTypeChangeAttributeType(g,E,O){let w={udtName:g,attributeName:E,newDataType:O};return y(x.alterTypeChangeAttributeType,w)},dropForeignKey(g,E){let O={tableName:g,fkConstraintName:E};return y(x.dropForeignKey,O)},createKeyConstraint(g,E,O){let w=I(x,E)(O);return{statement:y(x.addPkConstraint,{constraintStatement:(w.statement||"").trim(),tableName:g}),isActivated:w.isActivated}},dropKeyConstraint(g,E){let O={tableName:g,constraintName:E};return y(x.dropConstraint,O)},createSchemaSequences({schemaName:g,sequences:E}){return P({schemaName:g,sequences:E})},createSchemaSequence({schemaName:g,sequence:E}){return X({schemaName:g,sequence:E})},dropSchemaSequence({schemaName:g,sequence:E}){return ve({schemaName:g,sequence:E})},alterSchemaSequence({schemaName:g,sequence:E,oldSequence:O}){return me({schemaName:g,sequence:E,oldSequence:O})},dropIndex({indexName:g}){let E={indexName:g};return y(x.dropIndex,E)},alterIndexRename({schemaName:g,oldIndexName:E,newIndexName:O}){let w=f(g),K=h(f(E),w),Z=f(O),Q={oldIndexName:K,newIndexName:Z};return y(x.alterIndexRename,Q)},alterIndexTablespace({schemaName:g,indexName:E,tablespaceName:O}){let w=f(g),Z={indexName:h(f(E),w),tablespaceName:O};return y(x.alterIndexTablespace,Z)},alterIndexStorageParams({schemaName:g,indexName:E,index:O}){let w=f(g),K=h(f(E),w),Z=ie(O),Q={indexName:K,options:Z};return y(x.alterIndexStorageParams,Q)},reindexIndex({schemaName:g,indexName:E}){let O=f(g),K={indexName:h(f(E),O)};return y(x.reindexIndex,K)}}}});var Mu=C((XA,Lu)=>{var{getModifySchemaCommentsScriptDtos:n_}=tu(),{AlterScriptDto:Pu}=ne(),s_=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{wrapInQuotes:s}=L()(r),a=n.createSchemaOnly(s(e));return Pu.getInstance([a],!0,!1)},"getAddContainerScriptDto"),i_=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{wrapInQuotes:s}=L()(r),a=n.dropSchema(s(e));return Pu.getInstance([a],!0,!0)},"getDeleteContainerScriptDto"),a_=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t);return[...n_(r,n)(e)]},"getModifyContainerScriptDtos");Lu.exports={getAddContainerScriptDto:s_,getDeleteContainerScriptDto:i_,getModifyContainerScriptDtos:a_}});var Uu=C((eN,Fu)=>{var{AlterCollectionDto:JA}=Ge(),{AlterScriptDto:mr}=ne(),o_=i(t=>e=>{var o;let r=(o=e==null?void 0:e.compMod)==null?void 0:o.chkConstr;if(!r)return[];let n=r.new||[],s=r.old||[];return t.chain([...n,...s]).map(c=>c.chkConstrName).uniq().value().map(c=>({old:t.find(s,{chkConstrName:c}),new:t.find(n,{chkConstrName:c})}))},"mapCheckConstraintNamesToChangeHistory"),c_=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>a.old&&!a.new).map(a=>{let o=s(a.old.chkConstrName);return e.dropConstraint(n,o)}).map(a=>mr.getInstance([a],!0,!0))},"getDropCheckConstraintScriptDtos"),u_=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>a.new&&!a.old).map(a=>{let{chkConstrName:o,constrExpression:c}=a.new;return e.addCheckConstraint(n,s(o),c)}).map(a=>mr.getInstance([a],!0,!1))},"getAddCheckConstraintScriptDtos"),l_=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>{if(a.old&&a.new){let o=a.old.constrExpression,c=a.new.constrExpression;return o!==c}return!1}).map(a=>{let{chkConstrName:o}=a.old,c=e.dropConstraint(n,s(o)),{chkConstrName:u,constrExpression:l}=a.new,p=e.addCheckConstraint(n,s(u),l);return[mr.getInstance([c],!0,!0),mr.getInstance([p],!0,!1)]}).flat()},"getUpdateCheckConstraintScriptDtos"),p_=i((t,e)=>r=>{let{getFullTableName:n}=L()(t),s=n(r),a=o_(t)(r),o=u_(t,e)(a,s),c=c_(t,e)(a,s),u=l_(t,e)(a,s);return[...o,...c,...u]},"getModifyCheckConstraintScriptDtos");Fu.exports={getModifyCheckConstraintScriptDtos:p_}});var Bu=C((nN,$u)=>{var{AlterScriptDto:ku}=ne(),{AlterCollectionDto:rN}=Ge(),m_=i((t,e)=>r=>{var m;let{getFullTableName:n,wrapComment:s}=L()(t),a=(m=r==null?void 0:r.role.compMod)==null?void 0:m.description;if(!a)return;let{old:o,new:c}=a;if(!c||c===o)return;let u=n(r),l=s(c),p=e.updateTableComment(u,l);return ku.getInstance([p],!0,!1)},"getUpdatedCommentOnCollectionScriptDto"),d_=i((t,e)=>r=>{var l;let{getFullTableName:n}=L()(t),s=(l=r==null?void 0:r.role.compMod)==null?void 0:l.description;if(!s)return;let{old:a,new:o}=s;if(!a||o)return;let c=n(r),u=e.dropTableComment(c);return ku.getInstance([u],!0,!0)},"getDeletedCommentOnCollectionScriptDto"),f_=i((t,e)=>r=>{let n=m_(t,e)(r),s=d_(t,e)(r);return[n,s].filter(Boolean)},"getModifyEntityCommentsScriptDtos");$u.exports={getModifyEntityCommentsScriptDtos:f_}});var Gu=C((iN,Ku)=>{var{AlterScriptDto:h_}=ne(),g_=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.length,a=r==null?void 0:r.length;return s!==a},"hasLengthChanged"),y_=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.precision,a=r==null?void 0:r.precision,o=n==null?void 0:n.scale,c=r==null?void 0:r.scale;return s!==a||o!==c},"hasPrecisionOrScaleChanged"),__=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:a}=L()(t),o=s(r);return t.toPairs(r.properties).filter(([c,u])=>{let l=n(u.compMod,["type","mode"]);if(!l){let p=u.compMod.oldField.name,m=g_(r,p,u),d=y_(r,p,u);return m||d}return l}).map(([c,u])=>{let l=u.compMod.newField.mode||u.compMod.newField.type,p=a(c),m=t.pick(u,["length","precision","scale"]);return e.alterColumnType(o,p,l,m)}).map(c=>h_.getInstance([c],!0,!1))},"getUpdateTypesScriptDtos");Ku.exports={getUpdateTypesScriptDtos:__}});var Wu=C((oN,Hu)=>{var{AlterScriptDto:Vu}=ne(),E_=i((t,e)=>r=>{let{getFullTableName:n,wrapInQuotes:s}=L()(t),a=n(r),o=r.required||[],c=r.role.required||[],u=t.difference(o,c),l=t.difference(c,o),p=t.toPairs(r.properties).filter(([d,f])=>{let h=f.compMod.oldField.name,T=l.includes(h);return u.includes(d)&&!T}).map(([d])=>e.setNotNullConstraint(a,s(d))).map(d=>Vu.getInstance([d],!0,!1)),m=t.toPairs(r.properties).filter(([d,f])=>{let h=f.compMod.oldField.name,T=l.includes(h),_=u.includes(d);return T&&!_}).map(([d])=>e.dropNotNullConstraint(a,s(d))).map(d=>Vu.getInstance([d],!0,!0));return[...p,...m]},"getModifyNonNullColumnsScriptDtos");Hu.exports={getModifyNonNullColumnsScriptDtos:E_}});var ju=C((uN,Yu)=>{var{AlterScriptDto:Qu}=ne(),T_=i((t,e)=>r=>{let{getFullColumnName:n,wrapComment:s}=L()(t);return t.toPairs(r.properties).filter(([a,o])=>{var p;let c=o.description,u=o.compMod.oldField.name,l=(p=r.role.properties[u])==null?void 0:p.description;return c&&(!l||c!==l)}).map(([a,o])=>{let c=o.description,u=s(c),l=n(r,a);return e.updateColumnComment(l,u)}).map(a=>Qu.getInstance([a],!0,!1))},"getUpdatedCommentOnColumnScriptDtos"),S_=i((t,e)=>r=>{let{getFullColumnName:n}=L()(t);return t.toPairs(r.properties).filter(([s,a])=>{var l;let o=a.description,c=a.compMod.oldField.name;return((l=r.role.properties[c])==null?void 0:l.description)&&!o}).map(([s,a])=>{let o=n(r,s);return e.dropColumnComment(o)}).map(s=>Qu.getInstance([s],!0,!0))},"getDeletedCommentOnColumnScriptDtos"),C_=i((t,e)=>r=>{let n=T_(t,e)(r),s=S_(t,e)(r);return[...n,...s]},"getModifiedCommentOnColumnScriptDtos");Yu.exports={getModifiedCommentOnColumnScriptDtos:C_}});var Xu=C((pN,zu)=>{var{AlterScriptDto:A_}=ne(),N_=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:a}=L()(t),o=s(r);return t.values(r.properties).filter(c=>n(c.compMod,["name"])).map(c=>{let u=a(c.compMod.oldField.name),l=a(c.compMod.newField.name);return e.renameColumn(o,u,l)}).map(c=>A_.getInstance([c],!0,!1))},"getRenameColumnScriptDtos");zu.exports={getRenameColumnScriptDtos:N_}});var ei=C((dN,Zu)=>{var Zs=class Zs{didTransitionHappen;wasPkChangedInTransition;static noTransition(){return{didTransitionHappen:!1}}static transition(e){return{didTransitionHappen:!0,wasPkChangedInTransition:e}}};i(Zs,"KeyTransitionDto");var zs=Zs,Js=class Js{script;isDropScript;fullTableName;isActivated;constructor(e,r,n,s){this.script=e,this.isDropScript=n,this.fullTableName=r,this.isActivated=s}};i(Js,"KeyScriptModificationDto");var Xs=Js;Zu.exports={KeyScriptModificationDto:Xs,KeyTransitionDto:zs}});var nl=C((TN,rl)=>{var{AlterScriptDto:b_}=ne(),{AlterCollectionDto:hN,AlterCollectionColumnDto:gN,AlterCollectionRoleCompModPKDto:yN,AlterCollectionColumnKeyOptionDto:_N,AlterCollectionRoleCompModPrimaryKey:EN}=Ge(),{KeyTransitionDto:Ee,KeyScriptModificationDto:dr}=ei(),ct=1,ti=i(t=>`${t}_pkey`,"getDefaultConstraintName"),Ju=i(t=>({constraintName:t.constraintName,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexInclude:t.indexInclude}),"extractOptionsForComparisonWithRegularPkOptions"),ut=i(t=>(t.primaryKeyOptions||[]).map(r=>Ju(r)),"getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions"),fr=i(t=>[Ju(t)].filter(r=>Object.values(r).some(Boolean)),"getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions"),v_=i(t=>e=>{var p,m;let n=(((m=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:m.primaryKey)||{}).old||[],s=n.flatMap(d=>d.compositePrimaryKey.map(f=>f.keyId));if(s.length!==ct)return Ee.noTransition();let a=s[0],o=Object.values(e.properties).find(d=>d.GUID===a);if(!o||!((o==null?void 0:o.primaryKey)&&!(o!=null&&o.compositePrimaryKey)))return Ee.noTransition();let u=ut(o),l=n.some(d=>{if(d.compositePrimaryKey.length!==ct)return!1;let f=fr(d);return t(f).differenceWith(u,t.isEqual).isEmpty()});return Ee.transition(!l)},"wasCompositePkChangedInTransitionFromCompositeToRegular"),I_=i(t=>e=>{var p,m;let n=(((m=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:m.primaryKey)||{}).new||[],s=n.flatMap(d=>d.compositePrimaryKey.map(f=>f.keyId));if(s.length!==ct)return Ee.noTransition();let a=s[0],o=Object.values(e.role.properties).find(d=>d.GUID===a);if(!o||!((o==null?void 0:o.primaryKey)&&!(o!=null&&o.compositePrimaryKey)))return Ee.noTransition();let u=ut(o),l=n.some(d=>{if(d.compositePrimaryKey.length!==ct)return!1;let f=fr(d);return t(f).differenceWith(u,t.isEqual).isEmpty()});return Ee.transition(!l)},"wasCompositePkChangedInTransitionFromRegularToComposite"),O_=i((t,e)=>t.constraintName?t.constraintName:ti(e),"getConstraintNameForCompositePk"),R_=i(t=>(e,r,n)=>{let s=O_(e,r),a=t.toPairs(n.role.properties).filter(([l,p])=>!!e.compositePrimaryKey.find(m=>m.keyId===p.GUID)).map(([l,p])=>({name:l,isActivated:p.isActivated})),o="",c="",u=[];return e.indexStorageParameters&&(o=e.indexStorageParameters),e.indexTablespace&&(c=e.indexTablespace),e.indexInclude&&(u=t.toPairs(n.role.properties).filter(([l,p])=>!!e.indexInclude.find(m=>m.keyId===p.GUID)).map(([l,p])=>({name:l,isActivated:p.isActivated}))),{name:s,keyType:"PRIMARY KEY",columns:a,include:u,storageParameters:o,tablespace:c}},"getCreateCompositePKDDLProviderConfig"),w_=i((t,e)=>r=>{var f,h;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a}=L()(t),o=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},c=o.new||[],u=o.old||[];if(c.length===0&&u.length===0)return[];let l=I_(t)(r);if(l.didTransitionHappen&&!l.wasPkChangedInTransition)return[];if(c.length===u.length&&t(u).differenceWith(c,t.isEqual).isEmpty())return[];let p=s(r),m=n(p),d=a(p);return c.map(T=>{let _=R_(t)(T,d,r),y=e.createKeyConstraint(m,r.isActivated,_);return new dr(y.statement,m,!1,y.isActivated)}).filter(T=>!!T.script)},"getAddCompositePkScriptDtos"),D_=i((t,e)=>r=>{var h,T;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.primaryKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let p=v_(t)(r);if(p.didTransitionHappen&&!p.wasPkChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let m=s(r),d=n(m),f=a(m);return l.map(_=>{let y=ti(f);_.constraintName&&(y=_.constraintName);let N=o(y),S=e.dropKeyConstraint(d,N);return new dr(S,d,!0,r.isActivated)}).filter(_=>!!_.script)},"getDropCompositePkScriptDtos"),q_=i((t,e)=>r=>{let n=D_(t,e)(r),s=w_(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyCompositePkScriptDtos"),el=i((t,e)=>{let r=t.primaryKeyOptions;if(r!=null&&r.length&&(r==null?void 0:r.length)>0){let n=r[0];if(n.constraintName)return n.constraintName}return ti(e)},"getConstraintNameForRegularPk"),x_=i(t=>(e,r,n,s)=>{let a=el(r,n),o=[{name:e,isActivated:r.isActivated}],c="",u="",l=[],p=r.primaryKeyOptions;if(p!=null&&p.length&&(p==null?void 0:p.length)>0){let m=p[0];m.indexStorageParameters&&(c=m.indexStorageParameters),m.indexTablespace&&(u=m.indexTablespace),m.indexInclude&&(l=t.toPairs(s.role.properties).filter(([d,f])=>!!m.indexInclude.find(h=>h.keyId===f.GUID)).map(([d,f])=>({name:d,isActivated:f.isActivated})))}return{name:a,keyType:"PRIMARY KEY",columns:o,include:l,storageParameters:c,tablespace:u}},"getCreateRegularPKDDLProviderConfig"),P_=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.primaryKey&&!e.compositePrimaryKey,o=!!(s!=null&&s.primaryKey);return a&&!o},"wasFieldChangedToBeARegularPk"),L_=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.primaryKey&&!e.compositePrimaryKey,o=!!(s!=null&&s.primaryKey);if(!(a&&o))return Ee.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},u=c.new||[],l=c.old||[],p=l.some(T=>T.compositePrimaryKey.some(_=>_.keyId===s.GUID)),m=u.some(T=>T.compositePrimaryKey.some(_=>_.keyId===e.GUID));if(a&&(p&&!m)){let T=ut(e),_=l.some(y=>{if(y.compositePrimaryKey.length!==ct)return!1;let N=fr(y);return t(N).differenceWith(T,t.isEqual).isEmpty()});return Ee.transition(!_)}return Ee.noTransition()},"wasRegularPkChangedInTransitionFromCompositeToRegular"),M_=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=s.primaryKey&&!s.compositePrimaryKey,o=!!(e!=null&&e.primaryKey);if(!(a&&o))return Ee.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},u=c.new||[],p=(c.old||[]).some(T=>T.compositePrimaryKey.some(_=>_.keyId===s.GUID)),d=u.some(T=>T.compositePrimaryKey.some(_=>_.keyId===e.GUID))&&!p;if(a&&d){let T=ut(s),_=u.some(y=>{if(y.compositePrimaryKey.length!==ct)return!1;let N=fr(y);return t(N).differenceWith(T,t.isEqual).isEmpty()});return Ee.transition(!_)}return Ee.noTransition()},"wasRegularPkChangedInTransitionFromRegularToComposite"),F_=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey),o=!e.primaryKey&&!e.compositePrimaryKey;return a&&o},"isFieldNoLongerARegularPk"),tl=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n]||{},a=e.primaryKey&&!e.compositePrimaryKey,o=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey);if(!(a&&o))return!1;let c=ut(e),u=ut(s);return!t(u).differenceWith(c,t.isEqual).isEmpty()},"wasRegularPkModified"),U_=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a}=L()(t),o=s(r),c=n(o),u=a(o);return t.toPairs(r.properties).filter(([l,p])=>{if(P_(t)(p,r))return!0;let m=L_(t)(p,r);return m.didTransitionHappen?m.wasPkChangedInTransition:tl(t)(p,r)}).map(([l,p])=>{let m=x_(t)(l,p,u,r),d=e.createKeyConstraint(c,r.isActivated,m);return new dr(d.statement,c,!1,d.isActivated)}).filter(l=>!!l.script)},"getAddPkScriptDtos"),k_=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=s(r),u=n(c),l=a(c);return t.toPairs(r.properties).filter(([p,m])=>{if(F_(t)(m,r))return!0;let d=M_(t)(m,r);return d.didTransitionHappen?d.wasPkChangedInTransition:tl(t)(m,r)}).map(([p,m])=>{let d=m.compMod.oldField.name,f=r.role.properties[d],h=o(el(f,l)),T=e.dropKeyConstraint(u,h);return new dr(T,u,!0,r.isActivated)}).filter(p=>!!p.script)},"getDropPkScriptDto"),$_=i((t,e)=>r=>{let n=k_(t,e)(r),s=U_(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyPkScriptDtos"),B_=i(t=>t.sort((e,r)=>e.fullTableName===r.fullTableName?Number(r.isDropScript)-Number(e.isDropScript):e.fullTableNamer=>{let n=q_(t,e)(r),s=$_(t,e)(r),a=[...n,...s];return B_(a).map(c=>b_.getInstance([c.script],c.isActivated,c.isDropScript)).filter(Boolean)},"getModifyPkConstraintsScriptDtos");rl.exports={getModifyPkConstraintsScriptDtos:K_}});var cl=C((IN,ol)=>{var{AlterScriptDto:G_}=ne(),{AlterCollectionDto:CN,AlterCollectionColumnDto:AN,AlterCollectionRoleCompModUniqueKeyDto:NN,AlterCollectionColumnKeyOptionDto:bN,AlterCollectionRoleCompModUniqueKey:vN}=Ge(),{KeyTransitionDto:Te,KeyScriptModificationDto:hr}=ei(),lt=1,ri=i(t=>`${t}_ukey`,"getDefaultConstraintName"),sl=i(t=>({constraintName:t.constraintName,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexInclude:t.indexInclude}),"extractOptionsForComparisonWithRegularUniqueKeyOptions"),pt=i(t=>(t.uniqueKeyOptions||[]).map(r=>sl(r)),"getCustomPropertiesOfRegularUniqueKeyForComparisonWithRegularUniqueKeyOptions"),gr=i(t=>[sl(t)].filter(r=>Object.values(r).some(Boolean)),"getCustomPropertiesOfCompositeUniqueKeyForComparisonWithRegularUniqueKeyOptions"),V_=i(t=>e=>{var p,m;let n=(((m=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:m.uniqueKey)||{}).old||[],s=n.flatMap(d=>d.compositeUniqueKey.map(f=>f.keyId));if(s.length!==lt)return Te.noTransition();let a=s[0],o=Object.values(e.properties).find(d=>d.GUID===a);if(!o||!((o==null?void 0:o.unique)&&!(o!=null&&o.compositeUniqueKey)))return Te.noTransition();let u=pt(o),l=n.some(d=>{if(d.compositeUniqueKey.length!==lt)return!1;let f=gr(d);return t(f).differenceWith(u,t.isEqual).isEmpty()});return Te.transition(!l)},"wasCompositeUniqueKeyChangedInTransitionFromCompositeToRegular"),H_=i(t=>e=>{var p,m;let n=(((m=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:m.uniqueKey)||{}).new||[],s=n.flatMap(d=>d.compositeUniqueKey.map(f=>f.keyId));if(s.length!==lt)return Te.noTransition();let a=s[0],o=Object.values(e.role.properties).find(d=>d.GUID===a);if(!o||!((o==null?void 0:o.unique)&&!(o!=null&&o.compositeUniqueKey)))return Te.noTransition();let u=pt(o),l=n.some(d=>{if(d.compositeUniqueKey.length!==lt)return!1;let f=gr(d);return t(f).differenceWith(u,t.isEqual).isEmpty()});return Te.transition(!l)},"wasCompositeUniqueKeyChangedInTransitionFromRegularToComposite"),W_=i((t,e)=>t.constraintName?t.constraintName:ri(e),"getConstraintNameForCompositeUniqueKey"),Q_=i(t=>(e,r,n,s)=>{let{clean:a,getDbVersion:o}=L()(t),c=pr()(t,a),u=W_(e,r),l=t.toPairs(n.role.properties).filter(([_,y])=>!!e.compositeUniqueKey.find(N=>N.keyId===y.GUID)).map(([_,y])=>({name:_,isActivated:y.isActivated})),p="",m="",d=[],f=e.deferrable,h=e.deferrableConstraintCheckTime;e.indexStorageParameters&&(p=e.indexStorageParameters),e.indexTablespace&&(m=e.indexTablespace),e.indexInclude&&(d=t.toPairs(n.role.properties).filter(([_,y])=>!!e.indexInclude.find(N=>N.keyId===y.GUID)).map(([_,y])=>({name:_,isActivated:y.isActivated})));let T=c.getUniqueKeyType(e,o(s));return{name:u,keyType:T,columns:l,include:d,storageParameters:p,tablespace:m,deferrable:f,deferrableConstraintCheckTime:h}},"getCreateCompositeUniqueKeyDDLProviderConfig"),Y_=i((t,e)=>(r,n)=>{var h,T;let{getFullCollectionName:s,getSchemaOfAlterCollection:a,getEntityName:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.uniqueKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let p=H_(t)(r);if(p.didTransitionHappen&&!p.wasUniqueKeyChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let m=a(r),d=s(m),f=o(m);return u.map(_=>{let y=Q_(t)(_,f,r,n),N=e.createKeyConstraint(d,r.isActivated,y);return new hr(N.statement,d,!1,N.isActivated)}).filter(_=>!!_.script)},"getAddCompositeUniqueKeyScriptDtos"),j_=i((t,e)=>r=>{var h,T;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.uniqueKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let p=V_(t)(r);if(p.didTransitionHappen&&!p.wasUniqueKeyChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let m=s(r),d=n(m),f=a(m);return l.map(_=>{let y=ri(f);_.constraintName&&(y=_.constraintName);let N=o(y),S=e.dropKeyConstraint(d,N);return new hr(S,d,!0,r.isActivated)}).filter(_=>!!_.script)},"getDropCompositeUniqueKeyScriptDtos"),z_=i((t,e)=>(r,n)=>{let s=j_(t,e)(r),a=Y_(t,e)(r,n);return[...s,...a].filter(Boolean)},"getModifyCompositeUniqueKeyScriptDtos"),il=i((t,e)=>{let r=t.uniqueKeyOptions;if(r!=null&&r.length&&(r==null?void 0:r.length)>0){let n=r[0];if(n.constraintName)return n.constraintName}return ri(e)},"getConstraintNameForRegularUniqueKey"),X_=i(t=>(e,r,n,s,a)=>{let{clean:o,getDbVersion:c}=L()(t),u=pr()(t,o),l=il(r,n),p=[{name:e,isActivated:r.isActivated}],m="",d="",f=[],h="",T="",_="",y=r.uniqueKeyOptions;if(y!=null&&y.length&&(y==null?void 0:y.length)>0){let S=y[0];S.indexStorageParameters&&(m=S.indexStorageParameters),S.indexTablespace&&(d=S.indexTablespace),S.indexInclude&&(f=t.toPairs(s.role.properties).filter(([b,I])=>!!S.indexInclude.find(R=>R.keyId===I.GUID)).map(([b,I])=>({name:b,isActivated:I.isActivated}))),h=S.deferrable,T=S.deferrableConstraintCheckTime,_=S.nullsDistinct}let N=u.getUniqueKeyType({nullsDistinct:_},c(a));return{name:l,keyType:N,columns:p,include:f,storageParameters:m,tablespace:d,deferrable:h,deferrableConstraintCheckTime:T}},"getCreateRegularUniqueKeyDDLProviderConfig"),Z_=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)||s.compositeUniqueKey;return a&&!o},"wasFieldChangedToBeARegularUniqueKey"),J_=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)||s.compositeUniqueKey;if(!(a&&o))return Te.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.uniqueKey)||{},u=c.new||[],l=c.old||[],p=l.some(T=>T.compositeUniqueKey.some(_=>_.keyId===s.GUID)),m=u.some(T=>T.compositeUniqueKey.some(_=>_.keyId===e.GUID));if(a&&(p&&!m)){let T=pt(e),_=l.some(y=>{if(y.compositeUniqueKey.length!==lt)return!1;let N=gr(y);return t(N).differenceWith(T,t.isEqual).isEmpty()});return Te.transition(!_)}return Te.noTransition()},"wasRegularUniqueKeyChangedInTransitionFromCompositeToRegular"),eE=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=s.unique&&!s.compositeUniqueKey,o=!!(e!=null&&e.unique);if(!(a&&o))return Te.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.uniqueKey)||{},u=c.new||[],p=(c.old||[]).some(T=>T.compositeUniqueKey.some(_=>_.keyId===s.GUID)),d=u.some(T=>T.compositeUniqueKey.some(_=>_.keyId===e.GUID))&&!p;if(a&&d){let T=pt(s),_=u.some(y=>{if(y.compositeUniqueKey.length!==lt)return!1;let N=gr(y);return t(N).differenceWith(T,t.isEqual).isEmpty()});return Te.transition(!_)}return Te.noTransition()},"wasRegularUniqueKeyChangedInTransitionFromRegularToComposite"),tE=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=(s==null?void 0:s.unique)&&!(s!=null&&s.compositeUniqueKey),o=!e.unique&&!e.compositeUniqueKey;return a&&o},"isFieldNoLongerARegularUniqueKey"),al=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n]||{},a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)&&!(s!=null&&s.compositeUniqueKey);if(!(a&&o))return!1;let c=pt(e),u=pt(s);return!t(u).differenceWith(c,t.isEqual).isEmpty()},"wasRegularUniqueKeyModified"),rE=i((t,e)=>(r,n)=>{let{getFullCollectionName:s,getSchemaOfAlterCollection:a,getEntityName:o}=L()(t),c=a(r),u=s(c),l=o(c);return t.toPairs(r.properties).filter(([p,m])=>{if(Z_(t)(m,r))return!0;let d=J_(t)(m,r);return d.didTransitionHappen?d.wasUniqueKeyChangedInTransition:al(t)(m,r)}).map(([p,m])=>{let d=X_(t)(p,m,l,r,n),f=e.createKeyConstraint(u,r.isActivated,d);return new hr(f.statement,u,!1,f.isActivated)}).filter(p=>!!p.script)},"getAddUniqueKeyScriptDtos"),nE=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=s(r),u=n(c),l=a(c);return t.toPairs(r.properties).filter(([p,m])=>{if(tE(t)(m,r))return!0;let d=eE(t)(m,r);return d.didTransitionHappen?d.wasUniqueKeyChangedInTransition:al(t)(m,r)}).map(([p,m])=>{let d=m.compMod.oldField.name,f=r.role.properties[d],h=o(il(f,l)),T=e.dropKeyConstraint(u,h);return new hr(T,u,!0,r.isActivated)}).filter(p=>!!p.script)},"getDropUniqueKeyScriptDto"),sE=i((t,e)=>(r,n)=>{let s=nE(t,e)(r),a=rE(t,e)(r,n);return[...s,...a].filter(Boolean)},"getModifyUniqueKeyScriptDtos"),iE=i(t=>t.sort((e,r)=>e.fullTableName===r.fullTableName?Number(r.isDropScript)-Number(e.isDropScript):e.fullTableName({collection:r,dbVersion:n})=>{let s=z_(t,e)(r,n),a=sE(t,e)(r,n),o=[...s,...a];return iE(o).map(u=>G_.getInstance([u.script],u.isActivated,u.isDropScript)).filter(Boolean)},"getModifyUniqueKeyConstraintsScriptDtos");ol.exports={getModifyUniqueKeyConstraintsScriptDtos:aE}});var gl=C((DN,hl)=>{var{AlterCollectionDto:RN}=Ge(),{AlterIndexDto:wN}=Ps(),{AlterScriptDto:mt}=ne(),oE=i(({_:t})=>({columnId:e,collection:r})=>{var c,u,l;let n=t.toPairs(((c=r==null?void 0:r.role)==null?void 0:c.properties)||(r==null?void 0:r.properties)||{}).map(([p,m])=>({...m,name:p})),s=(((l=(u=r==null?void 0:r.role)==null?void 0:u.compMod)==null?void 0:l.oldProperties)||[]).map(p=>({...p,GUID:p.id})),o=(n.length>0?n:s).find(p=>p.GUID===e);if(o)return o.name},"getColumnNameById"),ul=i(({_:t})=>({columns:e,collection:r})=>(e||[]).map(n=>({...n,name:oE({_:t})({columnId:n.keyId,collection:r})})).filter(n=>!!n.name),"setNamesToColumns"),cE=i(({_:t})=>({index:e,collection:r})=>{let{getSchemaNameFromCollection:n}=L()(t),s=n({collection:r}),a=ul({_:t})({columns:e.columns,collection:r}),o=ul({_:t})({columns:e.include,collection:r});return{...e,schemaName:s,columns:a,include:o}},"mapIndexToFeIndexDto"),ll=i(({_:t})=>({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})=>{let s=t.pick(r,n),a=t.pick(e,n);return!t.isEqual(s,a)},"areIndexesDifferent"),uE=i(({_:t})=>({oldIndex:e,newIndex:r})=>{let n=["index_method","columns","include","nullsDistinct","where"];return ll({_:t})({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})},"shouldDropAndRecreateIndex"),lE=i(({_:t})=>({oldIndex:e,newIndex:r})=>{let n=["indxName","index_tablespace_name","index_storage_parameter"];return ll({_:t})({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})},"shouldAlterIndex"),ni=i(({oldIndex:t,newIndex:e})=>t.id===e.id||t.indxName===e.indxName,"areOldIndexDtoAndNewIndexDtoDescribingSameDatabaseIndex"),pl=i(({_:t,ddlProvider:e})=>({index:r,collection:n,additionalDataForDdlProvider:s})=>{let{dbData:a,tableName:o,isParentActivated:c}=s,u=cE({_:t})({index:r,collection:n}),l=e.createIndex(o,u,a,c),p=u.isActivated&&c;return mt.getInstance([l],p,!1)},"getCreateIndexScriptDto"),ml=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l;let s=((o=r==null?void 0:r.role)==null?void 0:o.Indxs)||[],a=((l=(u=(c=r==null?void 0:r.role)==null?void 0:c.compMod)==null?void 0:u.Indxs)==null?void 0:l.old)||[];return s.filter(p=>!a.find(d=>ni({oldIndex:d,newIndex:p}))).map(p=>pl({_:t,ddlProvider:e})({index:p,collection:r,additionalDataForDdlProvider:n})).filter(Boolean)},"getAddedIndexesScriptDtos"),dl=i(({_:t,ddlProvider:e})=>({index:r,additionalDataForDdlProvider:n})=>{let{getNamePrefixedWithSchemaName:s}=L()(t),{isParentActivated:a,schemaName:o}=n,c=s(r.indxName,o),u=e.dropIndex({indexName:c}),l=r.isActivated&&a;return mt.getInstance([u],l,!0)},"getDeleteIndexScriptDto"),pE=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l,p,m;let s=((u=(c=(o=r==null?void 0:r.role)==null?void 0:o.compMod)==null?void 0:c.Indxs)==null?void 0:u.new)||[];return(((m=(p=(l=r==null?void 0:r.role)==null?void 0:l.compMod)==null?void 0:p.Indxs)==null?void 0:m.old)||[]).filter(d=>!s.find(h=>ni({oldIndex:d,newIndex:h}))).map(d=>dl({_:t,ddlProvider:e})({index:d,additionalDataForDdlProvider:n})).filter(Boolean)},"getDeletedIndexesScriptDtos"),mE=i(({_:t,ddlProvider:e})=>({newIndex:r,oldIndex:n,additionalDataForDdlProvider:s})=>{let a=[],{isParentActivated:o,schemaName:c}=s,u=r.isActivated&&o;if(!t.isEqual(r.indxName,n.indxName)){let d=e.alterIndexRename({schemaName:c,oldIndexName:n.indxName,newIndexName:r.indxName}),f=mt.getInstance([d],u,!1);a.push(f)}if(!t.isEqual(r.index_tablespace_name,n.index_tablespace_name)){let d=e.alterIndexTablespace({schemaName:c,indexName:r.indxName,tablespaceName:r.index_tablespace_name}),f=mt.getInstance([d],u,!1);a.push(f)}if(!t.isEqual(r.index_storage_parameter,n.index_storage_parameter)){let d=e.alterIndexStorageParams({schemaName:c,indexName:r.indxName,index:r}),f=mt.getInstance([d],u,!1);a.push(f);let h=e.reindexIndex({schemaName:c,indexName:r.indxName}),T=mt.getInstance([h],u,!1);a.push(T)}return a.filter(Boolean)},"getAlterIndexScriptDtos"),dE=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l,p,m;let s=((u=(c=(o=r==null?void 0:r.role)==null?void 0:o.compMod)==null?void 0:c.Indxs)==null?void 0:u.new)||[],a=((m=(p=(l=r==null?void 0:r.role)==null?void 0:l.compMod)==null?void 0:p.Indxs)==null?void 0:m.old)||[];return s.map(d=>{let f=a.find(h=>ni({oldIndex:h,newIndex:d}));if(f)return{newIndex:d,oldIndex:f}}).filter(Boolean).flatMap(({newIndex:d,oldIndex:f})=>{if(uE({_:t})({newIndex:d,oldIndex:f})){let _=dl({_:t,ddlProvider:e})({index:f,additionalDataForDdlProvider:n}),y=pl({_:t,ddlProvider:e})({index:d,collection:r,additionalDataForDdlProvider:n});return[_,y]}return lE({_:t})({oldIndex:f,newIndex:d})?mE({_:t,ddlProvider:e})({oldIndex:f,newIndex:d,additionalDataForDdlProvider:n}):[]}).filter(Boolean)},"getModifiedIndexesScriptDtos"),fE=i(({_:t,ddlProvider:e})=>({collection:r,dbVersion:n})=>{let s=fl({_:t,dbVersion:n,collection:r}),a=pE({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s}),o=ml({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s}),c=dE({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s});return[...a,...o,...c].filter(Boolean)},"getModifyIndexesScriptDtos"),fl=i(({_:t,dbVersion:e,collection:r})=>{var s,a,o;let{getSchemaNameFromCollection:n}=L()(t);return{dbData:{dbVersion:e},tableName:((a=(s=r==null?void 0:r.compMod)==null?void 0:s.collectionName)==null?void 0:a.new)||((o=r==null?void 0:r.role)==null?void 0:o.name)||"",schemaName:n({collection:r})||"",isParentActivated:r.isActivated}},"getAdditionalDataForDdlProvider");hl.exports={getModifyIndexesScriptDtos:fE,getAddedIndexesScriptDtos:ml,getAdditionalDataForDdlProvider:fl}});var Mt=C((xN,yl)=>{yl.exports=t=>{let{createColumnDefinition:e}=t.require("@hackolade/ddl-fe-utils"),r=i(s=>s.$ref?s.$ref.split("/").pop():s.mode||s.childType||s.type,"getType");return{createColumnDefinitionBySchema:i(({name:s,jsonSchema:a,parentJsonSchema:o,ddlProvider:c,schemaData:u,definitionJsonSchema:l})=>e({name:s,jsonSchema:a,parentJsonSchema:o,ddlProvider:c,schemaData:u,definitionJsonSchema:l,getType:r}),"createColumnDefinitionBySchema")}}});var Cl=C((MN,Sl)=>{var{getModifyCheckConstraintScriptDtos:hE}=Uu(),{getModifyEntityCommentsScriptDtos:gE}=Bu(),{getUpdateTypesScriptDtos:yE}=Gu(),{getModifyNonNullColumnsScriptDtos:_E}=Wu(),{getModifiedCommentOnColumnScriptDtos:EE}=ju(),{getRenameColumnScriptDtos:TE}=Xu(),{AlterScriptDto:yr}=ne(),{AlterCollectionDto:LN}=Ge(),{getModifyPkConstraintsScriptDtos:SE}=nl(),{getModifyUniqueKeyConstraintsScriptDtos:CE}=cl(),{getModifyIndexesScriptDtos:AE,getAddedIndexesScriptDtos:NE,getAdditionalDataForDdlProvider:bE}=gl(),vE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{getEntityName:c}=L()(o),{createColumnDefinitionBySchema:u}=Mt()(t),l=se()(null,null,t),{getDefinitionByReference:p}=t.require("@hackolade/ddl-fe-utils"),d={schemaName:a.compMod.keyspaceName,dbVersion:e},f={...a,...o.omit(a==null?void 0:a.role,"properties")||{}},h=o.toPairs(f.properties).map(([b,I])=>{let R=p({propertySchema:I,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return u({name:b,jsonSchema:I,parentJsonSchema:f,ddlProvider:l,schemaData:d,definitionJsonSchema:R})}),T=(f.chkConstr||[]).map(b=>l.createCheckConstraint(l.hydrateCheckConstraint(b))),_={name:c(f),columns:h.map(l.convertColumnDefinition),checkConstraints:T,foreignKeyConstraints:[],schemaData:d,columnDefinitions:h,dbData:{dbVersion:e}},y=l.hydrateTable({tableData:_,entityData:[f],jsonSchema:f}),N=El({_:o,ddlProvider:l,collection:a,dbVersion:e}).flatMap(({scripts:b})=>b.map(({script:I})=>I)),S=l.createTable(y,f.isActivated);return yr.getInstance([S,...N],!0,!1)},"getAddCollectionScriptDto"),IE=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{getFullTableName:s}=L()(r),a=s(e),o=n.dropTable(a);return yr.getInstance([o],!0,!0)},"getDeleteCollectionScriptDto"),OE=i(({app:t,dbVersion:e})=>r=>{let n=t.require("lodash"),s=se()(null,null,t),a=hE(n,s)(r),o=gE(n,s)(r),c=SE(n,s)(r),u=CE({_:n,ddlProvider:s})({collection:r,dbVersion:e}),l=AE({_:n,ddlProvider:s})({collection:r,dbVersion:e});return[...a,...o,...c,...u,...l].filter(Boolean)},"getModifyCollectionScriptDtos"),_l=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>(a,o)=>{var b;let c=t.require("lodash"),{getEntityName:u,getNamePrefixedWithSchemaName:l}=L()(c),{createColumnDefinitionBySchema:p}=Mt()(t),m=se()(null,null,t),{getDefinitionByReference:d}=t.require("@hackolade/ddl-fe-utils"),f={...a,...c.omit(a==null?void 0:a.role,"properties")||{}},h=u(f),T=(b=f.compMod)==null?void 0:b.keyspaceName,_=l(h,T),y={schemaName:T,dbVersion:e},N=c.toPairs(a.properties).filter(([I,R])=>o([I,R])).map(([I,R])=>{let M=d({propertySchema:R,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return p({name:I,jsonSchema:R,parentJsonSchema:f,ddlProvider:m,schemaData:y,definitionJsonSchema:M})}).map(m.convertColumnDefinition).map(I=>m.addColumn(_,I)).map(I=>yr.getInstance([I],!0,!1)),S=El({_:c,ddlProvider:m,collection:a});return N.concat(S).filter(Boolean)},"getAddColumnsByConditionScriptDtos"),El=i(({_:t,ddlProvider:e,dbVersion:r,collection:n})=>{var l,p;let s=((l=n==null?void 0:n.role)==null?void 0:l.Indxs)||[],a={...n==null?void 0:n.properties,...(p=n==null?void 0:n.role)==null?void 0:p.properties},o=Object.values(a).map(({GUID:m})=>m);if(s.length===0||o.length===0)return[];if(!s.some(({columns:m})=>m.find(({keyId:d})=>o.includes(d))))return[];let u=bE({_:t,dbVersion:r,collection:n});return NE({_:t,ddlProvider:e})({collection:n,additionalDataForDdlProvider:u})},"getNewlyCreatedIndexesScripts"),RE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>_l({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(a,([o,c])=>!c.compMod),"getAddColumnScriptDtos"),Tl=i(t=>(e,r)=>{var d;let n=t.require("lodash"),s=se()(null,null,t),{getEntityName:a,getNamePrefixedWithSchemaName:o,wrapInQuotes:c}=L()(n),u={...e,...n.omit(e==null?void 0:e.role,"properties")||{}},l=a(u),p=(d=u.compMod)==null?void 0:d.keyspaceName,m=o(l,p);return n.toPairs(e.properties).filter(([f,h])=>r([f,h])).map(([f])=>{let h=c(f);return s.dropColumn(m,h)}).map(f=>yr.getInstance([f],!0,!0)).filter(Boolean)},"getDeleteColumnsByConditionScriptDtos"),wE=i(t=>e=>Tl(t)(e,([r,n])=>!n.compMod),"getDeleteColumnScriptDtos"),DE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash");return o.toPairs(a.properties).filter(([c,u])=>{let l=u.compMod.oldField.name,p=a.role.properties[l];return p.generatedColumn!==u.generatedColumn||p.columnGenerationExpression!==u.columnGenerationExpression}).flatMap(([c,u])=>{let l={...a,properties:o.fromPairs([[c,u]])},p=Tl(t)(l,()=>!0),m=_l({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(l,()=>!0);return[...p,...m]}).filter(Boolean)},"getDropAndRecreateColumnsScriptDtos"),qE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),c=se()(null,null,t),u=TE(o,c)(a),l=DE({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(a);if(l.length)return[...u,...l].filter(Boolean);let p=yE(o,c)(a),m=_E(o,c)(a),d=EE(o,c)(a);return[...u,...p,...m,...d].filter(Boolean)},"getModifyColumnScriptDtos");Sl.exports={getAddCollectionScriptDto:vE,getDeleteCollectionScriptDto:IE,getModifyCollectionScriptDtos:OE,getAddColumnScriptDtos:RE,getDeleteColumnScriptDtos:wE,getModifyColumnScriptDtos:qE}});var Nl=C((UN,Al)=>{var{AlterScriptDto:ze}=ne(),xE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{createColumnDefinitionBySchema:c}=Mt()(t),u=se()(null,null,t),{getDefinitionByReference:l}=t.require("@hackolade/ddl-fe-utils"),p={dbVersion:e},m=o.toPairs(a.properties||{}).map(([T,_])=>{let y=l({propertySchema:_,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:T,jsonSchema:_,parentJsonSchema:a,ddlProvider:u,schemaData:p,definitionJsonSchema:y})}),f={...c({name:a.code||a.name,jsonSchema:a,parentJsonSchema:{required:[]},definitionJsonSchema:{},ddlProvider:u,schemaData:p}),properties:m},h=u.createUdt(f);return ze.getInstance([h],!0,!1)},"getCreateUdtScriptDto"),PE=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{getUdtName:s,wrapInQuotes:a}=L()(r),o=a(s(e));if(e.type==="domain"){let c=n.dropDomain(o);return ze.getInstance([c],!0,!0)}else{let c=n.dropType(o);return ze.getInstance([c],!0,!0)}},"getDeleteUdtScriptDto"),LE=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{createColumnDefinitionBySchema:c}=Mt()(t),{getUdtName:u,wrapInQuotes:l}=L()(o),p=se()(null,null,t),{getDefinitionByReference:m}=t.require("@hackolade/ddl-fe-utils"),d=l(u(a)),f={dbVersion:e};return o.toPairs(a.properties).filter(([h,T])=>!T.compMod).map(([h,T])=>{let _=m({propertySchema:T,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:h,jsonSchema:T,parentJsonSchema:{required:[]},ddlProvider:p,schemaData:f,definitionJsonSchema:_})}).map(p.convertColumnDefinition).map(h=>p.alterTypeAddAttribute(d,h)).map(h=>ze.getInstance([h],!0,!1)).filter(Boolean)},"getAddColumnToTypeScriptDtos"),ME=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{wrapInQuotes:s}=L()(r),a=s(e.code||e.name);return r.toPairs(e.properties).filter(([o,c])=>!c.compMod).map(([o])=>n.alterTypeDropAttribute(a,s(o))).map(o=>ze.getInstance([o],!0,!0)).filter(Boolean)},"getDeleteColumnFromTypeScriptDtos"),FE=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{checkFieldPropertiesChanged:s,wrapInQuotes:a}=L()(r),o=a(e.code||e.name),c=r.values(e.properties).filter(l=>s(l.compMod,["name"])).map(l=>{let p=a(l.compMod.oldField.name),m=a(l.compMod.newField.name);return n.alterTypeRenameAttribute(o,p,m)}).map(l=>ze.getInstance([l],!0,!1)),u=r.toPairs(e.properties).filter(([l,p])=>s(p.compMod,["type","mode"])).map(([l,p])=>{let m=a(l),d=p.compMod.newField.mode||p.compMod.newField.type;return n.alterTypeChangeAttributeType(o,m,d)}).map(l=>ze.getInstance([l],!0,!1));return[...c,...u].filter(Boolean)},"getModifyColumnOfTypeScriptDtos");Al.exports={getCreateUdtScriptDto:xE,getDeleteUdtScriptDto:PE,getAddColumnToTypeScriptDtos:LE,getDeleteColumnFromTypeScriptDtos:ME,getModifyColumnOfTypeScriptDtos:FE}});var Ol=C(($N,Il)=>{var{AlterScriptDto:bl}=ne(),vl=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),UE=i((t,e)=>r=>{let{getFullViewName:n,wrapComment:s}=L()(t),a=vl(r);if(a.new&&a.new!==a.old){let o=s(a.new),c=n(r),u=e.updateViewComment(c,o);return bl.getInstance([u],!0,!1)}},"getUpsertCommentsScriptDto"),kE=i((t,e)=>r=>{let n=vl(r),{getFullViewName:s}=L()(t);if(n.old&&!n.new){let a=s(r),o=e.dropViewComment(a);return bl.getInstance([o],!0,!0)}},"getDropCommentsScriptDto"),$E=i((t,e)=>r=>{let n=UE(t,e)(r),s=kE(t,e)(r);return[n,s].filter(Boolean)},"getModifyViewCommentsScriptDtos");Il.exports={getModifyViewCommentsScriptDtos:$E}});var Dl=C((KN,wl)=>{var{getModifyViewCommentsScriptDtos:BE}=Ol(),{AlterScriptDto:Rl}=ne(),KE=i(t=>e=>{let r=se()(null,null,t),n={name:e.code||e.name,keys:[],schemaData:{schemaName:""}},s=r.hydrateView({viewData:n,entityData:[e]}),a=r.createView(s,{},e.isActivated);return Rl.getInstance([a],!0,!1)},"getAddViewScriptDto"),GE=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t),{wrapInQuotes:s}=L()(r),a=s(e.code||e.name),o=n.dropView(a);return Rl.getInstance([o],!0,!0)},"getDeleteViewScriptDto"),VE=i(t=>e=>{let r=t.require("lodash"),n=se()(null,null,t);return[...BE(r,n)(e)].filter(Boolean)},"getModifyViewScriptDtos");wl.exports={getAddViewScriptDto:KE,getDeleteViewScriptDto:GE,getModifyViewScriptDtos:VE}});var xl=C((VN,ql)=>{var pi=class pi{isActivated;name};i(pi,"AlterRelationshipFKField");var si=pi,mi=class mi{bucket;collection};i(mi,"AlterRelationshipParentDto");var ii=mi,di=class di{bucket;collection};i(di,"AlterRelationshipChildDto");var ai=di,fi=class fi{relationshipOnDelete;relationshipOnUpdate;relationshipMatch};i(fi,"AlterRelationshipCustomProperties");var oi=fi,hi=class hi{created;deleted;modified;parent;child;name;description;customProperties;isActivated};i(hi,"AlterRelationshipRoleCompModDto");var ci=hi,gi=class gi{id;name;relationshipType;parentField;parentCardinality;childField;isActivated;childCardinality;parentCollection;childCollection;hackoladeStyles;compMod;roleType};i(gi,"AlterRelationshipRoleDto");var ui=gi,yi=class yi{type;isActivated;unique;subtype;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(yi,"AlterRelationshipDto");var li=yi;ql.exports={AlterRelationshipRoleCompModDto:ci,AlterRelationshipRoleDto:ui,AlterRelationshipDto:li,AlterRelationshipFKField:si,AlterRelationshipParentDto:ii,AlterRelationshipChildDto:ai,AlterRelationshipCustomProperties:oi}});var kl=C((QN,Ul)=>{var{AlterScriptDto:_i}=ne(),{AlterRelationshipDto:WN}=xl(),_r=i(t=>t.role.name,"getRelationshipName"),HE=i(t=>e=>{let{getNamePrefixedWithSchemaName:r}=L()(t),n=e.role.compMod,s=n.child.bucket.name,a=n.child.collection.name;return r(a,s)},"getFullChildTableName"),Pl=i((t,e)=>r=>{var a,o,c,u,l;let n=r.role.compMod,s=((a=n.name)==null?void 0:a.new)||_r(r)||"";return t.createForeignKey({name:s,foreignKey:n.child.collection.fkFields,primaryKey:n.parent.collection.fkFields,customProperties:(o=n.customProperties)==null?void 0:o.new,foreignTable:n.child.collection.name,foreignSchemaName:n.child.bucket.name,foreignTableActivated:n.child.collection.isActivated,primaryTable:n.parent.collection.name,primarySchemaName:n.parent.bucket.name,primaryTableActivated:n.parent.collection.isActivated,isActivated:!!((l=(u=(c=r.role)==null?void 0:c.compMod)==null?void 0:u.isActivated)!=null&&l.new)})},"getAddSingleForeignKeyStatementDto"),Ll=i(t=>{var r,n,s,a,o,c,u,l,p,m,d;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.new)||_r(t),(n=e.parent)==null?void 0:n.bucket,(s=e.parent)==null?void 0:s.collection,(c=(o=(a=e.parent)==null?void 0:a.collection)==null?void 0:o.fkFields)==null?void 0:c.length,(u=e.child)==null?void 0:u.bucket,(l=e.child)==null?void 0:l.collection,(d=(m=(p=e.child)==null?void 0:p.collection)==null?void 0:m.fkFields)==null?void 0:d.length].every(f=>!!f):!1},"canRelationshipBeAdded"),WE=i((t,e)=>r=>r.filter(n=>Ll(n)).map(n=>{let s=Pl(t,e)(n);return _i.getInstance([s.statement],s.isActivated,!1)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getAddForeignKeyScriptDtos"),Ml=i((t,e)=>r=>{var m,d,f,h;let{wrapInQuotes:n}=L()(e),s=r.role.compMod,a=HE(e)(r),o=((m=s.name)==null?void 0:m.old)||_r(r)||"",c=n(o),u=t.dropForeignKey(a,c),l=!!((h=(f=(d=r.role)==null?void 0:d.compMod)==null?void 0:f.isActivated)!=null&&h.new),p=s.child.collection.isActivated;return{statement:u,isActivated:l&&p}},"getDeleteSingleForeignKeyStatementDto"),Fl=i(t=>{var r,n,s;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.old)||_r(t),(n=e.child)==null?void 0:n.bucket,(s=e.child)==null?void 0:s.collection].every(a=>!!a):!1},"canRelationshipBeDeleted"),QE=i((t,e)=>r=>r.filter(n=>Fl(n)).map(n=>{let s=Ml(t,e)(n);return _i.getInstance([s.statement],s.isActivated,!0)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getDeleteForeignKeyScriptDtos"),YE=i((t,e)=>r=>r.filter(n=>Ll(n)&&Fl(n)).map(n=>{let s=Ml(t,e)(n),a=Pl(t,e)(n),o=a.isActivated&&s.isActivated;return _i.getDropAndRecreateInstance(s.statement,a.statement,o)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getModifyForeignKeyScriptDtos");Ul.exports={getDeleteForeignKeyScriptDtos:QE,getModifyForeignKeyScriptDtos:YE,getAddForeignKeyScriptDtos:WE}});var Ii=C((jN,$l)=>{var Ai=class Ai{message;stack};i(Ai,"PluginError");var Ei=Ai,Ni=class Ni{require};i(Ni,"App");var Ti=Ni,bi=class bi{log;clear};i(bi,"Logger");var Si=bi,vi=class vi{jsonSchema;modelDefinitions;internalDefinitions;externalDefinitions;containerData;entityData;entities;views;viewData;relationships;collectionRefsDefinitionsMap;isUpdateScript;level;host;clusterId;accessToken;applyToInstanceQueryRequestTimeout;script;hiddenKeys;options;modelData};i(vi,"CoreData");var Ci=vi;$l.exports={App:Ti,CoreData:Ci,Logger:Si,PluginError:Ei}});var Kl=C((XN,Bl)=>{var Mi=class Mi{name;isActivated};i(Mi,"ContainerJsonSchema");var Oi=Mi,Fi=class Fi{backgroundColor};i(Fi,"ContainerStyles");var Ri=Fi,Ui=class Ui{collectionName;isActivated;bucketId;additionalProperties;tableIfNotExists};i(Ui,"EntityData");var wi=Ui,ki=class ki{$schema;type;GUID};i(ki,"InternalDefinitions");var Di=ki,$i=class $i{$schema;type;GUID};i($i,"ModelDefinitions");var qi=$i,Bi=class Bi{$schema;type;GUID};i(Bi,"ExternalDefinitions");var xi=Bi,Ki=class Ki{type;isActivated;mode;subtype;compositeKey;compositePartitionKey;compositeClusteringKey;compositePrimaryKey;compositeUniqueKey;GUID};i(Ki,"FieldJsonSchema");var Pi=Ki,Gi=class Gi{$schema;type;title;properties;isActivated;additionalProperties;tableIfNotExists;GUID};i(Gi,"EntityJsonSchema");var Li=Gi;Bl.exports={ContainerJsonSchema:Oi,ContainerStyles:Ri,EntityData:wi,InternalDefinitions:Di,ModelDefinitions:qi,ExternalDefinitions:xi,FieldJsonSchema:Pi,EntityJsonSchema:Li}});var Er=C((JN,Gl)=>{Gl.exports=se()});var Hl=C((tb,Vl)=>{var{AlterScriptDto:Ft}=ne(),{App:eb}=Ii(),jE="sequences",zE=i(({app:t})=>({container:e})=>{var o;let r=t.require("lodash"),n=Er()(null,null,t),{getDbName:s}=L()(r),a=s([e.role]);return(((o=e.role)==null?void 0:o.sequences)||[]).map(c=>n.createSchemaSequence({schemaName:a,sequence:c})).map(c=>Ft.getInstance([c],!0,!1)).filter(Boolean)},"getAddContainerSequencesScriptDtos"),XE=i(({app:t})=>({container:e})=>{var _,y;let r=t.require("lodash"),n=Er()(null,null,t),{getDbName:s,getGroupItemsByCompMode:a}=L()(r),o=s([e.role]),c=((y=(_=e.role)==null?void 0:_.compMod)==null?void 0:y[jE])||{},{new:u=[],old:l=[]}=c,{removed:p,added:m,modified:d}=a({newItems:u,oldItems:l}),f=p.map(N=>n.dropSchemaSequence({schemaName:o,sequence:N})).map(N=>Ft.getInstance([N],!0,!0)),h=m.map(N=>n.createSchemaSequence({schemaName:o,sequence:N})).map(N=>Ft.getInstance([N],!0,!1));return[...d.map(N=>{let S=r.find(l,{id:N.id})||{};return n.alterSchemaSequence({schemaName:o,sequence:N,oldSequence:S})}).map(N=>Ft.getInstance([N],!0,!1)),...f,...h].filter(Boolean)},"getModifyContainerSequencesScriptDtos"),ZE=i(({app:t})=>({container:e})=>{var o;let r=t.require("lodash"),n=Er()(null,null,t),{getDbName:s}=L()(r),a=s([e.role]);return(((o=e.role)==null?void 0:o.sequences)||[]).map(c=>n.dropSchemaSequence({schemaName:a,sequence:c})).map(c=>Ft.getInstance([c],!0,!0)).filter(Boolean)},"getDeleteContainerSequencesScriptDtos");Vl.exports={getAddContainerSequencesScriptDtos:zE,getModifyContainerSequencesScriptDtos:XE,getDeleteContainerSequencesScriptDtos:ZE}});var Ql=C((lb,Wl)=>{var{getAddContainerScriptDto:JE,getDeleteContainerScriptDto:eT,getModifyContainerScriptDtos:tT}=Mu(),{getAddCollectionScriptDto:rT,getDeleteCollectionScriptDto:nT,getAddColumnScriptDtos:sT,getDeleteColumnScriptDtos:iT,getModifyColumnScriptDtos:aT,getModifyCollectionScriptDtos:oT}=Cl(),{getDeleteUdtScriptDto:cT,getCreateUdtScriptDto:uT,getAddColumnToTypeScriptDtos:lT,getDeleteColumnFromTypeScriptDtos:pT,getModifyColumnOfTypeScriptDtos:mT}=Nl(),{getAddViewScriptDto:dT,getDeleteViewScriptDto:fT,getModifyViewScriptDtos:hT}=Dl(),{getModifyForeignKeyScriptDtos:gT,getDeleteForeignKeyScriptDtos:yT,getAddForeignKeyScriptDtos:_T}=kl(),{AlterScriptDto:nb,ModificationScript:sb}=ne(),{App:ib,CoreData:ab}=Ii(),{InternalDefinitions:ob,ModelDefinitions:cb,ExternalDefinitions:ub}=Kl(),{getModifyContainerSequencesScriptDtos:ET,getDeleteContainerSequencesScriptDtos:TT,getAddContainerSequencesScriptDtos:ST}=Hl(),CT=i(({collection:t,app:e})=>{var u,l,p,m,d,f,h,T,_,y,N,S;let r=(m=(p=(l=(u=t.properties)==null?void 0:u.containers)==null?void 0:l.properties)==null?void 0:p.added)==null?void 0:m.items,n=(T=(h=(f=(d=t.properties)==null?void 0:d.containers)==null?void 0:f.properties)==null?void 0:h.deleted)==null?void 0:T.items,s=(S=(N=(y=(_=t.properties)==null?void 0:_.containers)==null?void 0:y.properties)==null?void 0:N.modified)==null?void 0:S.items,a=[].concat(r).filter(Boolean).map(b=>JE(e)(Object.keys(b.properties)[0])),o=[].concat(n).filter(Boolean).map(b=>eT(e)(Object.keys(b.properties)[0])),c=[].concat(s).filter(Boolean).map(b=>Object.values(b.properties)[0]).flatMap(b=>tT(e)(b));return[...a,...o,...c].filter(Boolean)},"getAlterContainersScriptDtos"),AT=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})=>{var T,_,y,N,S,b,I,R,M,v,D,G;let o=[].concat((N=(y=(_=(T=t.properties)==null?void 0:T.entities)==null?void 0:_.properties)==null?void 0:y.added)==null?void 0:N.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),c=[].concat((R=(I=(b=(S=t.properties)==null?void 0:S.entities)==null?void 0:b.properties)==null?void 0:I.deleted)==null?void 0:R.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),u=[].concat((G=(D=(v=(M=t.properties)==null?void 0:M.entities)==null?void 0:v.properties)==null?void 0:D.modified)==null?void 0:G.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),l=o.filter(P=>{var X;return(X=P.compMod)==null?void 0:X.created}).map(rT({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),p=c.filter(P=>{var X;return(X=P.compMod)==null?void 0:X.deleted}).map(nT(e)),m=u.flatMap(oT({app:e,dbVersion:r})),d=o.filter(P=>{var X;return!((X=P==null?void 0:P.compMod)!=null&&X.created)}).flatMap(sT({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),f=c.filter(P=>{var X;return!((X=P==null?void 0:P.compMod)!=null&&X.deleted)}).flatMap(iT(e)),h=u.flatMap(aT({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}));return[...l,...p,...m,...d,...f,...h].filter(Boolean)},"getAlterCollectionsScriptDtos"),NT=i((t,e)=>{var a,o,c,u,l,p,m,d,f,h,T,_;let r=[].concat((u=(c=(o=(a=t.properties)==null?void 0:a.views)==null?void 0:o.properties)==null?void 0:c.added)==null?void 0:u.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).filter(y=>{var N;return((N=y.compMod)==null?void 0:N.created)&&y.selectStatement}).map(dT(e)),n=[].concat((d=(m=(p=(l=t.properties)==null?void 0:l.views)==null?void 0:p.properties)==null?void 0:m.deleted)==null?void 0:d.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).map(fT(e)),s=[].concat((_=(T=(h=(f=t.properties)==null?void 0:f.views)==null?void 0:h.properties)==null?void 0:T.modified)==null?void 0:_.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).flatMap(y=>hT(e)(y));return[...n,...r,...s].filter(Boolean)},"getAlterViewScriptDtos"),bT=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})=>{var m,d,f,h,T,_,y,N,S,b,I,R,M,v,D,G,P,X,ve,me;let o=[].concat((h=(f=(d=(m=t.properties)==null?void 0:m.modelDefinitions)==null?void 0:d.properties)==null?void 0:f.added)==null?void 0:h.items).filter(Boolean).map(U=>Object.values(U.properties)[0]).map(U=>({...U,...e.require("lodash").omit(U.role,"properties")||{}})).filter(U=>{var Ie;return(Ie=U.compMod)==null?void 0:Ie.created}).map(uT({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),c=[].concat((N=(y=(_=(T=t.properties)==null?void 0:T.modelDefinitions)==null?void 0:_.properties)==null?void 0:y.deleted)==null?void 0:N.items).filter(Boolean).map(U=>Object.values(U.properties)[0]).map(U=>({...U,...e.require("lodash").omit(U.role,"properties")||{}})).filter(U=>{var Ie;return(Ie=U.compMod)==null?void 0:Ie.deleted}).map(cT(e)),u=[].concat((R=(I=(b=(S=t.properties)==null?void 0:S.modelDefinitions)==null?void 0:b.properties)==null?void 0:I.added)==null?void 0:R.items).filter(Boolean).map(U=>Object.values(U.properties)[0]).filter(U=>!U.compMod).map(U=>({...U,...e.require("lodash").omit(U.role,"properties")||{}})).filter(U=>U.childType==="composite").flatMap(lT({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),l=[].concat((G=(D=(v=(M=t.properties)==null?void 0:M.modelDefinitions)==null?void 0:v.properties)==null?void 0:D.deleted)==null?void 0:G.items).filter(Boolean).map(U=>Object.values(U.properties)[0]).filter(U=>!U.compMod).map(U=>({...U,...e.require("lodash").omit(U.role,"properties")||{}})).filter(U=>U.childType==="composite").flatMap(pT(e)),p=[].concat((me=(ve=(X=(P=t.properties)==null?void 0:P.modelDefinitions)==null?void 0:X.properties)==null?void 0:ve.modified)==null?void 0:me.items).filter(Boolean).map(U=>Object.values(U.properties)[0]).filter(U=>!U.compMod).map(U=>({...U,...e.require("lodash").omit(U.role,"properties")||{}})).filter(U=>U.childType==="composite").flatMap(mT(e));return[...c,...o,...u,...l,...p].filter(Boolean)},"getAlterModelDefinitionsScriptDtos"),vT=i(({collection:t,app:e})=>{var p,m,d,f,h,T,_,y,N,S,b,I;let r=e.require("lodash"),n=se()(null,null,e),s=[].concat((f=(d=(m=(p=t.properties)==null?void 0:p.relationships)==null?void 0:m.properties)==null?void 0:d.added)==null?void 0:f.items).filter(Boolean).map(R=>Object.values(R.properties)[0]).filter(R=>{var M,v;return(v=(M=R==null?void 0:R.role)==null?void 0:M.compMod)==null?void 0:v.created}),a=[].concat((y=(_=(T=(h=t.properties)==null?void 0:h.relationships)==null?void 0:T.properties)==null?void 0:_.deleted)==null?void 0:y.items).filter(Boolean).map(R=>Object.values(R.properties)[0]).filter(R=>{var M,v;return(v=(M=R==null?void 0:R.role)==null?void 0:M.compMod)==null?void 0:v.deleted}),o=[].concat((I=(b=(S=(N=t.properties)==null?void 0:N.relationships)==null?void 0:S.properties)==null?void 0:b.modified)==null?void 0:I.items).filter(Boolean).map(R=>Object.values(R.properties)[0]).filter(R=>{var M,v;return(v=(M=R==null?void 0:R.role)==null?void 0:M.compMod)==null?void 0:v.modified}),c=yT(n,r)(a),u=_T(n,r)(s),l=gT(n,r)(o);return[...c,...u,...l].filter(Boolean)},"getAlterRelationshipsScriptDtos"),IT=i(t=>{if(!t)return;let e=t.scripts.map(r=>({...r,script:(r.script||"").trim()})).filter(r=>!!r.script);if(e.length)return{...t,scripts:e}},"prettifyAlterScriptDto"),OT=i(({collection:t,app:e})=>{var u,l,p,m,d,f,h,T,_,y,N,S;let r=(m=(p=(l=(u=t.properties)==null?void 0:u.containers)==null?void 0:l.properties)==null?void 0:p.added)==null?void 0:m.items,n=(T=(h=(f=(d=t.properties)==null?void 0:d.containers)==null?void 0:f.properties)==null?void 0:h.deleted)==null?void 0:T.items,s=(S=(N=(y=(_=t.properties)==null?void 0:_.containers)==null?void 0:y.properties)==null?void 0:N.modified)==null?void 0:S.items,a=[].concat(r).filter(Boolean).map(b=>Object.values(b.properties)[0]).flatMap(b=>ST({app:e})({container:b})),o=[].concat(n).filter(Boolean).map(b=>Object.values(b.properties)[0]).flatMap(b=>TT({app:e})({container:b})),c=[].concat(s).filter(Boolean).map(b=>Object.values(b.properties)[0]).flatMap(b=>ET({app:e})({container:b}));return[...a,...o,...c].filter(Boolean)},"getAlterContainersSequencesScriptDtos"),RT=i((t,e)=>{var f;let r=JSON.parse(t.jsonSchema);if(!r)throw new Error('"comparisonModelCollection" is not found. Alter script can be generated only from Delta model');let n=JSON.parse(t.modelDefinitions),s=JSON.parse(t.internalDefinitions),a=JSON.parse(t.externalDefinitions),o=(f=t.modelData[0])==null?void 0:f.dbVersion,c=CT({collection:r,app:e}),u=AT({collection:r,app:e,dbVersion:o,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}),l=NT(r,e),p=bT({collection:r,app:e,dbVersion:o,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}),m=vT({collection:r,app:e}),d=OT({collection:r,app:e});return[...c,...p,...u,...d,...l,...m].filter(Boolean).map(h=>IT(h)).filter(Boolean)},"getAlterScriptDtos");Wl.exports={getAlterScriptDtos:RT}});var Xl=C((db,zl)=>{var{getAlterScriptDtos:Tr}=Ql(),{AlterScriptDto:mb}=ne(),Yl=i(t=>(e,r)=>{let{commentIfDeactivated:n}=L()(t);return e.map(s=>s.isActivated===!1?s.scripts.map(a=>n(a.script,{isActivated:!1,isPartOfLine:!1})):r?s.scripts.map(a=>a.script):s.scripts.map(a=>n(a.script,{isActivated:!a.isDropScript,isPartOfLine:!1}))).flat().filter(Boolean).map(s=>s.trim()).filter(Boolean).join(` +`},dropView(g){let E={viewName:g};return y(x.dropView,E)},createViewIndex(){return""},createUdt(g){let E=n.map(g.properties,this.convertColumnDefinition);return C(g,E)},getDefaultType(g){return ng[g]},getTypesDescriptors(){return $c},hasType(g){return u($c,g)},hydrateDatabase({modelData:g}){return g=n.get(g,"0",{}),{databaseName:g.database_name,tablespace:g.tablespace_name,encoding:g.encoding,template:g.template,collate:g.LC_COLLATE,characterClassification:g.LC_CTYPE,dbVersion:g.dbVersion,locale:g.locale}},hydrateColumn({columnDefinition:g,jsonSchema:E,schemaData:O,definitionJsonSchema:R={},parentJsonSchema:K}){let X=n.includes(["char","varchar","text"],g.type)?E.collationRule:"",W=["time","timestamp"],ee=n.includes(W,g.type)?E.timePrecision:"",ie=n.includes(W,g.type)?E.timezone:"",oe=g.type==="interval"?E.intervalOptions:"",{getDbVersion:Ee}=L()(n),me=Ee(O.dbVersion),Z=n.omit(b.hydratePrimaryKeyOptions(n.first(E.primaryKeyOptions)||{},g.name,g.isActivated,K),"columns"),be=n.omit(b.hydrateUniqueOptions({options:n.first(E.uniqueKeyOptions)||{},columnName:g.name,isActivated:g.isActivated,jsonSchema:K,dbVersion:me}),"columns");return{name:g.name,type:g.type,primaryKey:b.isInlinePrimaryKey(E),primaryKeyOptions:Z,unique:b.isInlineUnique(E),uniqueKeyOptions:be,nullable:g.nullable,default:g.default,comment:E.refDescription||E.description||R.description,isActivated:g.isActivated,scale:g.scale,precision:g.precision,length:g.length,enum:E.enum,array_type:E.array_type,unit:E.unit,rangeSubtype:E.rangeSubtype,operatorClass:E.operatorClass,collation:E.collation,canonicalFunction:E.canonicalFunction,subtypeDiffFunction:E.subtypeDiffFunction,multiRangeType:E.multiRangeType,schemaName:O.schemaName,underlyingType:E.underlyingType,checkConstraints:E.checkConstraints,typeModifier:E.typeModifier,srid:E.srid,collationRule:X,timePrecision:ee,timezone:ie,intervalOptions:oe,dbVersion:me,generatedColumn:!!E.generatedColumn,columnGenerationExpression:E.columnGenerationExpression}},hydrateJsonSchemaColumn(g,E){return!g.$ref||n.isEmpty(E)||D(E)?g:(g=n.omit(g,"$ref"),{...E,...g})},hydrateIndex(g,E,O){return{...g,schemaName:O.schemaName}},hydrateViewIndex(g){return{}},hydrateCheckConstraint(g){return{name:g.chkConstrName,expression:g.constrExpression,noInherit:g.noInherit}},hydrateSchema(g,E){let O=n.get(E,"modelData.0.dbVersion");return{schemaName:g.name,ifNotExist:g.ifNotExist,comments:g.description,udfs:(E==null?void 0:E.udfs)||[],procedures:(E==null?void 0:E.procedures)||[],sequences:(E==null?void 0:E.sequences)||[],dbVersion:O}},hydrateTable({tableData:g,entityData:E,jsonSchema:O}){let R=E[0],K=n.chain(R.inherits).map(({parentTable:Z})=>n.get(g,`relatedSchemas[${Z}]`,"")).compact().map(Z=>Z.code||Z.collectionName).join(", ").thru(Z=>Z?`(${Z})`:"").value(),X=n.first(R.partitioning)||{},W=b.getKeys(X.compositePartitionKey,O),ee=n.get(g,`relatedSchemas[${R.partitionOf}]`),ie=ee?h(ee.collectionName,ee.bucketName):"",oe=Ci(E,g.relatedSchemas),{getDbVersion:Ee}=L()(n),me=Ee(n.get(g,"dbData.dbVersion",""));return{...g,triggers:oe,partitionOf:ie,keyConstraints:b.getTableKeyConstraints(O,me),inherits:K,selectStatement:n.trim(R.selectStatement),partitioning:n.assign({},X,{compositePartitionKey:W}),...n.pick(R,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","table_tablespace_name","partitionBounds")}},hydrateViewColumn(g){return{name:g.name,tableName:g.entityName,alias:g.alias,isActivated:g.isActivated,dbName:g.dbName}},hydrateView({viewData:g,entityData:E,relatedSchemas:O}){let R=E[0],K=Ci(E,O);return{name:g.name,keys:g.keys,comment:R.description,orReplace:R.orReplace,temporary:R.temporary,recursive:R.recursive,viewOptions:R.viewOptions,selectStatement:R.selectStatement,withCheckOption:R.withCheckOption,checkTestingScope:R.withCheckOption?R.checkTestingScope:"",schemaName:g.schemaData.schemaName,triggers:K}},commentIfDeactivated(g,E,O){return g},alterColumnType(g,E,O,R){let K=O;return R.length?K+=`(${R.length})`:R.precision&&R.scale?K+=`(${R.precision},${R.scale})`:R.precision&&(K+=`(${R.precision})`),y(x.alterColumnType,{tableName:g,columnName:E,dataType:K})},setNotNullConstraint(g,E){return y(x.addNotNullConstraint,{tableName:g,columnName:E})},dropNotNullConstraint(g,E){return y(x.dropNotNullConstraint,{tableName:g,columnName:E})},renameColumn(g,E,O){return y(x.renameColumn,{tableName:g,oldColumnName:E,newColumnName:O})},addCheckConstraint(g,E,O){let R={tableName:g,constraintName:E,expression:O};return y(x.addCheckConstraint,R)},dropConstraint(g,E){let O={tableName:g,constraintName:E};return y(x.dropConstraint,O)},updateTableComment(g,E){let O={tableName:g,comment:E};return y(x.updateCommentOnTable,O)},dropTableComment(g){let E={tableName:g,comment:"NULL"};return y(x.updateCommentOnTable,E)},updateColumnComment(g,E){let O={columnName:g,comment:E};return y(x.updateCommentOnColumn,O)},dropColumnComment(g){let E={columnName:g,comment:"NULL"};return y(x.updateCommentOnColumn,E)},updateSchemaComment(g,E){let O={schemaName:g,comment:E};return y(x.updateCommentOnSchema,O)},dropSchemaComment(g){let E={schemaName:g,comment:"NULL"};return y(x.updateCommentOnSchema,E)},updateViewComment(g,E){let O={viewName:g,comment:E};return y(x.updateCommentOnView,O)},dropViewComment(g){let E={viewName:g,comment:"NULL"};return y(x.updateCommentOnView,E)},createSchemaOnly(g){let E={schemaName:g};return y(x.createSchemaOnly,E)},dropSchema(g){let E={schemaName:g};return y(x.dropSchema,E)},dropTable(g){let E={tableName:g};return y(x.dropTable,E)},addColumn(g,E){let O={tableName:g,columnDefinition:E};return y(x.addColumn,O)},dropColumn(g,E){let O={tableName:g,columnName:E};return y(x.dropColumn,O)},dropDomain(g){let E={udtName:g};return y(x.dropDomain,E)},dropType(g){let E={udtName:g};return y(x.dropType,E)},alterTypeAddAttribute(g,E){let O={udtName:g,columnDefinition:E};return y(x.alterTypeAddAttribute,O)},alterTypeDropAttribute(g,E){let O={udtName:g,attributeName:E};return y(x.alterTypeDropAttribute,O)},alterTypeRenameAttribute(g,E,O){let R={udtName:g,oldAttributeName:E,newAttributeName:O};return y(x.alterTypeRenameAttribute,R)},alterTypeChangeAttributeType(g,E,O){let R={udtName:g,attributeName:E,newDataType:O};return y(x.alterTypeChangeAttributeType,R)},dropForeignKey(g,E){let O={tableName:g,fkConstraintName:E};return y(x.dropForeignKey,O)},createKeyConstraint(g,E,O){let R=v(x,E)(O);return{statement:y(x.addPkConstraint,{constraintStatement:(R.statement||"").trim(),tableName:g}),isActivated:R.isActivated}},dropKeyConstraint(g,E){let O={tableName:g,constraintName:E};return y(x.dropConstraint,O)},createSchemaSequences({schemaName:g,sequences:E}){return P({schemaName:g,sequences:E})},createSchemaSequence({schemaName:g,sequence:E}){return z({schemaName:g,sequence:E})},dropSchemaSequence({schemaName:g,sequence:E}){return Ae({schemaName:g,sequence:E})},alterSchemaSequence({schemaName:g,sequence:E,oldSequence:O}){return le({schemaName:g,sequence:E,oldSequence:O})},dropIndex({indexName:g}){let E={indexName:g};return y(x.dropIndex,E)},alterIndexRename({schemaName:g,oldIndexName:E,newIndexName:O}){let R=f(g),K=h(f(E),R),X=f(O),W={oldIndexName:K,newIndexName:X};return y(x.alterIndexRename,W)},alterIndexTablespace({schemaName:g,indexName:E,tablespaceName:O}){let R=f(g),X={indexName:h(f(E),R),tablespaceName:O};return y(x.alterIndexTablespace,X)},alterIndexStorageParams({schemaName:g,indexName:E,index:O}){let R=f(g),K=h(f(E),R),X=se(O),W={indexName:K,options:X};return y(x.alterIndexStorageParams,W)},reindexIndex({schemaName:g,indexName:E}){let O=f(g),K={indexName:h(f(E),O)};return y(x.reindexIndex,K)}}}});var Vc=N((US,Gc)=>{"use strict";var{getModifySchemaCommentsScriptDtos:sg}=uc(),{AlterScriptDto:Kc}=re(),ig=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{wrapInQuotes:s}=L()(r),a=n.createSchemaOnly(s(e));return Kc.getInstance([a],!0,!1)},"getAddContainerScriptDto"),ag=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{wrapInQuotes:s}=L()(r),a=n.dropSchema(s(e));return Kc.getInstance([a],!0,!0)},"getDeleteContainerScriptDto"),og=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t);return[...sg(r,n)(e)]},"getModifyContainerScriptDtos");Gc.exports={getAddContainerScriptDto:ig,getDeleteContainerScriptDto:ag,getModifyContainerScriptDtos:og}});var Wc=N((BS,Hc)=>{"use strict";var{AlterCollectionDto:$S}=$e(),{AlterScriptDto:Jt}=re(),cg=i(t=>e=>{var o;let r=(o=e==null?void 0:e.compMod)==null?void 0:o.chkConstr;if(!r)return[];let n=r.new||[],s=r.old||[];return t.chain([...n,...s]).map(c=>c.chkConstrName).uniq().value().map(c=>({old:t.find(s,{chkConstrName:c}),new:t.find(n,{chkConstrName:c})}))},"mapCheckConstraintNamesToChangeHistory"),ug=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>a.old&&!a.new).map(a=>{let o=s(a.old.chkConstrName);return e.dropConstraint(n,o)}).map(a=>Jt.getInstance([a],!0,!0))},"getDropCheckConstraintScriptDtos"),lg=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>a.new&&!a.old).map(a=>{let{chkConstrName:o,constrExpression:c}=a.new;return e.addCheckConstraint(n,s(o),c)}).map(a=>Jt.getInstance([a],!0,!1))},"getAddCheckConstraintScriptDtos"),pg=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=L()(t);return r.filter(a=>{if(a.old&&a.new){let o=a.old.constrExpression,c=a.new.constrExpression;return o!==c}return!1}).map(a=>{let{chkConstrName:o}=a.old,c=e.dropConstraint(n,s(o)),{chkConstrName:u,constrExpression:l}=a.new,d=e.addCheckConstraint(n,s(u),l);return[Jt.getInstance([c],!0,!0),Jt.getInstance([d],!0,!1)]}).flat()},"getUpdateCheckConstraintScriptDtos"),mg=i((t,e)=>r=>{let{getFullTableName:n}=L()(t),s=n(r),a=cg(t)(r),o=lg(t,e)(a,s),c=ug(t,e)(a,s),u=pg(t,e)(a,s);return[...o,...c,...u]},"getModifyCheckConstraintScriptDtos");Hc.exports={getModifyCheckConstraintScriptDtos:mg}});var jc=N((VS,Yc)=>{"use strict";var{AlterScriptDto:Qc}=re(),{AlterCollectionDto:GS}=$e(),dg=i((t,e)=>r=>{var p;let{getFullTableName:n,wrapComment:s}=L()(t),a=(p=r==null?void 0:r.role.compMod)==null?void 0:p.description;if(!a)return;let{old:o,new:c}=a;if(!c||c===o)return;let u=n(r),l=s(c),d=e.updateTableComment(u,l);return Qc.getInstance([d],!0,!1)},"getUpdatedCommentOnCollectionScriptDto"),fg=i((t,e)=>r=>{var l;let{getFullTableName:n}=L()(t),s=(l=r==null?void 0:r.role.compMod)==null?void 0:l.description;if(!s)return;let{old:a,new:o}=s;if(!a||o)return;let c=n(r),u=e.dropTableComment(c);return Qc.getInstance([u],!0,!0)},"getDeletedCommentOnCollectionScriptDto"),hg=i((t,e)=>r=>{let n=dg(t,e)(r),s=fg(t,e)(r);return[n,s].filter(Boolean)},"getModifyEntityCommentsScriptDtos");Yc.exports={getModifyEntityCommentsScriptDtos:hg}});var Xc=N((WS,zc)=>{"use strict";var{AlterScriptDto:gg}=re(),yg=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.length,a=r==null?void 0:r.length;return s!==a},"hasLengthChanged"),_g=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.precision,a=r==null?void 0:r.precision,o=n==null?void 0:n.scale,c=r==null?void 0:r.scale;return s!==a||o!==c},"hasPrecisionOrScaleChanged"),Eg=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:a}=L()(t),o=s(r);return t.toPairs(r.properties).filter(([c,u])=>{let l=n(u.compMod,["type","mode"]);if(!l){let d=u.compMod.oldField.name,p=yg(r,d,u),m=_g(r,d,u);return p||m}return l}).map(([c,u])=>{let l=u.compMod.newField.mode||u.compMod.newField.type,d=a(c),p=t.pick(u,["length","precision","scale"]);return e.alterColumnType(o,d,l,p)}).map(c=>gg.getInstance([c],!0,!1))},"getUpdateTypesScriptDtos");zc.exports={getUpdateTypesScriptDtos:Eg}});var eu=N((YS,Jc)=>{"use strict";var{AlterScriptDto:Zc}=re(),Tg=i((t,e)=>r=>{let{getFullTableName:n,wrapInQuotes:s}=L()(t),a=n(r),o=r.required||[],c=r.role.required||[],u=t.difference(o,c),l=t.difference(c,o),d=t.toPairs(r.properties).filter(([m,f])=>{let h=f.compMod.oldField.name,T=l.includes(h);return u.includes(m)&&!T}).map(([m])=>e.setNotNullConstraint(a,s(m))).map(m=>Zc.getInstance([m],!0,!1)),p=t.toPairs(r.properties).filter(([m,f])=>{let h=f.compMod.oldField.name,T=l.includes(h),_=u.includes(m);return T&&!_}).map(([m])=>e.dropNotNullConstraint(a,s(m))).map(m=>Zc.getInstance([m],!0,!0));return[...d,...p]},"getModifyNonNullColumnsScriptDtos");Jc.exports={getModifyNonNullColumnsScriptDtos:Tg}});var nu=N((zS,ru)=>{"use strict";var{AlterScriptDto:tu}=re(),Sg=i((t,e)=>r=>{let{getFullColumnName:n,wrapComment:s}=L()(t);return t.toPairs(r.properties).filter(([a,o])=>{var d;let c=o.description,u=o.compMod.oldField.name,l=(d=r.role.properties[u])==null?void 0:d.description;return c&&(!l||c!==l)}).map(([a,o])=>{let c=o.description,u=s(c),l=n(r,a);return e.updateColumnComment(l,u)}).map(a=>tu.getInstance([a],!0,!1))},"getUpdatedCommentOnColumnScriptDtos"),Cg=i((t,e)=>r=>{let{getFullColumnName:n}=L()(t);return t.toPairs(r.properties).filter(([s,a])=>{var l;let o=a.description,c=a.compMod.oldField.name;return((l=r.role.properties[c])==null?void 0:l.description)&&!o}).map(([s,a])=>{let o=n(r,s);return e.dropColumnComment(o)}).map(s=>tu.getInstance([s],!0,!0))},"getDeletedCommentOnColumnScriptDtos"),Ag=i((t,e)=>r=>{let n=Sg(t,e)(r),s=Cg(t,e)(r);return[...n,...s]},"getModifiedCommentOnColumnScriptDtos");ru.exports={getModifiedCommentOnColumnScriptDtos:Ag}});var iu=N((ZS,su)=>{"use strict";var{AlterScriptDto:Ng}=re(),bg=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:a}=L()(t),o=s(r);return t.values(r.properties).filter(c=>n(c.compMod,["name"])).map(c=>{let u=a(c.compMod.oldField.name),l=a(c.compMod.newField.name);return e.renameColumn(o,u,l)}).map(c=>Ng.getInstance([c],!0,!1))},"getRenameColumnScriptDtos");su.exports={getRenameColumnScriptDtos:bg}});var qs=N((eC,au)=>{"use strict";var Rs=class Rs{didTransitionHappen;wasPkChangedInTransition;static noTransition(){return{didTransitionHappen:!1}}static transition(e){return{didTransitionHappen:!0,wasPkChangedInTransition:e}}};i(Rs,"KeyTransitionDto");var vs=Rs,ws=class ws{script;isDropScript;fullTableName;isActivated;constructor(e,r,n,s){this.script=e,this.isDropScript=n,this.fullTableName=r,this.isActivated=s}};i(ws,"KeyScriptModificationDto");var Os=ws;au.exports={KeyScriptModificationDto:Os,KeyTransitionDto:vs}});var pu=N((oC,lu)=>{"use strict";var{AlterScriptDto:Ig}=re(),{AlterCollectionDto:rC,AlterCollectionColumnDto:nC,AlterCollectionRoleCompModPKDto:sC,AlterCollectionColumnKeyOptionDto:iC,AlterCollectionRoleCompModPrimaryKey:aC}=$e(),{KeyTransitionDto:ge,KeyScriptModificationDto:er}=qs(),st=1,Ds=i(t=>`${t}_pkey`,"getDefaultConstraintName"),ou=i(t=>({constraintName:t.constraintName,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexInclude:t.indexInclude}),"extractOptionsForComparisonWithRegularPkOptions"),it=i(t=>(t.primaryKeyOptions||[]).map(r=>ou(r)),"getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions"),tr=i(t=>[ou(t)].filter(r=>Object.values(r).some(Boolean)),"getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions"),vg=i(t=>e=>{var d,p;let n=(((p=(d=e==null?void 0:e.role)==null?void 0:d.compMod)==null?void 0:p.primaryKey)||{}).old||[],s=n.flatMap(m=>m.compositePrimaryKey.map(f=>f.keyId));if(s.length!==st)return ge.noTransition();let a=s[0],o=Object.values(e.properties).find(m=>m.GUID===a);if(!o||!((o==null?void 0:o.primaryKey)&&!(o!=null&&o.compositePrimaryKey)))return ge.noTransition();let u=it(o),l=n.some(m=>{if(m.compositePrimaryKey.length!==st)return!1;let f=tr(m);return t(f).differenceWith(u,t.isEqual).isEmpty()});return ge.transition(!l)},"wasCompositePkChangedInTransitionFromCompositeToRegular"),Og=i(t=>e=>{var d,p;let n=(((p=(d=e==null?void 0:e.role)==null?void 0:d.compMod)==null?void 0:p.primaryKey)||{}).new||[],s=n.flatMap(m=>m.compositePrimaryKey.map(f=>f.keyId));if(s.length!==st)return ge.noTransition();let a=s[0],o=Object.values(e.role.properties).find(m=>m.GUID===a);if(!o||!((o==null?void 0:o.primaryKey)&&!(o!=null&&o.compositePrimaryKey)))return ge.noTransition();let u=it(o),l=n.some(m=>{if(m.compositePrimaryKey.length!==st)return!1;let f=tr(m);return t(f).differenceWith(u,t.isEqual).isEmpty()});return ge.transition(!l)},"wasCompositePkChangedInTransitionFromRegularToComposite"),Rg=i((t,e)=>t.constraintName?t.constraintName:Ds(e),"getConstraintNameForCompositePk"),wg=i(t=>(e,r,n)=>{let s=Rg(e,r),a=t.toPairs(n.role.properties).filter(([l,d])=>!!e.compositePrimaryKey.find(p=>p.keyId===d.GUID)).map(([l,d])=>({name:l,isActivated:d.isActivated})),o="",c="",u=[];return e.indexStorageParameters&&(o=e.indexStorageParameters),e.indexTablespace&&(c=e.indexTablespace),e.indexInclude&&(u=t.toPairs(n.role.properties).filter(([l,d])=>!!e.indexInclude.find(p=>p.keyId===d.GUID)).map(([l,d])=>({name:l,isActivated:d.isActivated}))),{name:s,keyType:"PRIMARY KEY",columns:a,include:u,storageParameters:o,tablespace:c}},"getCreateCompositePKDDLProviderConfig"),qg=i((t,e)=>r=>{var f,h;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a}=L()(t),o=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},c=o.new||[],u=o.old||[];if(c.length===0&&u.length===0)return[];let l=Og(t)(r);if(l.didTransitionHappen&&!l.wasPkChangedInTransition)return[];if(c.length===u.length&&t(u).differenceWith(c,t.isEqual).isEmpty())return[];let d=s(r),p=n(d),m=a(d);return c.map(T=>{let _=wg(t)(T,m,r),y=e.createKeyConstraint(p,r.isActivated,_);return new er(y.statement,p,!1,y.isActivated)}).filter(T=>!!T.script)},"getAddCompositePkScriptDtos"),Dg=i((t,e)=>r=>{var h,T;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.primaryKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let d=vg(t)(r);if(d.didTransitionHappen&&!d.wasPkChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let p=s(r),m=n(p),f=a(p);return l.map(_=>{let y=Ds(f);_.constraintName&&(y=_.constraintName);let A=o(y),S=e.dropKeyConstraint(m,A);return new er(S,m,!0,r.isActivated)}).filter(_=>!!_.script)},"getDropCompositePkScriptDtos"),xg=i((t,e)=>r=>{let n=Dg(t,e)(r),s=qg(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyCompositePkScriptDtos"),cu=i((t,e)=>{let r=t.primaryKeyOptions;if(r!=null&&r.length&&(r==null?void 0:r.length)>0){let n=r[0];if(n.constraintName)return n.constraintName}return Ds(e)},"getConstraintNameForRegularPk"),Pg=i(t=>(e,r,n,s)=>{let a=cu(r,n),o=[{name:e,isActivated:r.isActivated}],c="",u="",l=[],d=r.primaryKeyOptions;if(d!=null&&d.length&&(d==null?void 0:d.length)>0){let p=d[0];p.indexStorageParameters&&(c=p.indexStorageParameters),p.indexTablespace&&(u=p.indexTablespace),p.indexInclude&&(l=t.toPairs(s.role.properties).filter(([m,f])=>!!p.indexInclude.find(h=>h.keyId===f.GUID)).map(([m,f])=>({name:m,isActivated:f.isActivated})))}return{name:a,keyType:"PRIMARY KEY",columns:o,include:l,storageParameters:c,tablespace:u}},"getCreateRegularPKDDLProviderConfig"),Lg=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.primaryKey&&!e.compositePrimaryKey,o=!!(s!=null&&s.primaryKey);return a&&!o},"wasFieldChangedToBeARegularPk"),Mg=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.primaryKey&&!e.compositePrimaryKey,o=!!(s!=null&&s.primaryKey);if(!(a&&o))return ge.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},u=c.new||[],l=c.old||[],d=l.some(T=>T.compositePrimaryKey.some(_=>_.keyId===s.GUID)),p=u.some(T=>T.compositePrimaryKey.some(_=>_.keyId===e.GUID));if(a&&(d&&!p)){let T=it(e),_=l.some(y=>{if(y.compositePrimaryKey.length!==st)return!1;let A=tr(y);return t(A).differenceWith(T,t.isEqual).isEmpty()});return ge.transition(!_)}return ge.noTransition()},"wasRegularPkChangedInTransitionFromCompositeToRegular"),Fg=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=s.primaryKey&&!s.compositePrimaryKey,o=!!(e!=null&&e.primaryKey);if(!(a&&o))return ge.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.primaryKey)||{},u=c.new||[],d=(c.old||[]).some(T=>T.compositePrimaryKey.some(_=>_.keyId===s.GUID)),m=u.some(T=>T.compositePrimaryKey.some(_=>_.keyId===e.GUID))&&!d;if(a&&m){let T=it(s),_=u.some(y=>{if(y.compositePrimaryKey.length!==st)return!1;let A=tr(y);return t(A).differenceWith(T,t.isEqual).isEmpty()});return ge.transition(!_)}return ge.noTransition()},"wasRegularPkChangedInTransitionFromRegularToComposite"),Ug=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey),o=!e.primaryKey&&!e.compositePrimaryKey;return a&&o},"isFieldNoLongerARegularPk"),uu=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n]||{},a=e.primaryKey&&!e.compositePrimaryKey,o=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey);if(!(a&&o))return!1;let c=it(e),u=it(s);return!t(u).differenceWith(c,t.isEqual).isEmpty()},"wasRegularPkModified"),kg=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a}=L()(t),o=s(r),c=n(o),u=a(o);return t.toPairs(r.properties).filter(([l,d])=>{if(Lg(t)(d,r))return!0;let p=Mg(t)(d,r);return p.didTransitionHappen?p.wasPkChangedInTransition:uu(t)(d,r)}).map(([l,d])=>{let p=Pg(t)(l,d,u,r),m=e.createKeyConstraint(c,r.isActivated,p);return new er(m.statement,c,!1,m.isActivated)}).filter(l=>!!l.script)},"getAddPkScriptDtos"),$g=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=s(r),u=n(c),l=a(c);return t.toPairs(r.properties).filter(([d,p])=>{if(Ug(t)(p,r))return!0;let m=Fg(t)(p,r);return m.didTransitionHappen?m.wasPkChangedInTransition:uu(t)(p,r)}).map(([d,p])=>{let m=p.compMod.oldField.name,f=r.role.properties[m],h=o(cu(f,l)),T=e.dropKeyConstraint(u,h);return new er(T,u,!0,r.isActivated)}).filter(d=>!!d.script)},"getDropPkScriptDto"),Bg=i((t,e)=>r=>{let n=$g(t,e)(r),s=kg(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyPkScriptDtos"),Kg=i(t=>t.sort((e,r)=>e.fullTableName===r.fullTableName?Number(r.isDropScript)-Number(e.isDropScript):e.fullTableNamer=>{let n=xg(t,e)(r),s=Bg(t,e)(r),a=[...n,...s];return Kg(a).map(c=>Ig.getInstance([c.script],c.isActivated,c.isDropScript)).filter(Boolean)},"getModifyPkConstraintsScriptDtos");lu.exports={getModifyPkConstraintsScriptDtos:Gg}});var gu=N((fC,hu)=>{"use strict";var{AlterScriptDto:Vg}=re(),{AlterCollectionDto:uC,AlterCollectionColumnDto:lC,AlterCollectionRoleCompModUniqueKeyDto:pC,AlterCollectionColumnKeyOptionDto:mC,AlterCollectionRoleCompModUniqueKey:dC}=$e(),{KeyTransitionDto:ye,KeyScriptModificationDto:rr}=qs(),at=1,xs=i(t=>`${t}_ukey`,"getDefaultConstraintName"),mu=i(t=>({constraintName:t.constraintName,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexInclude:t.indexInclude}),"extractOptionsForComparisonWithRegularUniqueKeyOptions"),ot=i(t=>(t.uniqueKeyOptions||[]).map(r=>mu(r)),"getCustomPropertiesOfRegularUniqueKeyForComparisonWithRegularUniqueKeyOptions"),nr=i(t=>[mu(t)].filter(r=>Object.values(r).some(Boolean)),"getCustomPropertiesOfCompositeUniqueKeyForComparisonWithRegularUniqueKeyOptions"),Hg=i(t=>e=>{var d,p;let n=(((p=(d=e==null?void 0:e.role)==null?void 0:d.compMod)==null?void 0:p.uniqueKey)||{}).old||[],s=n.flatMap(m=>m.compositeUniqueKey.map(f=>f.keyId));if(s.length!==at)return ye.noTransition();let a=s[0],o=Object.values(e.properties).find(m=>m.GUID===a);if(!o||!((o==null?void 0:o.unique)&&!(o!=null&&o.compositeUniqueKey)))return ye.noTransition();let u=ot(o),l=n.some(m=>{if(m.compositeUniqueKey.length!==at)return!1;let f=nr(m);return t(f).differenceWith(u,t.isEqual).isEmpty()});return ye.transition(!l)},"wasCompositeUniqueKeyChangedInTransitionFromCompositeToRegular"),Wg=i(t=>e=>{var d,p;let n=(((p=(d=e==null?void 0:e.role)==null?void 0:d.compMod)==null?void 0:p.uniqueKey)||{}).new||[],s=n.flatMap(m=>m.compositeUniqueKey.map(f=>f.keyId));if(s.length!==at)return ye.noTransition();let a=s[0],o=Object.values(e.role.properties).find(m=>m.GUID===a);if(!o||!((o==null?void 0:o.unique)&&!(o!=null&&o.compositeUniqueKey)))return ye.noTransition();let u=ot(o),l=n.some(m=>{if(m.compositeUniqueKey.length!==at)return!1;let f=nr(m);return t(f).differenceWith(u,t.isEqual).isEmpty()});return ye.transition(!l)},"wasCompositeUniqueKeyChangedInTransitionFromRegularToComposite"),Qg=i((t,e)=>t.constraintName?t.constraintName:xs(e),"getConstraintNameForCompositeUniqueKey"),Yg=i(t=>(e,r,n,s)=>{let{clean:a,getDbVersion:o}=L()(t),c=Zt()(t,a),u=Qg(e,r),l=t.toPairs(n.role.properties).filter(([_,y])=>!!e.compositeUniqueKey.find(A=>A.keyId===y.GUID)).map(([_,y])=>({name:_,isActivated:y.isActivated})),d="",p="",m=[],f=e.deferrable,h=e.deferrableConstraintCheckTime;e.indexStorageParameters&&(d=e.indexStorageParameters),e.indexTablespace&&(p=e.indexTablespace),e.indexInclude&&(m=t.toPairs(n.role.properties).filter(([_,y])=>!!e.indexInclude.find(A=>A.keyId===y.GUID)).map(([_,y])=>({name:_,isActivated:y.isActivated})));let T=c.getUniqueKeyType(e,o(s));return{name:u,keyType:T,columns:l,include:m,storageParameters:d,tablespace:p,deferrable:f,deferrableConstraintCheckTime:h}},"getCreateCompositeUniqueKeyDDLProviderConfig"),jg=i((t,e)=>(r,n)=>{var h,T;let{getFullCollectionName:s,getSchemaOfAlterCollection:a,getEntityName:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.uniqueKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let d=Wg(t)(r);if(d.didTransitionHappen&&!d.wasUniqueKeyChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let p=a(r),m=s(p),f=o(p);return u.map(_=>{let y=Yg(t)(_,f,r,n),A=e.createKeyConstraint(m,r.isActivated,y);return new rr(A.statement,m,!1,A.isActivated)}).filter(_=>!!_.script)},"getAddCompositeUniqueKeyScriptDtos"),zg=i((t,e)=>r=>{var h,T;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=((T=(h=r==null?void 0:r.role)==null?void 0:h.compMod)==null?void 0:T.uniqueKey)||{},u=c.new||[],l=c.old||[];if(u.length===0&&l.length===0)return[];let d=Hg(t)(r);if(d.didTransitionHappen&&!d.wasUniqueKeyChangedInTransition)return[];if(u.length===l.length&&t(l).differenceWith(u,t.isEqual).isEmpty())return[];let p=s(r),m=n(p),f=a(p);return l.map(_=>{let y=xs(f);_.constraintName&&(y=_.constraintName);let A=o(y),S=e.dropKeyConstraint(m,A);return new rr(S,m,!0,r.isActivated)}).filter(_=>!!_.script)},"getDropCompositeUniqueKeyScriptDtos"),Xg=i((t,e)=>(r,n)=>{let s=zg(t,e)(r),a=jg(t,e)(r,n);return[...s,...a].filter(Boolean)},"getModifyCompositeUniqueKeyScriptDtos"),du=i((t,e)=>{let r=t.uniqueKeyOptions;if(r!=null&&r.length&&(r==null?void 0:r.length)>0){let n=r[0];if(n.constraintName)return n.constraintName}return xs(e)},"getConstraintNameForRegularUniqueKey"),Zg=i(t=>(e,r,n,s,a)=>{let{clean:o,getDbVersion:c}=L()(t),u=Zt()(t,o),l=du(r,n),d=[{name:e,isActivated:r.isActivated}],p="",m="",f=[],h="",T="",_="",y=r.uniqueKeyOptions;if(y!=null&&y.length&&(y==null?void 0:y.length)>0){let S=y[0];S.indexStorageParameters&&(p=S.indexStorageParameters),S.indexTablespace&&(m=S.indexTablespace),S.indexInclude&&(f=t.toPairs(s.role.properties).filter(([I,v])=>!!S.indexInclude.find(w=>w.keyId===v.GUID)).map(([I,v])=>({name:I,isActivated:v.isActivated}))),h=S.deferrable,T=S.deferrableConstraintCheckTime,_=S.nullsDistinct}let A=u.getUniqueKeyType({nullsDistinct:_},c(a));return{name:l,keyType:A,columns:d,include:f,storageParameters:p,tablespace:m,deferrable:h,deferrableConstraintCheckTime:T}},"getCreateRegularUniqueKeyDDLProviderConfig"),Jg=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)||s.compositeUniqueKey;return a&&!o},"wasFieldChangedToBeARegularUniqueKey"),ey=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)||s.compositeUniqueKey;if(!(a&&o))return ye.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.uniqueKey)||{},u=c.new||[],l=c.old||[],d=l.some(T=>T.compositeUniqueKey.some(_=>_.keyId===s.GUID)),p=u.some(T=>T.compositeUniqueKey.some(_=>_.keyId===e.GUID));if(a&&(d&&!p)){let T=ot(e),_=l.some(y=>{if(y.compositeUniqueKey.length!==at)return!1;let A=nr(y);return t(A).differenceWith(T,t.isEqual).isEmpty()});return ye.transition(!_)}return ye.noTransition()},"wasRegularUniqueKeyChangedInTransitionFromCompositeToRegular"),ty=i(t=>(e,r)=>{var f,h;let n=e.compMod.oldField.name,s=r.role.properties[n],a=s.unique&&!s.compositeUniqueKey,o=!!(e!=null&&e.unique);if(!(a&&o))return ye.noTransition();let c=((h=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:h.uniqueKey)||{},u=c.new||[],d=(c.old||[]).some(T=>T.compositeUniqueKey.some(_=>_.keyId===s.GUID)),m=u.some(T=>T.compositeUniqueKey.some(_=>_.keyId===e.GUID))&&!d;if(a&&m){let T=ot(s),_=u.some(y=>{if(y.compositeUniqueKey.length!==at)return!1;let A=nr(y);return t(A).differenceWith(T,t.isEqual).isEmpty()});return ye.transition(!_)}return ye.noTransition()},"wasRegularUniqueKeyChangedInTransitionFromRegularToComposite"),ry=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],a=(s==null?void 0:s.unique)&&!(s!=null&&s.compositeUniqueKey),o=!e.unique&&!e.compositeUniqueKey;return a&&o},"isFieldNoLongerARegularUniqueKey"),fu=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n]||{},a=e.unique&&!e.compositeUniqueKey,o=(s==null?void 0:s.unique)&&!(s!=null&&s.compositeUniqueKey);if(!(a&&o))return!1;let c=ot(e),u=ot(s);return!t(u).differenceWith(c,t.isEqual).isEmpty()},"wasRegularUniqueKeyModified"),ny=i((t,e)=>(r,n)=>{let{getFullCollectionName:s,getSchemaOfAlterCollection:a,getEntityName:o}=L()(t),c=a(r),u=s(c),l=o(c);return t.toPairs(r.properties).filter(([d,p])=>{if(Jg(t)(p,r))return!0;let m=ey(t)(p,r);return m.didTransitionHappen?m.wasUniqueKeyChangedInTransition:fu(t)(p,r)}).map(([d,p])=>{let m=Zg(t)(d,p,l,r,n),f=e.createKeyConstraint(u,r.isActivated,m);return new rr(f.statement,u,!1,f.isActivated)}).filter(d=>!!d.script)},"getAddUniqueKeyScriptDtos"),sy=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:a,wrapInQuotes:o}=L()(t),c=s(r),u=n(c),l=a(c);return t.toPairs(r.properties).filter(([d,p])=>{if(ry(t)(p,r))return!0;let m=ty(t)(p,r);return m.didTransitionHappen?m.wasUniqueKeyChangedInTransition:fu(t)(p,r)}).map(([d,p])=>{let m=p.compMod.oldField.name,f=r.role.properties[m],h=o(du(f,l)),T=e.dropKeyConstraint(u,h);return new rr(T,u,!0,r.isActivated)}).filter(d=>!!d.script)},"getDropUniqueKeyScriptDto"),iy=i((t,e)=>(r,n)=>{let s=sy(t,e)(r),a=ny(t,e)(r,n);return[...s,...a].filter(Boolean)},"getModifyUniqueKeyScriptDtos"),ay=i(t=>t.sort((e,r)=>e.fullTableName===r.fullTableName?Number(r.isDropScript)-Number(e.isDropScript):e.fullTableName({collection:r,dbVersion:n})=>{let s=Xg(t,e)(r,n),a=iy(t,e)(r,n),o=[...s,...a];return ay(o).map(u=>Vg.getInstance([u.script],u.isActivated,u.isDropScript)).filter(Boolean)},"getModifyUniqueKeyConstraintsScriptDtos");hu.exports={getModifyUniqueKeyConstraintsScriptDtos:oy}});var Nu=N((_C,Au)=>{"use strict";var{AlterCollectionDto:gC}=$e(),{AlterIndexDto:yC}=ps(),{AlterScriptDto:ct}=re(),cy=i(({_:t})=>({columnId:e,collection:r})=>{var c,u,l;let n=t.toPairs(((c=r==null?void 0:r.role)==null?void 0:c.properties)||(r==null?void 0:r.properties)||{}).map(([d,p])=>({...p,name:d})),s=(((l=(u=r==null?void 0:r.role)==null?void 0:u.compMod)==null?void 0:l.oldProperties)||[]).map(d=>({...d,GUID:d.id})),o=(n.length>0?n:s).find(d=>d.GUID===e);if(o)return o.name},"getColumnNameById"),yu=i(({_:t})=>({columns:e,collection:r})=>(e||[]).map(n=>({...n,name:cy({_:t})({columnId:n.keyId,collection:r})})).filter(n=>!!n.name),"setNamesToColumns"),uy=i(({_:t})=>({index:e,collection:r})=>{let{getSchemaNameFromCollection:n}=L()(t),s=n({collection:r}),a=yu({_:t})({columns:e.columns,collection:r}),o=yu({_:t})({columns:e.include,collection:r});return{...e,schemaName:s,columns:a,include:o}},"mapIndexToFeIndexDto"),_u=i(({_:t})=>({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})=>{let s=t.pick(r,n),a=t.pick(e,n);return!t.isEqual(s,a)},"areIndexesDifferent"),ly=i(({_:t})=>({oldIndex:e,newIndex:r})=>{let n=["index_method","columns","include","nullsDistinct","where"];return _u({_:t})({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})},"shouldDropAndRecreateIndex"),py=i(({_:t})=>({oldIndex:e,newIndex:r})=>{let n=["indxName","index_tablespace_name","index_storage_parameter"];return _u({_:t})({oldIndex:e,newIndex:r,indexPropertiesToCompare:n})},"shouldAlterIndex"),Ps=i(({oldIndex:t,newIndex:e})=>t.id===e.id||t.indxName===e.indxName,"areOldIndexDtoAndNewIndexDtoDescribingSameDatabaseIndex"),Eu=i(({_:t,ddlProvider:e})=>({index:r,collection:n,additionalDataForDdlProvider:s})=>{let{dbData:a,tableName:o,isParentActivated:c}=s,u=uy({_:t})({index:r,collection:n}),l=e.createIndex(o,u,a,c),d=u.isActivated&&c;return ct.getInstance([l],d,!1)},"getCreateIndexScriptDto"),Tu=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l;let s=((o=r==null?void 0:r.role)==null?void 0:o.Indxs)||[],a=((l=(u=(c=r==null?void 0:r.role)==null?void 0:c.compMod)==null?void 0:u.Indxs)==null?void 0:l.old)||[];return s.filter(d=>!a.find(m=>Ps({oldIndex:m,newIndex:d}))).map(d=>Eu({_:t,ddlProvider:e})({index:d,collection:r,additionalDataForDdlProvider:n})).filter(Boolean)},"getAddedIndexesScriptDtos"),Su=i(({_:t,ddlProvider:e})=>({index:r,additionalDataForDdlProvider:n})=>{let{getNamePrefixedWithSchemaName:s}=L()(t),{isParentActivated:a,schemaName:o}=n,c=s(r.indxName,o),u=e.dropIndex({indexName:c}),l=r.isActivated&&a;return ct.getInstance([u],l,!0)},"getDeleteIndexScriptDto"),my=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l,d,p;let s=((u=(c=(o=r==null?void 0:r.role)==null?void 0:o.compMod)==null?void 0:c.Indxs)==null?void 0:u.new)||[];return(((p=(d=(l=r==null?void 0:r.role)==null?void 0:l.compMod)==null?void 0:d.Indxs)==null?void 0:p.old)||[]).filter(m=>!s.find(h=>Ps({oldIndex:m,newIndex:h}))).map(m=>Su({_:t,ddlProvider:e})({index:m,additionalDataForDdlProvider:n})).filter(Boolean)},"getDeletedIndexesScriptDtos"),dy=i(({_:t,ddlProvider:e})=>({newIndex:r,oldIndex:n,additionalDataForDdlProvider:s})=>{let a=[],{isParentActivated:o,schemaName:c}=s,u=r.isActivated&&o;if(!t.isEqual(r.indxName,n.indxName)){let m=e.alterIndexRename({schemaName:c,oldIndexName:n.indxName,newIndexName:r.indxName}),f=ct.getInstance([m],u,!1);a.push(f)}if(!t.isEqual(r.index_tablespace_name,n.index_tablespace_name)){let m=e.alterIndexTablespace({schemaName:c,indexName:r.indxName,tablespaceName:r.index_tablespace_name}),f=ct.getInstance([m],u,!1);a.push(f)}if(!t.isEqual(r.index_storage_parameter,n.index_storage_parameter)){let m=e.alterIndexStorageParams({schemaName:c,indexName:r.indxName,index:r}),f=ct.getInstance([m],u,!1);a.push(f);let h=e.reindexIndex({schemaName:c,indexName:r.indxName}),T=ct.getInstance([h],u,!1);a.push(T)}return a.filter(Boolean)},"getAlterIndexScriptDtos"),fy=i(({_:t,ddlProvider:e})=>({collection:r,additionalDataForDdlProvider:n})=>{var o,c,u,l,d,p;let s=((u=(c=(o=r==null?void 0:r.role)==null?void 0:o.compMod)==null?void 0:c.Indxs)==null?void 0:u.new)||[],a=((p=(d=(l=r==null?void 0:r.role)==null?void 0:l.compMod)==null?void 0:d.Indxs)==null?void 0:p.old)||[];return s.map(m=>{let f=a.find(h=>Ps({oldIndex:h,newIndex:m}));if(f)return{newIndex:m,oldIndex:f}}).filter(Boolean).flatMap(({newIndex:m,oldIndex:f})=>{if(ly({_:t})({newIndex:m,oldIndex:f})){let _=Su({_:t,ddlProvider:e})({index:f,additionalDataForDdlProvider:n}),y=Eu({_:t,ddlProvider:e})({index:m,collection:r,additionalDataForDdlProvider:n});return[_,y]}return py({_:t})({oldIndex:f,newIndex:m})?dy({_:t,ddlProvider:e})({oldIndex:f,newIndex:m,additionalDataForDdlProvider:n}):[]}).filter(Boolean)},"getModifiedIndexesScriptDtos"),hy=i(({_:t,ddlProvider:e})=>({collection:r,dbVersion:n})=>{let s=Cu({_:t,dbVersion:n,collection:r}),a=my({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s}),o=Tu({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s}),c=fy({_:t,ddlProvider:e})({collection:r,additionalDataForDdlProvider:s});return[...a,...o,...c].filter(Boolean)},"getModifyIndexesScriptDtos"),Cu=i(({_:t,dbVersion:e,collection:r})=>{var s,a,o;let{getSchemaNameFromCollection:n}=L()(t);return{dbData:{dbVersion:e},tableName:((a=(s=r==null?void 0:r.compMod)==null?void 0:s.collectionName)==null?void 0:a.new)||((o=r==null?void 0:r.role)==null?void 0:o.name)||"",schemaName:n({collection:r})||"",isParentActivated:r.isActivated}},"getAdditionalDataForDdlProvider");Au.exports={getModifyIndexesScriptDtos:hy,getAddedIndexesScriptDtos:Tu,getAdditionalDataForDdlProvider:Cu}});var bt=N((TC,bu)=>{"use strict";bu.exports=t=>{let{createColumnDefinition:e}=t.require("@hackolade/ddl-fe-utils"),r=i(s=>s.$ref?s.$ref.split("/").pop():s.mode||s.childType||s.type,"getType");return{createColumnDefinitionBySchema:i(({name:s,jsonSchema:a,parentJsonSchema:o,ddlProvider:c,schemaData:u,definitionJsonSchema:l})=>e({name:s,jsonSchema:a,parentJsonSchema:o,ddlProvider:c,schemaData:u,definitionJsonSchema:l,getType:r}),"createColumnDefinitionBySchema")}}});var wu=N((AC,Ru)=>{"use strict";var{getModifyCheckConstraintScriptDtos:gy}=Wc(),{getModifyEntityCommentsScriptDtos:yy}=jc(),{getUpdateTypesScriptDtos:_y}=Xc(),{getModifyNonNullColumnsScriptDtos:Ey}=eu(),{getModifiedCommentOnColumnScriptDtos:Ty}=nu(),{getRenameColumnScriptDtos:Sy}=iu(),{AlterScriptDto:sr}=re(),{AlterCollectionDto:CC}=$e(),{getModifyPkConstraintsScriptDtos:Cy}=pu(),{getModifyUniqueKeyConstraintsScriptDtos:Ay}=gu(),{getModifyIndexesScriptDtos:Ny,getAddedIndexesScriptDtos:by,getAdditionalDataForDdlProvider:Iy}=Nu(),vy=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{getEntityName:c}=L()(o),{createColumnDefinitionBySchema:u}=bt()(t),l=ne()(null,null,t),{getDefinitionByReference:d}=t.require("@hackolade/ddl-fe-utils"),m={schemaName:a.compMod.keyspaceName,dbVersion:e},f={...a,...o.omit(a==null?void 0:a.role,"properties")||{}},h=o.toPairs(f.properties).map(([I,v])=>{let w=d({propertySchema:v,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return u({name:I,jsonSchema:v,parentJsonSchema:f,ddlProvider:l,schemaData:m,definitionJsonSchema:w})}),T=(f.chkConstr||[]).map(I=>l.createCheckConstraint(l.hydrateCheckConstraint(I))),_={name:c(f),columns:h.map(l.convertColumnDefinition),checkConstraints:T,foreignKeyConstraints:[],schemaData:m,columnDefinitions:h,dbData:{dbVersion:e}},y=l.hydrateTable({tableData:_,entityData:[f],jsonSchema:f}),A=vu({_:o,ddlProvider:l,collection:a,dbVersion:e}).flatMap(({scripts:I})=>I.map(({script:v})=>v)),S=l.createTable(y,f.isActivated);return sr.getInstance([S,...A],!0,!1)},"getAddCollectionScriptDto"),Oy=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{getFullTableName:s}=L()(r),a=s(e),o=n.dropTable(a);return sr.getInstance([o],!0,!0)},"getDeleteCollectionScriptDto"),Ry=i(({app:t,dbVersion:e})=>r=>{let n=t.require("lodash"),s=ne()(null,null,t),a=gy(n,s)(r),o=yy(n,s)(r),c=Cy(n,s)(r),u=Ay({_:n,ddlProvider:s})({collection:r,dbVersion:e}),l=Ny({_:n,ddlProvider:s})({collection:r,dbVersion:e});return[...a,...o,...c,...u,...l].filter(Boolean)},"getModifyCollectionScriptDtos"),Iu=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>(a,o)=>{var I;let c=t.require("lodash"),{getEntityName:u,getNamePrefixedWithSchemaName:l}=L()(c),{createColumnDefinitionBySchema:d}=bt()(t),p=ne()(null,null,t),{getDefinitionByReference:m}=t.require("@hackolade/ddl-fe-utils"),f={...a,...c.omit(a==null?void 0:a.role,"properties")||{}},h=u(f),T=(I=f.compMod)==null?void 0:I.keyspaceName,_=l(h,T),y={schemaName:T,dbVersion:e},A=c.toPairs(a.properties).filter(([v,w])=>o([v,w])).map(([v,w])=>{let $=m({propertySchema:w,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return d({name:v,jsonSchema:w,parentJsonSchema:f,ddlProvider:p,schemaData:y,definitionJsonSchema:$})}).map(p.convertColumnDefinition).map(v=>p.addColumn(_,v)).map(v=>sr.getInstance([v],!0,!1)),S=vu({_:c,ddlProvider:p,collection:a});return A.concat(S).filter(Boolean)},"getAddColumnsByConditionScriptDtos"),vu=i(({_:t,ddlProvider:e,dbVersion:r,collection:n})=>{var l,d;let s=((l=n==null?void 0:n.role)==null?void 0:l.Indxs)||[],a={...n==null?void 0:n.properties,...(d=n==null?void 0:n.role)==null?void 0:d.properties},o=Object.values(a).map(({GUID:p})=>p);if(s.length===0||o.length===0)return[];if(!s.some(({columns:p})=>p.find(({keyId:m})=>o.includes(m))))return[];let u=Iy({_:t,dbVersion:r,collection:n});return by({_:t,ddlProvider:e})({collection:n,additionalDataForDdlProvider:u})},"getNewlyCreatedIndexesScripts"),wy=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>Iu({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(a,([o,c])=>!c.compMod),"getAddColumnScriptDtos"),Ou=i(t=>(e,r)=>{var m;let n=t.require("lodash"),s=ne()(null,null,t),{getEntityName:a,getNamePrefixedWithSchemaName:o,wrapInQuotes:c}=L()(n),u={...e,...n.omit(e==null?void 0:e.role,"properties")||{}},l=a(u),d=(m=u.compMod)==null?void 0:m.keyspaceName,p=o(l,d);return n.toPairs(e.properties).filter(([f,h])=>r([f,h])).map(([f])=>{let h=c(f);return s.dropColumn(p,h)}).map(f=>sr.getInstance([f],!0,!0)).filter(Boolean)},"getDeleteColumnsByConditionScriptDtos"),qy=i(t=>e=>Ou(t)(e,([r,n])=>!n.compMod),"getDeleteColumnScriptDtos"),Dy=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash");return o.toPairs(a.properties).filter(([c,u])=>{let l=u.compMod.oldField.name,d=a.role.properties[l];return d.generatedColumn!==u.generatedColumn||d.columnGenerationExpression!==u.columnGenerationExpression}).flatMap(([c,u])=>{let l={...a,properties:o.fromPairs([[c,u]])},d=Ou(t)(l,()=>!0),p=Iu({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(l,()=>!0);return[...d,...p]}).filter(Boolean)},"getDropAndRecreateColumnsScriptDtos"),xy=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),c=ne()(null,null,t),u=Sy(o,c)(a),l=Dy({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(a);if(l.length)return[...u,...l].filter(Boolean);let d=_y(o,c)(a),p=Ey(o,c)(a),m=Ty(o,c)(a);return[...u,...d,...p,...m].filter(Boolean)},"getModifyColumnScriptDtos");Ru.exports={getAddCollectionScriptDto:vy,getDeleteCollectionScriptDto:Oy,getModifyCollectionScriptDtos:Ry,getAddColumnScriptDtos:wy,getDeleteColumnScriptDtos:qy,getModifyColumnScriptDtos:xy}});var Du=N((bC,qu)=>{"use strict";var{AlterScriptDto:We}=re(),Py=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{createColumnDefinitionBySchema:c}=bt()(t),u=ne()(null,null,t),{getDefinitionByReference:l}=t.require("@hackolade/ddl-fe-utils"),d={dbVersion:e},p=o.toPairs(a.properties||{}).map(([T,_])=>{let y=l({propertySchema:_,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:T,jsonSchema:_,parentJsonSchema:a,ddlProvider:u,schemaData:d,definitionJsonSchema:y})}),f={...c({name:a.code||a.name,jsonSchema:a,parentJsonSchema:{required:[]},definitionJsonSchema:{},ddlProvider:u,schemaData:d}),properties:p},h=u.createUdt(f);return We.getInstance([h],!0,!1)},"getCreateUdtScriptDto"),Ly=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{getUdtName:s,wrapInQuotes:a}=L()(r),o=a(s(e));if(e.type==="domain"){let c=n.dropDomain(o);return We.getInstance([c],!0,!0)}else{let c=n.dropType(o);return We.getInstance([c],!0,!0)}},"getDeleteUdtScriptDto"),My=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>a=>{let o=t.require("lodash"),{createColumnDefinitionBySchema:c}=bt()(t),{getUdtName:u,wrapInQuotes:l}=L()(o),d=ne()(null,null,t),{getDefinitionByReference:p}=t.require("@hackolade/ddl-fe-utils"),m=l(u(a)),f={dbVersion:e};return o.toPairs(a.properties).filter(([h,T])=>!T.compMod).map(([h,T])=>{let _=p({propertySchema:T,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:h,jsonSchema:T,parentJsonSchema:{required:[]},ddlProvider:d,schemaData:f,definitionJsonSchema:_})}).map(d.convertColumnDefinition).map(h=>d.alterTypeAddAttribute(m,h)).map(h=>We.getInstance([h],!0,!1)).filter(Boolean)},"getAddColumnToTypeScriptDtos"),Fy=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{wrapInQuotes:s}=L()(r),a=s(e.code||e.name);return r.toPairs(e.properties).filter(([o,c])=>!c.compMod).map(([o])=>n.alterTypeDropAttribute(a,s(o))).map(o=>We.getInstance([o],!0,!0)).filter(Boolean)},"getDeleteColumnFromTypeScriptDtos"),Uy=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{checkFieldPropertiesChanged:s,wrapInQuotes:a}=L()(r),o=a(e.code||e.name),c=r.values(e.properties).filter(l=>s(l.compMod,["name"])).map(l=>{let d=a(l.compMod.oldField.name),p=a(l.compMod.newField.name);return n.alterTypeRenameAttribute(o,d,p)}).map(l=>We.getInstance([l],!0,!1)),u=r.toPairs(e.properties).filter(([l,d])=>s(d.compMod,["type","mode"])).map(([l,d])=>{let p=a(l),m=d.compMod.newField.mode||d.compMod.newField.type;return n.alterTypeChangeAttributeType(o,p,m)}).map(l=>We.getInstance([l],!0,!1));return[...c,...u].filter(Boolean)},"getModifyColumnOfTypeScriptDtos");qu.exports={getCreateUdtScriptDto:Py,getDeleteUdtScriptDto:Ly,getAddColumnToTypeScriptDtos:My,getDeleteColumnFromTypeScriptDtos:Fy,getModifyColumnOfTypeScriptDtos:Uy}});var Mu=N((vC,Lu)=>{"use strict";var{AlterScriptDto:xu}=re(),Pu=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),ky=i((t,e)=>r=>{let{getFullViewName:n,wrapComment:s}=L()(t),a=Pu(r);if(a.new&&a.new!==a.old){let o=s(a.new),c=n(r),u=e.updateViewComment(c,o);return xu.getInstance([u],!0,!1)}},"getUpsertCommentsScriptDto"),$y=i((t,e)=>r=>{let n=Pu(r),{getFullViewName:s}=L()(t);if(n.old&&!n.new){let a=s(r),o=e.dropViewComment(a);return xu.getInstance([o],!0,!0)}},"getDropCommentsScriptDto"),By=i((t,e)=>r=>{let n=ky(t,e)(r),s=$y(t,e)(r);return[n,s].filter(Boolean)},"getModifyViewCommentsScriptDtos");Lu.exports={getModifyViewCommentsScriptDtos:By}});var ku=N((RC,Uu)=>{"use strict";var{getModifyViewCommentsScriptDtos:Ky}=Mu(),{AlterScriptDto:Fu}=re(),Gy=i(t=>e=>{let r=ne()(null,null,t),n={name:e.code||e.name,keys:[],schemaData:{schemaName:""}},s=r.hydrateView({viewData:n,entityData:[e]}),a=r.createView(s,{},e.isActivated);return Fu.getInstance([a],!0,!1)},"getAddViewScriptDto"),Vy=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t),{wrapInQuotes:s}=L()(r),a=s(e.code||e.name),o=n.dropView(a);return Fu.getInstance([o],!0,!0)},"getDeleteViewScriptDto"),Hy=i(t=>e=>{let r=t.require("lodash"),n=ne()(null,null,t);return[...Ky(r,n)(e)].filter(Boolean)},"getModifyViewScriptDtos");Uu.exports={getAddViewScriptDto:Gy,getDeleteViewScriptDto:Vy,getModifyViewScriptDtos:Hy}});var Bu=N((qC,$u)=>{"use strict";var Ks=class Ks{isActivated;name};i(Ks,"AlterRelationshipFKField");var Ls=Ks,Gs=class Gs{bucket;collection};i(Gs,"AlterRelationshipParentDto");var Ms=Gs,Vs=class Vs{bucket;collection};i(Vs,"AlterRelationshipChildDto");var Fs=Vs,Hs=class Hs{relationshipOnDelete;relationshipOnUpdate;relationshipMatch};i(Hs,"AlterRelationshipCustomProperties");var Us=Hs,Ws=class Ws{created;deleted;modified;parent;child;name;description;customProperties;isActivated};i(Ws,"AlterRelationshipRoleCompModDto");var ks=Ws,Qs=class Qs{id;name;relationshipType;parentField;parentCardinality;childField;isActivated;childCardinality;parentCollection;childCollection;hackoladeStyles;compMod;roleType};i(Qs,"AlterRelationshipRoleDto");var $s=Qs,Ys=class Ys{type;isActivated;unique;subtype;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(Ys,"AlterRelationshipDto");var Bs=Ys;$u.exports={AlterRelationshipRoleCompModDto:ks,AlterRelationshipRoleDto:$s,AlterRelationshipDto:Bs,AlterRelationshipFKField:Ls,AlterRelationshipParentDto:Ms,AlterRelationshipChildDto:Fs,AlterRelationshipCustomProperties:Us}});var Qu=N((PC,Wu)=>{"use strict";var{AlterScriptDto:js}=re(),{AlterRelationshipDto:xC}=Bu(),ir=i(t=>t.role.name,"getRelationshipName"),Wy=i(t=>e=>{let{getNamePrefixedWithSchemaName:r}=L()(t),n=e.role.compMod,s=n.child.bucket.name,a=n.child.collection.name;return r(a,s)},"getFullChildTableName"),Ku=i((t,e)=>r=>{var a,o,c,u,l;let n=r.role.compMod,s=((a=n.name)==null?void 0:a.new)||ir(r)||"";return t.createForeignKey({name:s,foreignKey:n.child.collection.fkFields,primaryKey:n.parent.collection.fkFields,customProperties:(o=n.customProperties)==null?void 0:o.new,foreignTable:n.child.collection.name,foreignSchemaName:n.child.bucket.name,foreignTableActivated:n.child.collection.isActivated,primaryTable:n.parent.collection.name,primarySchemaName:n.parent.bucket.name,primaryTableActivated:n.parent.collection.isActivated,isActivated:!!((l=(u=(c=r.role)==null?void 0:c.compMod)==null?void 0:u.isActivated)!=null&&l.new)})},"getAddSingleForeignKeyStatementDto"),Gu=i(t=>{var r,n,s,a,o,c,u,l,d,p,m;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.new)||ir(t),(n=e.parent)==null?void 0:n.bucket,(s=e.parent)==null?void 0:s.collection,(c=(o=(a=e.parent)==null?void 0:a.collection)==null?void 0:o.fkFields)==null?void 0:c.length,(u=e.child)==null?void 0:u.bucket,(l=e.child)==null?void 0:l.collection,(m=(p=(d=e.child)==null?void 0:d.collection)==null?void 0:p.fkFields)==null?void 0:m.length].every(f=>!!f):!1},"canRelationshipBeAdded"),Qy=i((t,e)=>r=>r.filter(n=>Gu(n)).map(n=>{let s=Ku(t,e)(n);return js.getInstance([s.statement],s.isActivated,!1)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getAddForeignKeyScriptDtos"),Vu=i((t,e)=>r=>{var p,m,f,h;let{wrapInQuotes:n}=L()(e),s=r.role.compMod,a=Wy(e)(r),o=((p=s.name)==null?void 0:p.old)||ir(r)||"",c=n(o),u=t.dropForeignKey(a,c),l=!!((h=(f=(m=r.role)==null?void 0:m.compMod)==null?void 0:f.isActivated)!=null&&h.new),d=s.child.collection.isActivated;return{statement:u,isActivated:l&&d}},"getDeleteSingleForeignKeyStatementDto"),Hu=i(t=>{var r,n,s;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.old)||ir(t),(n=e.child)==null?void 0:n.bucket,(s=e.child)==null?void 0:s.collection].every(a=>!!a):!1},"canRelationshipBeDeleted"),Yy=i((t,e)=>r=>r.filter(n=>Hu(n)).map(n=>{let s=Vu(t,e)(n);return js.getInstance([s.statement],s.isActivated,!0)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getDeleteForeignKeyScriptDtos"),jy=i((t,e)=>r=>r.filter(n=>Gu(n)&&Hu(n)).map(n=>{let s=Vu(t,e)(n),a=Ku(t,e)(n),o=a.isActivated&&s.isActivated;return js.getDropAndRecreateInstance(s.statement,a.statement,o)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getModifyForeignKeyScriptDtos");Wu.exports={getDeleteForeignKeyScriptDtos:Yy,getModifyForeignKeyScriptDtos:jy,getAddForeignKeyScriptDtos:Qy}});var si=N((MC,Yu)=>{"use strict";var ei=class ei{message;stack};i(ei,"PluginError");var zs=ei,ti=class ti{require};i(ti,"App");var Xs=ti,ri=class ri{log;clear};i(ri,"Logger");var Zs=ri,ni=class ni{jsonSchema;modelDefinitions;internalDefinitions;externalDefinitions;containerData;entityData;entities;views;viewData;relationships;collectionRefsDefinitionsMap;isUpdateScript;level;host;clusterId;accessToken;applyToInstanceQueryRequestTimeout;script;hiddenKeys;options;modelData};i(ni,"CoreData");var Js=ni;Yu.exports={App:Xs,CoreData:Js,Logger:Zs,PluginError:zs}});var zu=N((UC,ju)=>{"use strict";var di=class di{name;isActivated};i(di,"ContainerJsonSchema");var ii=di,fi=class fi{backgroundColor};i(fi,"ContainerStyles");var ai=fi,hi=class hi{collectionName;isActivated;bucketId;additionalProperties;tableIfNotExists};i(hi,"EntityData");var oi=hi,gi=class gi{$schema;type;GUID};i(gi,"InternalDefinitions");var ci=gi,yi=class yi{$schema;type;GUID};i(yi,"ModelDefinitions");var ui=yi,_i=class _i{$schema;type;GUID};i(_i,"ExternalDefinitions");var li=_i,Ei=class Ei{type;isActivated;mode;subtype;compositeKey;compositePartitionKey;compositeClusteringKey;compositePrimaryKey;compositeUniqueKey;GUID};i(Ei,"FieldJsonSchema");var pi=Ei,Ti=class Ti{$schema;type;title;properties;isActivated;additionalProperties;tableIfNotExists;GUID};i(Ti,"EntityJsonSchema");var mi=Ti;ju.exports={ContainerJsonSchema:ii,ContainerStyles:ai,EntityData:oi,InternalDefinitions:ci,ModelDefinitions:ui,ExternalDefinitions:li,FieldJsonSchema:pi,EntityJsonSchema:mi}});var ar=N(($C,Xu)=>{"use strict";Xu.exports=ne()});var Ju=N((KC,Zu)=>{"use strict";var{AlterScriptDto:It}=re(),{App:BC}=si(),zy="sequences",Xy=i(({app:t})=>({container:e})=>{var o;let r=t.require("lodash"),n=ar()(null,null,t),{getDbName:s}=L()(r),a=s([e.role]);return(((o=e.role)==null?void 0:o.sequences)||[]).map(c=>n.createSchemaSequence({schemaName:a,sequence:c})).map(c=>It.getInstance([c],!0,!1)).filter(Boolean)},"getAddContainerSequencesScriptDtos"),Zy=i(({app:t})=>({container:e})=>{var _,y;let r=t.require("lodash"),n=ar()(null,null,t),{getDbName:s,getGroupItemsByCompMode:a}=L()(r),o=s([e.role]),c=((y=(_=e.role)==null?void 0:_.compMod)==null?void 0:y[zy])||{},{new:u=[],old:l=[]}=c,{removed:d,added:p,modified:m}=a({newItems:u,oldItems:l}),f=d.map(A=>n.dropSchemaSequence({schemaName:o,sequence:A})).map(A=>It.getInstance([A],!0,!0)),h=p.map(A=>n.createSchemaSequence({schemaName:o,sequence:A})).map(A=>It.getInstance([A],!0,!1));return[...m.map(A=>{let S=r.find(l,{id:A.id})||{};return n.alterSchemaSequence({schemaName:o,sequence:A,oldSequence:S})}).map(A=>It.getInstance([A],!0,!1)),...f,...h].filter(Boolean)},"getModifyContainerSequencesScriptDtos"),Jy=i(({app:t})=>({container:e})=>{var o;let r=t.require("lodash"),n=ar()(null,null,t),{getDbName:s}=L()(r),a=s([e.role]);return(((o=e.role)==null?void 0:o.sequences)||[]).map(c=>n.dropSchemaSequence({schemaName:a,sequence:c})).map(c=>It.getInstance([c],!0,!0)).filter(Boolean)},"getDeleteContainerSequencesScriptDtos");Zu.exports={getAddContainerSequencesScriptDtos:Xy,getModifyContainerSequencesScriptDtos:Zy,getDeleteContainerSequencesScriptDtos:Jy}});var tl=N((XC,el)=>{"use strict";var{getAddContainerScriptDto:e_,getDeleteContainerScriptDto:t_,getModifyContainerScriptDtos:r_}=Vc(),{getAddCollectionScriptDto:n_,getDeleteCollectionScriptDto:s_,getAddColumnScriptDtos:i_,getDeleteColumnScriptDtos:a_,getModifyColumnScriptDtos:o_,getModifyCollectionScriptDtos:c_}=wu(),{getDeleteUdtScriptDto:u_,getCreateUdtScriptDto:l_,getAddColumnToTypeScriptDtos:p_,getDeleteColumnFromTypeScriptDtos:m_,getModifyColumnOfTypeScriptDtos:d_}=Du(),{getAddViewScriptDto:f_,getDeleteViewScriptDto:h_,getModifyViewScriptDtos:g_}=ku(),{getModifyForeignKeyScriptDtos:y_,getDeleteForeignKeyScriptDtos:__,getAddForeignKeyScriptDtos:E_}=Qu(),{AlterScriptDto:VC,ModificationScript:HC}=re(),{App:WC,CoreData:QC}=si(),{InternalDefinitions:YC,ModelDefinitions:jC,ExternalDefinitions:zC}=zu(),{getModifyContainerSequencesScriptDtos:T_,getDeleteContainerSequencesScriptDtos:S_,getAddContainerSequencesScriptDtos:C_}=Ju(),A_=i(({collection:t,app:e})=>{var u,l,d,p,m,f,h,T,_,y,A,S;let r=(p=(d=(l=(u=t.properties)==null?void 0:u.containers)==null?void 0:l.properties)==null?void 0:d.added)==null?void 0:p.items,n=(T=(h=(f=(m=t.properties)==null?void 0:m.containers)==null?void 0:f.properties)==null?void 0:h.deleted)==null?void 0:T.items,s=(S=(A=(y=(_=t.properties)==null?void 0:_.containers)==null?void 0:y.properties)==null?void 0:A.modified)==null?void 0:S.items,a=[].concat(r).filter(Boolean).map(I=>e_(e)(Object.keys(I.properties)[0])),o=[].concat(n).filter(Boolean).map(I=>t_(e)(Object.keys(I.properties)[0])),c=[].concat(s).filter(Boolean).map(I=>Object.values(I.properties)[0]).flatMap(I=>r_(e)(I));return[...a,...o,...c].filter(Boolean)},"getAlterContainersScriptDtos"),N_=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})=>{var T,_,y,A,S,I,v,w,$,b,q,G;let o=[].concat((A=(y=(_=(T=t.properties)==null?void 0:T.entities)==null?void 0:_.properties)==null?void 0:y.added)==null?void 0:A.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),c=[].concat((w=(v=(I=(S=t.properties)==null?void 0:S.entities)==null?void 0:I.properties)==null?void 0:v.deleted)==null?void 0:w.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),u=[].concat((G=(q=(b=($=t.properties)==null?void 0:$.entities)==null?void 0:b.properties)==null?void 0:q.modified)==null?void 0:G.items).filter(Boolean).map(P=>Object.values(P.properties)[0]),l=o.filter(P=>{var z;return(z=P.compMod)==null?void 0:z.created}).map(n_({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),d=c.filter(P=>{var z;return(z=P.compMod)==null?void 0:z.deleted}).map(s_(e)),p=u.flatMap(c_({app:e,dbVersion:r})),m=o.filter(P=>{var z;return!((z=P==null?void 0:P.compMod)!=null&&z.created)}).flatMap(i_({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),f=c.filter(P=>{var z;return!((z=P==null?void 0:P.compMod)!=null&&z.deleted)}).flatMap(a_(e)),h=u.flatMap(o_({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}));return[...l,...d,...p,...m,...f,...h].filter(Boolean)},"getAlterCollectionsScriptDtos"),b_=i((t,e)=>{var a,o,c,u,l,d,p,m,f,h,T,_;let r=[].concat((u=(c=(o=(a=t.properties)==null?void 0:a.views)==null?void 0:o.properties)==null?void 0:c.added)==null?void 0:u.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).filter(y=>{var A;return((A=y.compMod)==null?void 0:A.created)&&y.selectStatement}).map(f_(e)),n=[].concat((m=(p=(d=(l=t.properties)==null?void 0:l.views)==null?void 0:d.properties)==null?void 0:p.deleted)==null?void 0:m.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).map(h_(e)),s=[].concat((_=(T=(h=(f=t.properties)==null?void 0:f.views)==null?void 0:h.properties)==null?void 0:T.modified)==null?void 0:_.items).filter(Boolean).map(y=>Object.values(y.properties)[0]).map(y=>({...y,...y.role||{}})).flatMap(y=>g_(e)(y));return[...n,...r,...s].filter(Boolean)},"getAlterViewScriptDtos"),I_=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})=>{var p,m,f,h,T,_,y,A,S,I,v,w,$,b,q,G,P,z,Ae,le;let o=[].concat((h=(f=(m=(p=t.properties)==null?void 0:p.modelDefinitions)==null?void 0:m.properties)==null?void 0:f.added)==null?void 0:h.items).filter(Boolean).map(F=>Object.values(F.properties)[0]).map(F=>({...F,...e.require("lodash").omit(F.role,"properties")||{}})).filter(F=>{var Ne;return(Ne=F.compMod)==null?void 0:Ne.created}).map(l_({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),c=[].concat((A=(y=(_=(T=t.properties)==null?void 0:T.modelDefinitions)==null?void 0:_.properties)==null?void 0:y.deleted)==null?void 0:A.items).filter(Boolean).map(F=>Object.values(F.properties)[0]).map(F=>({...F,...e.require("lodash").omit(F.role,"properties")||{}})).filter(F=>{var Ne;return(Ne=F.compMod)==null?void 0:Ne.deleted}).map(u_(e)),u=[].concat((w=(v=(I=(S=t.properties)==null?void 0:S.modelDefinitions)==null?void 0:I.properties)==null?void 0:v.added)==null?void 0:w.items).filter(Boolean).map(F=>Object.values(F.properties)[0]).filter(F=>!F.compMod).map(F=>({...F,...e.require("lodash").omit(F.role,"properties")||{}})).filter(F=>F.childType==="composite").flatMap(p_({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a})),l=[].concat((G=(q=(b=($=t.properties)==null?void 0:$.modelDefinitions)==null?void 0:b.properties)==null?void 0:q.deleted)==null?void 0:G.items).filter(Boolean).map(F=>Object.values(F.properties)[0]).filter(F=>!F.compMod).map(F=>({...F,...e.require("lodash").omit(F.role,"properties")||{}})).filter(F=>F.childType==="composite").flatMap(m_(e)),d=[].concat((le=(Ae=(z=(P=t.properties)==null?void 0:P.modelDefinitions)==null?void 0:z.properties)==null?void 0:Ae.modified)==null?void 0:le.items).filter(Boolean).map(F=>Object.values(F.properties)[0]).filter(F=>!F.compMod).map(F=>({...F,...e.require("lodash").omit(F.role,"properties")||{}})).filter(F=>F.childType==="composite").flatMap(d_(e));return[...c,...o,...u,...l,...d].filter(Boolean)},"getAlterModelDefinitionsScriptDtos"),v_=i(({collection:t,app:e})=>{var d,p,m,f,h,T,_,y,A,S,I,v;let r=e.require("lodash"),n=ne()(null,null,e),s=[].concat((f=(m=(p=(d=t.properties)==null?void 0:d.relationships)==null?void 0:p.properties)==null?void 0:m.added)==null?void 0:f.items).filter(Boolean).map(w=>Object.values(w.properties)[0]).filter(w=>{var $,b;return(b=($=w==null?void 0:w.role)==null?void 0:$.compMod)==null?void 0:b.created}),a=[].concat((y=(_=(T=(h=t.properties)==null?void 0:h.relationships)==null?void 0:T.properties)==null?void 0:_.deleted)==null?void 0:y.items).filter(Boolean).map(w=>Object.values(w.properties)[0]).filter(w=>{var $,b;return(b=($=w==null?void 0:w.role)==null?void 0:$.compMod)==null?void 0:b.deleted}),o=[].concat((v=(I=(S=(A=t.properties)==null?void 0:A.relationships)==null?void 0:S.properties)==null?void 0:I.modified)==null?void 0:v.items).filter(Boolean).map(w=>Object.values(w.properties)[0]).filter(w=>{var $,b;return(b=($=w==null?void 0:w.role)==null?void 0:$.compMod)==null?void 0:b.modified}),c=__(n,r)(a),u=E_(n,r)(s),l=y_(n,r)(o);return[...c,...u,...l].filter(Boolean)},"getAlterRelationshipsScriptDtos"),O_=i(t=>{if(!t)return;let e=t.scripts.map(r=>({...r,script:(r.script||"").trim()})).filter(r=>!!r.script);if(e.length)return{...t,scripts:e}},"prettifyAlterScriptDto"),R_=i(({collection:t,app:e})=>{var u,l,d,p,m,f,h,T,_,y,A,S;let r=(p=(d=(l=(u=t.properties)==null?void 0:u.containers)==null?void 0:l.properties)==null?void 0:d.added)==null?void 0:p.items,n=(T=(h=(f=(m=t.properties)==null?void 0:m.containers)==null?void 0:f.properties)==null?void 0:h.deleted)==null?void 0:T.items,s=(S=(A=(y=(_=t.properties)==null?void 0:_.containers)==null?void 0:y.properties)==null?void 0:A.modified)==null?void 0:S.items,a=[].concat(r).filter(Boolean).map(I=>Object.values(I.properties)[0]).flatMap(I=>C_({app:e})({container:I})),o=[].concat(n).filter(Boolean).map(I=>Object.values(I.properties)[0]).flatMap(I=>S_({app:e})({container:I})),c=[].concat(s).filter(Boolean).map(I=>Object.values(I.properties)[0]).flatMap(I=>T_({app:e})({container:I}));return[...a,...o,...c].filter(Boolean)},"getAlterContainersSequencesScriptDtos"),w_=i((t,e)=>{var f;let r=JSON.parse(t.jsonSchema);if(!r)throw new Error('"comparisonModelCollection" is not found. Alter script can be generated only from Delta model');let n=JSON.parse(t.modelDefinitions),s=JSON.parse(t.internalDefinitions),a=JSON.parse(t.externalDefinitions),o=(f=t.modelData[0])==null?void 0:f.dbVersion,c=A_({collection:r,app:e}),u=N_({collection:r,app:e,dbVersion:o,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}),l=b_(r,e),d=I_({collection:r,app:e,dbVersion:o,modelDefinitions:n,internalDefinitions:s,externalDefinitions:a}),p=v_({collection:r,app:e}),m=R_({collection:r,app:e});return[...c,...d,...u,...m,...l,...p].filter(Boolean).map(h=>O_(h)).filter(Boolean)},"getAlterScriptDtos");el.exports={getAlterScriptDtos:w_}});var il=N((eA,sl)=>{"use strict";var{getAlterScriptDtos:or}=tl(),{AlterScriptDto:JC}=re(),rl=i(t=>(e,r)=>{let{commentIfDeactivated:n}=L()(t);return e.map(s=>s.isActivated===!1?s.scripts.map(a=>n(a.script,{isActivated:!1,isPartOfLine:!1})):r?s.scripts.map(a=>a.script):s.scripts.map(a=>n(a.script,{isActivated:!a.isDropScript,isPartOfLine:!1}))).flat().filter(Boolean).map(s=>s.trim()).filter(Boolean).join(` -`)},"joinAlterScriptDtosIntoScript"),wT=i((t,e)=>{var a,o;let r=e.require("lodash"),n=Tr(t,e),s=(o=(a=t.options)==null?void 0:a.additionalOptions)==null?void 0:o.some(c=>c.id==="applyDropStatements"&&c.value);return Yl(r)(n,s)},"buildEntityLevelAlterScript"),DT=i((t,e)=>Tr(t,e).some(n=>n.isActivated&&n.scripts.some(s=>s.isDropScript)),"doesEntityLevelAlterScriptContainDropStatements"),jl=i(t=>({...t,jsonSchema:t.collections[0],internalDefinitions:Object.values(t.internalDefinitions)[0]}),"mapCoreDataForContainerLevelScripts"),qT=i((t,e)=>{var o,c;let r=jl(t),n=e.require("lodash"),s=Tr(r,e),a=(c=(o=r.options)==null?void 0:o.additionalOptions)==null?void 0:c.some(u=>u.id==="applyDropStatements"&&u.value);return Yl(n)(s,a)},"buildContainerLevelAlterScript"),xT=i((t,e)=>{let r=jl(t);return Tr(r,e).some(s=>s.isActivated&&s.scripts.some(a=>a.isDropScript))},"doesContainerLevelAlterScriptContainDropStatements");zl.exports={buildEntityLevelAlterScript:wT,doesEntityLevelAlterScriptContainDropStatements:DT,buildContainerLevelAlterScript:qT,doesContainerLevelAlterScriptContainDropStatements:xT}});var Zl=Gc(),{createLogger:PT}=Nr(),LT=Hc(),{buildEntityLevelAlterScript:MT,buildContainerLevelAlterScript:FT,doesContainerLevelAlterScriptContainDropStatements:UT,doesEntityLevelAlterScriptContainDropStatements:kT}=Xl();module.exports={generateScript(t,e,r,n){try{let s=MT(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"PostgreSQL Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},generateViewScript(t,e,r,n){r(new Error("Forward-Engineering of delta model on view level is not supported"))},generateContainerScript(t,e,r,n){try{let s=FT(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"PostgreSQL Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},getDatabases(t,e,r,n){e.progress({message:"Find all databases"}),Zl.getDatabases(t,e,r,n)},applyToInstance(t,e,r,n){e.clear(),e.log("info",n.require("lodash").omit(t,"script","containerData"),"connectionInfo",t.hiddenKeys);let s=PT({title:"Apply to instance",hiddenKeys:t.hiddenKeys,logger:e});LT.applyToInstance(t,s,n).then(r,r)},testConnection(t,e,r,n){Zl.testConnection(t,e,r,n).then(r,r)},isDropInStatements(t,e,r,n){try{if(t.level==="container"){let s=UT(t,n);r(null,s)}else{let s=kT(t,n);r(null,s)}}catch(s){r({message:s.message,stack:s.stack})}}}; +`)},"joinAlterScriptDtosIntoScript"),q_=i((t,e)=>{var a,o;let r=e.require("lodash"),n=or(t,e),s=(o=(a=t.options)==null?void 0:a.additionalOptions)==null?void 0:o.some(c=>c.id==="applyDropStatements"&&c.value);return rl(r)(n,s)},"buildEntityLevelAlterScript"),D_=i((t,e)=>or(t,e).some(n=>n.isActivated&&n.scripts.some(s=>s.isDropScript)),"doesEntityLevelAlterScriptContainDropStatements"),nl=i(t=>({...t,jsonSchema:t.collections[0],internalDefinitions:Object.values(t.internalDefinitions)[0]}),"mapCoreDataForContainerLevelScripts"),x_=i((t,e)=>{var o,c;let r=nl(t),n=e.require("lodash"),s=or(r,e),a=(c=(o=r.options)==null?void 0:o.additionalOptions)==null?void 0:c.some(u=>u.id==="applyDropStatements"&&u.value);return rl(n)(s,a)},"buildContainerLevelAlterScript"),P_=i((t,e)=>{let r=nl(t);return or(r,e).some(s=>s.isActivated&&s.scripts.some(a=>a.isDropScript))},"doesContainerLevelAlterScriptContainDropStatements");sl.exports={buildEntityLevelAlterScript:q_,doesEntityLevelAlterScriptContainDropStatements:D_,buildContainerLevelAlterScript:x_,doesContainerLevelAlterScriptContainDropStatements:P_}});var al=Xo(),{createLogger:L_}=pr(),M_=Jo(),{buildEntityLevelAlterScript:F_,buildContainerLevelAlterScript:U_,doesContainerLevelAlterScriptContainDropStatements:k_,doesEntityLevelAlterScriptContainDropStatements:$_}=il();module.exports={generateScript(t,e,r,n){try{let s=F_(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"PostgreSQL Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},generateViewScript(t,e,r,n){r(new Error("Forward-Engineering of delta model on view level is not supported"))},generateContainerScript(t,e,r,n){try{let s=U_(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"PostgreSQL Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},getDatabases(t,e,r,n){e.progress({message:"Find all databases"}),al.getDatabases(t,e,r,n)},applyToInstance(t,e,r,n){e.clear(),e.log("info",n.require("lodash").omit(t,"script","containerData"),"connectionInfo",t.hiddenKeys);let s=L_({title:"Apply to instance",hiddenKeys:t.hiddenKeys,logger:e});M_.applyToInstance(t,s,n).then(r,r)},testConnection(t,e,r,n){al.testConnection(t,e,r,n).then(r,r)},isDropInStatements(t,e,r,n){try{if(t.level==="container"){let s=k_(t,n);r(null,s)}else{let s=$_(t,n);r(null,s)}}catch(s){r({message:s.message,stack:s.stack})}}}; diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index cefa7cf..ad82ec5 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -1,60 +1,60 @@ -var Qt=Object.defineProperty;var n=(s,$)=>Qt(s,"name",{value:$,configurable:!0});var _=(s,$)=>()=>($||s(($={exports:{}}).exports,$),$.exports);var et=_((cn,Je)=>{Je.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var nt=_((mn,tt)=>{tt.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var at=_((un,rt)=>{rt.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${locale}${collate}${characterClassification}${tablespace};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${noInherit}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}${tablespace}${deferrable}${deferrableConstraintCheckTime}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON${only} ${tableName}${using}${keys}${nullsDistinct}${options};\n",dropIndex:"DROP INDEX IF EXISTS ${indexName};\n",alterIndexRename:"ALTER INDEX IF EXISTS ${oldIndexName} RENAME TO ${newIndexName};\n",alterIndexTablespace:"ALTER INDEX IF EXISTS ${indexName} SET TABLESPACE ${tablespaceName};\n",alterIndexStorageParams:`ALTER INDEX IF EXISTS \${indexName} SET ( +"use strict";var Qt=Object.defineProperty;var n=(s,$)=>Qt(s,"name",{value:$,configurable:!0});var _=(s,$)=>()=>($||s(($={exports:{}}).exports,$),$.exports);var et=_((cn,Je)=>{"use strict";Je.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var nt=_((mn,tt)=>{"use strict";tt.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var at=_((un,rt)=>{"use strict";rt.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${locale}${collate}${characterClassification}${tablespace};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${noInherit}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}${tablespace}${deferrable}${deferrableConstraintCheckTime}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate}${deferrable}${deferrableConstraintCheckTime};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON${only} ${tableName}${using}${keys}${nullsDistinct}${options};\n",dropIndex:"DROP INDEX IF EXISTS ${indexName};\n",alterIndexRename:"ALTER INDEX IF EXISTS ${oldIndexName} RENAME TO ${newIndexName};\n",alterIndexTablespace:"ALTER INDEX IF EXISTS ${indexName} SET TABLESPACE ${tablespaceName};\n",alterIndexStorageParams:`ALTER INDEX IF EXISTS \${indexName} SET ( \${options} ); `,reindexIndex:"REINDEX INDEX ${indexName};\n",createView:"CREATE${orReplace}${temporary} VIEW ${name}${withOptions}\nAS ${selectStatement}${checkOption};\n\n${comment}\n",viewSelectStatement:"SELECT ${keys}\n FROM ${tableName}",dropView:"DROP VIEW IF EXISTS ${viewName};",createFunction:"CREATE${orReplace} FUNCTION ${name}\n (${parameters})\n RETURNS ${returnType}\n LANGUAGE ${language}\n${properties}AS $BODY$\n${definition}\n$BODY$;\n",createProcedure:"CREATE${orReplace} PROCEDURE ${name} (${parameters})\n LANGUAGE ${language}\nAS $BODY$\n${body}\n$BODY$;\n",createCompositeType:`CREATE TYPE \${name} AS ( \${columnDefinitions} ); -\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}",createTrigger:"CREATE${orReplace}${constraint} TRIGGER ${name} ${actionTiming} ${events}\n ON ${tableName}\n${options} EXECUTE ${functionKey} ${functionName};\n",createSequence:"CREATE${sequenceType} SEQUENCE${ifNotExists} ${name}${options};\n",dropSequence:"DROP SEQUENCE IF EXISTS ${name};\n",renameSequence:"ALTER SEQUENCE IF EXISTS ${name} RENAME TO ${newName};\n",setSequenceType:"ALTER SEQUENCE IF EXISTS ${name} SET ${sequenceType};\n",alterSequence:"ALTER SEQUENCE IF EXISTS ${name}${options};\n"}});var Se=_((ln,it)=>{var $e=class $e{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};n($e,"Sequence");var Ae=$e,fe=class fe{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};n(fe,"SequenceDto");var Ce=fe;it.exports={Sequence:Ae,SequenceDto:Ce}});var st=_((dn,ot)=>{var be=class be{sortOrder;nullsOrder;isActivated;keyId;collation;opclass};n(be,"AlterIndexColumnDto");var Ie=be,Le=class Le{keyId};n(Le,"AlterIndexIncludeColumnDto");var Oe=Le,he=class he{id;isActivated;index_method;ifNotExist;only;index_tablespace_name;indxName;columns;include;index_storage_parameter};n(he,"AlterIndexDto");var Re=he;ot.exports={AlterIndexDto:Re,AlterIndexColumnDto:Ie,AlterIndexIncludeColumnDto:Oe}});var mt=_((En,ct)=>{var{AlterIndexDto:Tn}=st(),Ve=class Ve{id;constraintName;indexStorageParameters;indexTablespace;indexInclude};n(Ve,"AlterCollectionColumnKeyOptionDto");var de=Ve,Ye=class Ye{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};n(Ye,"AlterCollectionColumnDto");var Pe=Ye,Be=class Be extends de{compositePrimaryKey};n(Be,"AlterCollectionRoleCompModPKDto");var Ue=Be,qe=class qe extends de{compositeUniqueKey};n(qe,"AlterCollectionRoleCompModUniqueKeyDto");var xe=qe,_e=class _e{new;old};n(_e,"AlterCollectionRoleCompModPrimaryKey");var Fe=_e,ke=class ke{new;old};n(ke,"AlterCollectionRoleCompModUniqueKey");var ve=ke,Ge=class Ge{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;table_tablespace_name;bucketId;compMod;name;roleType;patternProperties};n(Ge,"AlterCollectionRoleDto");var Ke=Ge,we=class we{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};n(we,"AlterCollectionDto");var Me=we;ct.exports={AlterCollectionDto:Me,AlterCollectionRoleDto:Ke,AlterCollectionColumnDto:Pe,AlterCollectionColumnKeyOptionDto:de,AlterCollectionRoleCompModPrimaryKey:Fe,AlterCollectionRoleCompModPKDto:Ue,AlterCollectionRoleCompModUniqueKeyDto:xe,AlterCollectionRoleCompModUniqueKey:ve}});var lt=_((yn,ut)=>{var Zt=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),Jt=Object.values(Zt);ut.exports={ReservedWordsAsArray:Jt}});var ue=_(($n,pt)=>{var{AlterCollectionDto:An,AlterCollectionRoleDto:Cn}=mt(),{ReservedWordsAsArray:en}=lt(),tn=/\t|\n|'|\f|\r/gm;pt.exports=s=>{let $=n(o=>s.get(o,"[0].code")||s.get(o,"[0].name",""),"getDbName"),O=n(o=>o&&(o.code||o.collectionName)||"","getEntityName"),u=n(o=>o&&(o.code||o.name)||"","getViewName"),R=n(o=>Object.assign({},s.get(o,"[0]",{}),{name:$(o)}),"getDbData"),P=n(o=>s.get(o,"[0].viewOn"),"getViewOn"),U=n((o,E=" ")=>o.split(` +\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}",createTrigger:"CREATE${orReplace}${constraint} TRIGGER ${name} ${actionTiming} ${events}\n ON ${tableName}\n${options} EXECUTE ${functionKey} ${functionName};\n",createSequence:"CREATE${sequenceType} SEQUENCE${ifNotExists} ${name}${options};\n",dropSequence:"DROP SEQUENCE IF EXISTS ${name};\n",renameSequence:"ALTER SEQUENCE IF EXISTS ${name} RENAME TO ${newName};\n",setSequenceType:"ALTER SEQUENCE IF EXISTS ${name} SET ${sequenceType};\n",alterSequence:"ALTER SEQUENCE IF EXISTS ${name}${options};\n"}});var Se=_((ln,it)=>{"use strict";var $e=class $e{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};n($e,"Sequence");var Ae=$e,fe=class fe{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};n(fe,"SequenceDto");var Ce=fe;it.exports={Sequence:Ae,SequenceDto:Ce}});var st=_((dn,ot)=>{"use strict";var be=class be{sortOrder;nullsOrder;isActivated;keyId;collation;opclass};n(be,"AlterIndexColumnDto");var Ie=be,Le=class Le{keyId};n(Le,"AlterIndexIncludeColumnDto");var Oe=Le,he=class he{id;isActivated;index_method;ifNotExist;only;index_tablespace_name;indxName;columns;include;index_storage_parameter};n(he,"AlterIndexDto");var Re=he;ot.exports={AlterIndexDto:Re,AlterIndexColumnDto:Ie,AlterIndexIncludeColumnDto:Oe}});var mt=_((En,ct)=>{"use strict";var{AlterIndexDto:Tn}=st(),Ve=class Ve{id;constraintName;indexStorageParameters;indexTablespace;indexInclude};n(Ve,"AlterCollectionColumnKeyOptionDto");var de=Ve,Ye=class Ye{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};n(Ye,"AlterCollectionColumnDto");var Pe=Ye,Be=class Be extends de{compositePrimaryKey};n(Be,"AlterCollectionRoleCompModPKDto");var Ue=Be,qe=class qe extends de{compositeUniqueKey};n(qe,"AlterCollectionRoleCompModUniqueKeyDto");var xe=qe,_e=class _e{new;old};n(_e,"AlterCollectionRoleCompModPrimaryKey");var Fe=_e,ke=class ke{new;old};n(ke,"AlterCollectionRoleCompModUniqueKey");var ve=ke,Ge=class Ge{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;table_tablespace_name;bucketId;compMod;name;roleType;patternProperties};n(Ge,"AlterCollectionRoleDto");var Ke=Ge,we=class we{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};n(we,"AlterCollectionDto");var Me=we;ct.exports={AlterCollectionDto:Me,AlterCollectionRoleDto:Ke,AlterCollectionColumnDto:Pe,AlterCollectionColumnKeyOptionDto:de,AlterCollectionRoleCompModPrimaryKey:Fe,AlterCollectionRoleCompModPKDto:Ue,AlterCollectionRoleCompModUniqueKeyDto:xe,AlterCollectionRoleCompModUniqueKey:ve}});var lt=_((yn,ut)=>{"use strict";var Zt=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),Jt=Object.values(Zt);ut.exports={ReservedWordsAsArray:Jt}});var ue=_(($n,pt)=>{"use strict";var{AlterCollectionDto:An,AlterCollectionRoleDto:Cn}=mt(),{ReservedWordsAsArray:en}=lt(),tn=/\t|\n|'|\f|\r/gm;pt.exports=s=>{let $=n(o=>s.get(o,"[0].code")||s.get(o,"[0].name",""),"getDbName"),O=n(o=>o&&(o.code||o.collectionName)||"","getEntityName"),u=n(o=>o&&(o.code||o.name)||"","getViewName"),R=n(o=>Object.assign({},s.get(o,"[0]",{}),{name:$(o)}),"getDbData"),P=n(o=>s.get(o,"[0].viewOn"),"getViewOn"),U=n((o,E=" ")=>o.split(` `).map(b=>E+b).join(` -`),"tab"),K=n((o,E)=>Object.keys(o).map(s.toLower).includes(s.toLower(E)),"hasType"),h=n(o=>({...o,...s.omit(o==null?void 0:o.role,"properties")||{}}),"getSchemaOfAlterCollection"),x=n(o=>{var F;let E=O(o),b=(F=o.compMod)==null?void 0:F.keyspaceName;return M(E,b)},"getFullCollectionName"),S=n(o=>Object.entries(o).filter(([E,b])=>!s.isNil(b)).reduce((E,[b,F])=>({...E,[b]:F}),{}),"clean"),p=n(o=>o.every(E=>s.get(E,"isActivated",!0)),"checkAllKeysActivated"),l=n(o=>o.length?o.every(E=>!s.get(E,"isActivated",!0)):!1,"checkAllKeysDeactivated"),r=n((o,E)=>{let b=o.filter(w=>s.get(w,"isActivated",!0)).map(E),F=o.filter(w=>!s.get(w,"isActivated",!0)).map(E);return{activatedItems:b,deactivatedItems:F}},"divideIntoActivatedAndDeactivated"),i=n((o,{isActivated:E,isPartOfLine:b,inlineComment:F="--"})=>o?E!==!1?o:b?"/* "+o+" */":o.includes(` +`),"tab"),M=n((o,E)=>Object.keys(o).map(s.toLower).includes(s.toLower(E)),"hasType"),h=n(o=>({...o,...s.omit(o==null?void 0:o.role,"properties")||{}}),"getSchemaOfAlterCollection"),x=n(o=>{var K;let E=O(o),b=(K=o.compMod)==null?void 0:K.keyspaceName;return V(E,b)},"getFullCollectionName"),S=n(o=>Object.entries(o).filter(([E,b])=>!s.isNil(b)).reduce((E,[b,K])=>({...E,[b]:K}),{}),"clean"),p=n(o=>o.every(E=>s.get(E,"isActivated",!0)),"checkAllKeysActivated"),l=n(o=>o.length?o.every(E=>!s.get(E,"isActivated",!0)):!1,"checkAllKeysDeactivated"),r=n((o,E)=>{let b=o.filter(w=>s.get(w,"isActivated",!0)).map(E),K=o.filter(w=>!s.get(w,"isActivated",!0)).map(E);return{activatedItems:b,deactivatedItems:K}},"divideIntoActivatedAndDeactivated"),i=n((o,{isActivated:E,isPartOfLine:b,inlineComment:K="--"})=>o?E!==!1?o:b?"/* "+o+" */":o.includes(` `)?`/* `+o+` */ -`:F+" "+o:"","commentIfDeactivated"),I=n((o,E="'",b="'")=>{let F=o[0];return o[o.length-1]===E&&F===b?o:`${E}${o}${b}`},"wrap"),c=n((o,E)=>E.some(b=>(o==null?void 0:o.oldField[b])!==(o==null?void 0:o.newField[b])),"checkFieldPropertiesChanged"),a=n(o=>{let E={...o,...s.omit(o==null?void 0:o.role,"properties")||{}},b=O(E),F=f({collection:E});return M(b,F)},"getFullTableName"),f=n(({collection:o})=>{var E;return(E=o.compMod)==null?void 0:E.keyspaceName},"getSchemaNameFromCollection"),m=n((o,E)=>{let{wrapInQuotes:b}=ue()(s);return`${a(o)}.${b(E)}`},"getFullColumnName"),C=n(o=>{var w;let E={...o,...s.omit(o==null?void 0:o.role,"properties")||{}},b=u(E),F=(w=E.compMod)==null?void 0:w.keyspaceName;return M(b,F)},"getFullViewName"),N=n(o=>o.code||o.name,"getUdtName"),v=n((o="")=>{let E=o.match(/\d+/);return Number(s.get(E,[0],0))},"getDbVersion"),G=n((o="")=>o.replace(tn,E=>`\\${E}`),"prepareComment"),g=n(o=>`E'${G(JSON.stringify(o)).slice(1,-1)}'`,"wrapComment"),A=n(o=>s.map(o,E=>{let b=E.defaultExpression?`DEFAULT ${E.defaultExpression}`:"";return s.trim(`${E.argumentMode} ${E.argumentName||""} ${E.argumentType} ${b}`)}).join(", "),"getFunctionArguments"),M=n((o,E)=>E?`${V(E)}.${V(o)}`:V(o),"getNamePrefixedWithSchemaName"),V=n(o=>/\s|\W/.test(o)||s.includes(en,s.toUpper(o))?`"${o}"`:o,"wrapInQuotes"),le=n(({name:o})=>V(o),"columnMapToString"),ge=n((o,E,b,F=le)=>{var ne;let w=r(o,F),ae=(ne=w==null?void 0:w.deactivatedItems)!=null&&ne.length?i(w.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!E&&b?" ("+w.activatedItems.join(", ")+ae+")":" ("+o.map(F).join(", ")+")"},"getColumnsList"),te=n(o=>o?o.alias?`${V(o.name)} as ${V(o.alias)}`:V(o.name):"","getKeyWithAlias");return{getDbName:$,getDbData:R,getEntityName:O,getViewName:u,getViewOn:P,tab:U,hasType:K,clean:S,checkAllKeysActivated:p,checkAllKeysDeactivated:l,divideIntoActivatedAndDeactivated:r,commentIfDeactivated:i,wrap:I,checkFieldPropertiesChanged:c,getFullTableName:a,getFullColumnName:m,getFullViewName:C,getUdtName:N,getDbVersion:v,wrapComment:g,getFunctionArguments:A,getNamePrefixedWithSchemaName:M,wrapInQuotes:V,getColumnsList:ge,getViewData:n(o=>Array.isArray(o)?o.reduce((E,b)=>{if(!b.tableName)return E.columns.push(te(b)),E;let F=`${V(b.dbName)}.${V(b.tableName)}`;return E.tables.includes(F)||E.tables.push(F),E.columns.push({statement:`${F}.${te(b)}`,isActivated:b.isActivated}),E},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:h,getFullCollectionName:x,getSchemaNameFromCollection:f,getGroupItemsByCompMode:n(({newItems:o=[],oldItems:E=[]})=>{let b=o.filter(ae=>!E.some(ne=>ne.id===ae.id)),F=[],w=[];return E.forEach(ae=>{let ne=o.find(Ee=>Ee.id===ae.id);ne?s.isEqual(ne,ae)||w.push(ne):F.push(ae)}),{added:b,removed:F,modified:w}},"getGroupItemsByCompMode")}}});var Tt=_((Sn,gt)=>{var dt=n((s="")=>new RegExp("\\$\\{(.*?)\\}",s),"template"),nn=n(s=>s.match(dt("gi"))||[],"getAllTemplates"),rn=n(s=>(s.match(dt("i"))||[])[1],"parseTemplate"),an=n((s,$)=>nn(s).reduce((O,u)=>{let R=rn(u);return O.replace(u,()=>$[R]||$[R]===0?$[R]:"")},s),"assignTemplates");gt.exports=an});var Nt=_((On,Et)=>{Et.exports=({_:s,commentIfDeactivated:$,checkAllKeysDeactivated:O,assignTemplates:u,wrapInQuotes:R,getColumnsList:P})=>({generateConstraintsString:n((l,r)=>{var a,f;let i=$(((l==null?void 0:l.deactivatedItems)||[]).join(`, +`:K+" "+o:"","commentIfDeactivated"),I=n((o,E="'",b="'")=>{let K=o[0];return o[o.length-1]===E&&K===b?o:`${E}${o}${b}`},"wrap"),c=n((o,E)=>E.some(b=>(o==null?void 0:o.oldField[b])!==(o==null?void 0:o.newField[b])),"checkFieldPropertiesChanged"),a=n(o=>{let E={...o,...s.omit(o==null?void 0:o.role,"properties")||{}},b=O(E),K=f({collection:E});return V(b,K)},"getFullTableName"),f=n(({collection:o})=>{var E;return(E=o.compMod)==null?void 0:E.keyspaceName},"getSchemaNameFromCollection"),m=n((o,E)=>`${a(o)}.${v(E)}`,"getFullColumnName"),C=n(o=>{var w;let E={...o,...s.omit(o==null?void 0:o.role,"properties")||{}},b=u(E),K=(w=E.compMod)==null?void 0:w.keyspaceName;return V(b,K)},"getFullViewName"),N=n(o=>o.code||o.name,"getUdtName"),F=n((o="")=>{let E=o.match(/\d+/);return Number(s.get(E,[0],0))},"getDbVersion"),G=n((o="")=>o.replace(tn,E=>`\\${E}`),"prepareComment"),g=n(o=>`E'${G(JSON.stringify(o)).slice(1,-1)}'`,"wrapComment"),A=n(o=>s.map(o,E=>{let b=E.defaultExpression?`DEFAULT ${E.defaultExpression}`:"";return s.trim(`${E.argumentMode} ${E.argumentName||""} ${E.argumentType} ${b}`)}).join(", "),"getFunctionArguments"),V=n((o,E)=>E?`${v(E)}.${v(o)}`:v(o),"getNamePrefixedWithSchemaName"),v=n(o=>/\s|\W/.test(o)||s.includes(en,s.toUpper(o))?`"${o}"`:o,"wrapInQuotes"),le=n(({name:o})=>v(o),"columnMapToString"),ge=n((o,E,b,K=le)=>{var ne;let w=r(o,K),ae=(ne=w==null?void 0:w.deactivatedItems)!=null&&ne.length?i(w.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!E&&b?" ("+w.activatedItems.join(", ")+ae+")":" ("+o.map(K).join(", ")+")"},"getColumnsList"),te=n(o=>o?o.alias?`${v(o.name)} as ${v(o.alias)}`:v(o.name):"","getKeyWithAlias");return{getDbName:$,getDbData:R,getEntityName:O,getViewName:u,getViewOn:P,tab:U,hasType:M,clean:S,checkAllKeysActivated:p,checkAllKeysDeactivated:l,divideIntoActivatedAndDeactivated:r,commentIfDeactivated:i,wrap:I,checkFieldPropertiesChanged:c,getFullTableName:a,getFullColumnName:m,getFullViewName:C,getUdtName:N,getDbVersion:F,wrapComment:g,getFunctionArguments:A,getNamePrefixedWithSchemaName:V,wrapInQuotes:v,getColumnsList:ge,getViewData:n(o=>Array.isArray(o)?o.reduce((E,b)=>{if(!b.tableName)return E.columns.push(te(b)),E;let K=`${v(b.dbName)}.${v(b.tableName)}`;return E.tables.includes(K)||E.tables.push(K),E.columns.push({statement:`${K}.${te(b)}`,isActivated:b.isActivated}),E},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:h,getFullCollectionName:x,getSchemaNameFromCollection:f,getGroupItemsByCompMode:n(({newItems:o=[],oldItems:E=[]})=>{let b=o.filter(ae=>!E.some(ne=>ne.id===ae.id)),K=[],w=[];return E.forEach(ae=>{let ne=o.find(Ee=>Ee.id===ae.id);ne?s.isEqual(ne,ae)||w.push(ne):K.push(ae)}),{added:b,removed:K,modified:w}},"getGroupItemsByCompMode")}}});var Tt=_((Sn,gt)=>{"use strict";var dt=n((s="")=>new RegExp("\\$\\{(.*?)\\}",s),"template"),nn=n(s=>s.match(dt("gi"))||[],"getAllTemplates"),rn=n(s=>(s.match(dt("i"))||[])[1],"parseTemplate"),an=n((s,$)=>nn(s).reduce((O,u)=>{let R=rn(u);return O.replace(u,()=>$[R]||$[R]===0?$[R]:"")},s),"assignTemplates");gt.exports=an});var Nt=_((On,Et)=>{"use strict";Et.exports=({_:s,commentIfDeactivated:$,checkAllKeysDeactivated:O,assignTemplates:u,wrapInQuotes:R,getColumnsList:P})=>({generateConstraintsString:n((l,r)=>{var a,f;let i=$(((l==null?void 0:l.deactivatedItems)||[]).join(`, `),{isActivated:!r,isPartOfLine:!0}),I=(a=l==null?void 0:l.activatedItems)!=null&&a.length?`, `+l.activatedItems.join(`, `):"",c=(f=l==null?void 0:l.deactivatedItems)!=null&&f.length?` - `+i:"";return I+c},"generateConstraintsString"),foreignKeysToString:n(l=>{if(Array.isArray(l)){let r=l.filter(c=>s.get(c,"isActivated",!0)).map(c=>R(s.trim(c.name))),i=l.filter(c=>!s.get(c,"isActivated",!0)).map(c=>R(s.trim(c.name))),I=i.length?$(i,{isActivated:!1,isPartOfLine:!0}):"";return r.join(", ")+I}return l},"foreignKeysToString"),foreignActiveKeysToString:n(l=>l.map(r=>s.trim(r.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:n((l,r)=>i=>{let I=R(s.trim(i.name)),c=O(i.columns||[]),a=s.isEmpty(i.columns)?"":P(i.columns,c,r),f=i.include.length?` INCLUDE${P(i.include,c,r)}`:"",m=i.storageParameters?` WITH (${i.storageParameters})`:"",C=i.tablespace?` USING INDEX TABLESPACE ${R(i.tablespace)}`:"",N=i!=null&&i.deferrable?` ${i.deferrable}`:"",v=(i==null?void 0:i.deferrable)==="DEFERRABLE"&&(i!=null&&i.deferrableConstraintCheckTime)?` ${i==null?void 0:i.deferrableConstraintCheckTime}`:"";return{statement:u(l.createKeyConstraint,{constraintName:i.name?`CONSTRAINT ${I} `:"",keyType:i.keyType,columns:a,includeNonKey:f,storageParameters:m,tablespace:C,deferrable:N,deferrableConstraintCheckTime:v}),isActivated:!c}},"createKeyConstraint"),getConstraintsWarnings:n((l=[])=>s.isEmpty(l)?"":` + `+i:"";return I+c},"generateConstraintsString"),foreignKeysToString:n(l=>{if(Array.isArray(l)){let r=l.filter(c=>s.get(c,"isActivated",!0)).map(c=>R(s.trim(c.name))),i=l.filter(c=>!s.get(c,"isActivated",!0)).map(c=>R(s.trim(c.name))),I=i.length?$(i,{isActivated:!1,isPartOfLine:!0}):"";return r.join(", ")+I}return l},"foreignKeysToString"),foreignActiveKeysToString:n(l=>l.map(r=>s.trim(r.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:n((l,r)=>i=>{let I=R(s.trim(i.name)),c=O(i.columns||[]),a=s.isEmpty(i.columns)?"":P(i.columns,c,r),f=i.include.length?` INCLUDE${P(i.include,c,r)}`:"",m=i.storageParameters?` WITH (${i.storageParameters})`:"",C=i.tablespace?` USING INDEX TABLESPACE ${R(i.tablespace)}`:"",N=i!=null&&i.deferrable?` ${i.deferrable}`:"",F=(i==null?void 0:i.deferrable)==="DEFERRABLE"&&(i!=null&&i.deferrableConstraintCheckTime)?` ${i==null?void 0:i.deferrableConstraintCheckTime}`:"";return{statement:u(l.createKeyConstraint,{constraintName:i.name?`CONSTRAINT ${I} `:"",keyType:i.keyType,columns:a,includeNonKey:f,storageParameters:m,tablespace:C,deferrable:N,deferrableConstraintCheckTime:F}),isActivated:!c}},"createKeyConstraint"),getConstraintsWarnings:n((l=[])=>s.isEmpty(l)?"":` `+l.map(r=>{let i=r.name?` [constraint name: ${r.name}]`:"";return`-- ${r.errorMessage}${i}`}).join(` - `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:n(l=>{let r=s.get(l,"relationshipOnDelete",""),i=s.get(l,"relationshipOnUpdate",""),I=s.get(l,"relationshipMatch",""),c=s.get(l,"deferrable",""),a=s.get(l,"deferrableConstraintCheckTime","");return{foreignOnDelete:r,foreignOnUpdate:i,foreignMatch:I,deferrable:c,deferrableConstraintCheckTime:a}},"additionalPropertiesForForeignKey")})});var At=_((bn,yt)=>{yt.exports=(s,$)=>{let O=n((c,a)=>Object.entries(c.properties).map(a),"mapProperties"),u=n(c=>c.compositeUniqueKey?!1:!!c.unique,"isUniqueKey"),R=n(c=>{var a,f;return u(c)&&(((a=c.uniqueKeyOptions)==null?void 0:a.length)===1&&!((f=s.first(c.uniqueKeyOptions))!=null&&f.constraintName)||s.isEmpty(c.uniqueKeyOptions))},"isInlineUnique"),P=n(c=>c.compositeUniqueKey||c.compositePrimaryKey?!1:!!c.primaryKey,"isPrimaryKey"),U=n(c=>{var a;return P(c)&&!((a=s.first(c.primaryKeyOptions))!=null&&a.constraintName)},"isInlinePrimaryKey"),K=n((c,a)=>{let f=c.nullsDistinct;return`UNIQUE${a>=15&&f?` ${f}`:""}`},"getUniqueKeyType"),h=n(({options:c,columnName:a,isActivated:f,jsonSchema:m,dbVersion:C})=>$({keyType:K(c,C),name:c.constraintName,columns:[{name:a,isActivated:f}],include:l(c.indexInclude||[],m),storageParameters:c.indexStorageParameters,comment:c.indexComment,tablespace:c.indexTablespace,nullsDistinct:c.nullsDistinct,deferrable:c.deferrable,deferrableConstraintCheckTime:c.deferrableConstraintCheckTime}),"hydrateUniqueOptions"),x=n((c,a,f,m)=>$({keyType:"PRIMARY KEY",name:c.constraintName,columns:[{name:a,isActivated:f}],include:l(c.indexInclude||[],m),storageParameters:c.indexStorageParameters,comment:c.indexComment,tablespace:c.indexTablespace,deferrable:c.deferrable,deferrableConstraintCheckTime:c.deferrableConstraintCheckTime}),"hydratePrimaryKeyOptions"),S=n((c,a)=>Object.keys(a).find(f=>a[f].GUID===c),"findName"),p=n((c,a)=>s.get(Object.values(a).find(f=>f.GUID===c),"isActivated",!0),"checkIfActivated"),l=n((c,a)=>s.map(c,f=>({name:S(f.keyId,a.properties),isActivated:p(f.keyId,a.properties)})),"getKeys"),r=n(c=>Array.isArray(c.primaryKey)?c.primaryKey.map(a=>s.isEmpty(a.compositePrimaryKey)?{name:a.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...x(a,null,null,c),columns:l(a.compositePrimaryKey,c)}):[],"getCompositePrimaryKeys"),i=n((c,a)=>Array.isArray(c.uniqueKey)?c.uniqueKey.map(f=>s.isEmpty(f.compositeUniqueKey)?{name:f.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...h({options:f,columnName:null,isActivated:null,jsonSchema:c,dbVersion:a}),columns:l(f.compositeUniqueKey,c)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:n((c,a)=>{if(!c.properties)return[];let f=O(c,([C,N])=>{if(!(!P(N)||U(N)))return x(s.first(N.primaryKeyOptions),C,N.isActivated,c)}).filter(Boolean),m=s.flatten(O(c,([C,N])=>!u(N)||R(N)?[]:(N.uniqueKeyOptions||[]).map(v=>h({options:v,columnName:C,isActivated:N.isActivated,jsonSchema:c,dbVersion:a})))).filter(Boolean);return[...f,...r(c),...m,...i(c,a)]},"getTableKeyConstraints"),isInlineUnique:R,isInlinePrimaryKey:U,getKeys:l,hydratePrimaryKeyOptions:x,hydrateUniqueOptions:h,getUniqueKeyType:K}}});var $t=_((hn,Ct)=>{Ct.exports=({_:s,templates:$,assignTemplates:O,getFunctionArguments:u,getNamePrefixedWithSchemaName:R,wrapComment:P})=>{let U=n((m,C)=>s.map(C,N=>{let v=N.functionOrReplace?" OR REPLACE":"",G=O($.createFunction,{name:R(N.name,m),orReplace:v,parameters:u(N.functionArguments),returnType:N.functionReturnsSetOf?`SETOF ${N.functionReturnType}`:N.functionReturnType,language:N.functionLanguage,properties:K(N),definition:N.functionBody}),g=N.functionDescription?O($.comment,{object:"FUNCTION",objectName:R(N.name,m),comment:P(N.functionDescription)}):"";return[G,g].filter(Boolean).join(` + `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:n(l=>{let r=s.get(l,"relationshipOnDelete",""),i=s.get(l,"relationshipOnUpdate",""),I=s.get(l,"relationshipMatch",""),c=s.get(l,"deferrable",""),a=s.get(l,"deferrableConstraintCheckTime","");return{foreignOnDelete:r,foreignOnUpdate:i,foreignMatch:I,deferrable:c,deferrableConstraintCheckTime:a}},"additionalPropertiesForForeignKey")})});var At=_((bn,yt)=>{"use strict";yt.exports=(s,$)=>{let O=n((c,a)=>Object.entries(c.properties).map(a),"mapProperties"),u=n(c=>c.compositeUniqueKey?!1:!!c.unique,"isUniqueKey"),R=n(c=>{var a,f;return u(c)&&(((a=c.uniqueKeyOptions)==null?void 0:a.length)===1&&!((f=s.first(c.uniqueKeyOptions))!=null&&f.constraintName)||s.isEmpty(c.uniqueKeyOptions))},"isInlineUnique"),P=n(c=>c.compositeUniqueKey||c.compositePrimaryKey?!1:!!c.primaryKey,"isPrimaryKey"),U=n(c=>{var a;return P(c)&&!((a=s.first(c.primaryKeyOptions))!=null&&a.constraintName)},"isInlinePrimaryKey"),M=n((c,a)=>{let f=c.nullsDistinct;return`UNIQUE${a>=15&&f?` ${f}`:""}`},"getUniqueKeyType"),h=n(({options:c,columnName:a,isActivated:f,jsonSchema:m,dbVersion:C})=>$({keyType:M(c,C),name:c.constraintName,columns:[{name:a,isActivated:f}],include:l(c.indexInclude||[],m),storageParameters:c.indexStorageParameters,comment:c.indexComment,tablespace:c.indexTablespace,nullsDistinct:c.nullsDistinct,deferrable:c.deferrable,deferrableConstraintCheckTime:c.deferrableConstraintCheckTime}),"hydrateUniqueOptions"),x=n((c,a,f,m)=>$({keyType:"PRIMARY KEY",name:c.constraintName,columns:[{name:a,isActivated:f}],include:l(c.indexInclude||[],m),storageParameters:c.indexStorageParameters,comment:c.indexComment,tablespace:c.indexTablespace,deferrable:c.deferrable,deferrableConstraintCheckTime:c.deferrableConstraintCheckTime}),"hydratePrimaryKeyOptions"),S=n((c,a)=>Object.keys(a).find(f=>a[f].GUID===c),"findName"),p=n((c,a)=>s.get(Object.values(a).find(f=>f.GUID===c),"isActivated",!0),"checkIfActivated"),l=n((c,a)=>s.map(c,f=>({name:S(f.keyId,a.properties),isActivated:p(f.keyId,a.properties)})),"getKeys"),r=n(c=>Array.isArray(c.primaryKey)?c.primaryKey.map(a=>s.isEmpty(a.compositePrimaryKey)?{name:a.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...x(a,null,null,c),columns:l(a.compositePrimaryKey,c)}):[],"getCompositePrimaryKeys"),i=n((c,a)=>Array.isArray(c.uniqueKey)?c.uniqueKey.map(f=>s.isEmpty(f.compositeUniqueKey)?{name:f.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...h({options:f,columnName:null,isActivated:null,jsonSchema:c,dbVersion:a}),columns:l(f.compositeUniqueKey,c)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:n((c,a)=>{if(!c.properties)return[];let f=O(c,([C,N])=>{if(!(!P(N)||U(N)))return x(s.first(N.primaryKeyOptions),C,N.isActivated,c)}).filter(Boolean),m=s.flatten(O(c,([C,N])=>!u(N)||R(N)?[]:(N.uniqueKeyOptions||[]).map(F=>h({options:F,columnName:C,isActivated:N.isActivated,jsonSchema:c,dbVersion:a})))).filter(Boolean);return[...f,...r(c),...m,...i(c,a)]},"getTableKeyConstraints"),isInlineUnique:R,isInlinePrimaryKey:U,getKeys:l,hydratePrimaryKeyOptions:x,hydrateUniqueOptions:h,getUniqueKeyType:M}}});var $t=_((hn,Ct)=>{"use strict";Ct.exports=({_:s,templates:$,assignTemplates:O,getFunctionArguments:u,getNamePrefixedWithSchemaName:R,wrapComment:P})=>{let U=n((m,C)=>s.map(C,N=>{let F=N.functionOrReplace?" OR REPLACE":"",G=O($.createFunction,{name:R(N.name,m),orReplace:F,parameters:u(N.functionArguments),returnType:N.functionReturnsSetOf?`SETOF ${N.functionReturnType}`:N.functionReturnType,language:N.functionLanguage,properties:M(N),definition:N.functionBody}),g=N.functionDescription?O($.comment,{object:"FUNCTION",objectName:R(N.name,m),comment:P(N.functionDescription)}):"";return[G,g].filter(Boolean).join(` `)}).join(` -`),"getFunctionsScript"),K=n(m=>{let C=n(N=>N?` ${N} -`:"","wrap");return[{key:"functionWindow",getValue:h},{key:"functionVolatility",getValue:x},{key:"functionLeakProof",getValue:S},{key:"functionNullArgs",getValue:p},{key:"functionSqlSecurity",getValue:l},{key:"functionParallel",getValue:r},{key:"functionExecutionCost",getValue:i},{key:"functionExecutionRows",getValue:I},{key:"functionSupportFunction",getValue:c},{key:"functionConfigurationParameters",getValue:a}].map(N=>C(N.getValue(m[N.key],m))).filter(Boolean).join("")},"getProperties"),h=n((m,C)=>C.language!=="c"||!m?"":"WINDOW","getWindow"),x=n(m=>m,"getVolatility"),S=n(m=>m?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),p=n(m=>m,"getNullArgs"),l=n(m=>{if(m)return`SECURITY ${m}`},"getSqlSecurity"),r=n(m=>{if(m)return`PARALLEL ${m}`},"getParallel"),i=n(m=>{if(m)return`COST ${m}`},"getExecutionCost"),I=n((m,C)=>!m||!C.functionReturnsSetOf&&!f(C)?"":`ROWS ${m}`,"getExecutionRows"),c=n(m=>{if(m)return`SUPPORT ${m}`},"getSupportFunction"),a=n(m=>{if(m)return`SET ${m}`},"getConfigurationParameters"),f=n(m=>(m.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:U}}});var St=_((Un,ft)=>{ft.exports=({_:s,templates:$,assignTemplates:O,getFunctionArguments:u,getNamePrefixedWithSchemaName:R})=>({getProceduresScript:n((U,K)=>s.map(K,h=>{let x=h.orReplace?" OR REPLACE":"";return O($.createProcedure,{name:R(h.name,U),orReplace:x,parameters:u(h.inputArgs),language:h.language,body:h.body})}).join(` -`),"getProceduresScript")})});var Ot=_((vn,It)=>{var{Sequence:Fn}=Se();It.exports=({_:s,templates:$,assignTemplates:O,getNamePrefixedWithSchemaName:u,wrapInQuotes:R})=>{let P=n(({schemaName:m,sequences:C})=>s.map(C,N=>U({schemaName:m,sequence:N})).join(` -`),"getSequencesScript"),U=n(({schemaName:m,sequence:C})=>{let N=C.temporary?"":m,v=u(C.sequenceName,N),G=r({sequence:C}),g=i({sequence:C}),A=x({sequence:C,schemaName:m});return O($.createSequence,{name:v,ifNotExists:G,sequenceType:g,options:A})},"createSequenceScript"),K=n(({schemaName:m,sequence:C,oldSequence:N})=>{let v=C.temporary?"":m,G=N.sequenceName||C.sequenceName,g=u(G,v),A=f({sequence:C,oldSequence:N}),M=x({schemaName:m,sequence:A}),V=I({sequence:A}),le=A.sequenceName;return[{key:"options",value:M,template:$.alterSequence},{key:"sequenceType",value:V,template:$.setSequenceType},{key:"newName",value:le,template:$.renameSequence}].filter(te=>te.value).map(te=>O(te.template,{[te.key]:te.value,name:g})).join(` -`)},"alterSequenceScript"),h=n(({schemaName:m,sequence:C})=>{let N=C.temporary?"":m,v=u(C.sequenceName,N);return O($.dropSequence,{name:v})},"dropSequenceScript"),x=n(({schemaName:m,sequence:C})=>{let v=[{getOption:S,key:"dataType",clause:"AS"},{getOption:S,key:"increment",clause:"INCREMENT BY"},{getOption:S,key:"start",clause:"START WITH"},{getOption:S,key:"restart",clause:"RESTART WITH"},{getOption:S,key:"minValue",clause:"MINVALUE"},{getOption:S,key:"maxValue",clause:"MAXVALUE"},{getOption:S,key:"cache",clause:"CACHE"},{getOption:c,key:"cycle"},{getOption:a,key:"ownedByColumn"}].map(G=>{let g=G.getOption({sequence:C,schemaName:m,config:G});return p({option:g})}).filter(Boolean).join("");return v&&l({options:v})},"getSequenceOptions"),S=n(({sequence:m,config:C})=>{let N=m[C.key];return N||N===0?`${C.clause} ${N}`:""},"getOption"),p=n(({option:m})=>m?` ${m} +`),"getFunctionsScript"),M=n(m=>{let C=n(N=>N?` ${N} +`:"","wrap");return[{key:"functionWindow",getValue:h},{key:"functionVolatility",getValue:x},{key:"functionLeakProof",getValue:S},{key:"functionNullArgs",getValue:p},{key:"functionSqlSecurity",getValue:l},{key:"functionParallel",getValue:r},{key:"functionExecutionCost",getValue:i},{key:"functionExecutionRows",getValue:I},{key:"functionSupportFunction",getValue:c},{key:"functionConfigurationParameters",getValue:a}].map(N=>C(N.getValue(m[N.key],m))).filter(Boolean).join("")},"getProperties"),h=n((m,C)=>C.language!=="c"||!m?"":"WINDOW","getWindow"),x=n(m=>m,"getVolatility"),S=n(m=>m?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),p=n(m=>m,"getNullArgs"),l=n(m=>{if(m)return`SECURITY ${m}`},"getSqlSecurity"),r=n(m=>{if(m)return`PARALLEL ${m}`},"getParallel"),i=n(m=>{if(m)return`COST ${m}`},"getExecutionCost"),I=n((m,C)=>!m||!C.functionReturnsSetOf&&!f(C)?"":`ROWS ${m}`,"getExecutionRows"),c=n(m=>{if(m)return`SUPPORT ${m}`},"getSupportFunction"),a=n(m=>{if(m)return`SET ${m}`},"getConfigurationParameters"),f=n(m=>(m.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:U}}});var St=_((Un,ft)=>{"use strict";ft.exports=({_:s,templates:$,assignTemplates:O,getFunctionArguments:u,getNamePrefixedWithSchemaName:R})=>({getProceduresScript:n((U,M)=>s.map(M,h=>{let x=h.orReplace?" OR REPLACE":"";return O($.createProcedure,{name:R(h.name,U),orReplace:x,parameters:u(h.inputArgs),language:h.language,body:h.body})}).join(` +`),"getProceduresScript")})});var Ot=_((vn,It)=>{"use strict";var{Sequence:Fn}=Se();It.exports=({_:s,templates:$,assignTemplates:O,getNamePrefixedWithSchemaName:u,wrapInQuotes:R})=>{let P=n(({schemaName:m,sequences:C})=>s.map(C,N=>U({schemaName:m,sequence:N})).join(` +`),"getSequencesScript"),U=n(({schemaName:m,sequence:C})=>{let N=C.temporary?"":m,F=u(C.sequenceName,N),G=r({sequence:C}),g=i({sequence:C}),A=x({sequence:C,schemaName:m});return O($.createSequence,{name:F,ifNotExists:G,sequenceType:g,options:A})},"createSequenceScript"),M=n(({schemaName:m,sequence:C,oldSequence:N})=>{let F=C.temporary?"":m,G=N.sequenceName||C.sequenceName,g=u(G,F),A=f({sequence:C,oldSequence:N}),V=x({schemaName:m,sequence:A}),v=I({sequence:A}),le=A.sequenceName;return[{key:"options",value:V,template:$.alterSequence},{key:"sequenceType",value:v,template:$.setSequenceType},{key:"newName",value:le,template:$.renameSequence}].filter(te=>te.value).map(te=>O(te.template,{[te.key]:te.value,name:g})).join(` +`)},"alterSequenceScript"),h=n(({schemaName:m,sequence:C})=>{let N=C.temporary?"":m,F=u(C.sequenceName,N);return O($.dropSequence,{name:F})},"dropSequenceScript"),x=n(({schemaName:m,sequence:C})=>{let F=[{getOption:S,key:"dataType",clause:"AS"},{getOption:S,key:"increment",clause:"INCREMENT BY"},{getOption:S,key:"start",clause:"START WITH"},{getOption:S,key:"restart",clause:"RESTART WITH"},{getOption:S,key:"minValue",clause:"MINVALUE"},{getOption:S,key:"maxValue",clause:"MAXVALUE"},{getOption:S,key:"cache",clause:"CACHE"},{getOption:c,key:"cycle"},{getOption:a,key:"ownedByColumn"}].map(G=>{let g=G.getOption({sequence:C,schemaName:m,config:G});return p({option:g})}).filter(Boolean).join("");return F&&l({options:F})},"getSequenceOptions"),S=n(({sequence:m,config:C})=>{let N=m[C.key];return N||N===0?`${C.clause} ${N}`:""},"getOption"),p=n(({option:m})=>m?` ${m} `:"","wrapOption"),l=n(({options:m})=>` -`+m.replace(/\n$/,""),"wrapOptionsBlock"),r=n(({sequence:m})=>m.ifNotExist?" IF NOT EXISTS":"","getIfNotExists"),i=n(({sequence:m})=>m.temporary?" TEMPORARY":m.unlogged?" UNLOGGED":"","getSequenceType"),I=n(({sequence:m})=>m.temporary?"":m.unlogged===!0?"UNLOGGED":m.unlogged===!1?"LOGGED":"","getAlterSequenceType"),c=n(({sequence:m})=>m.cycle===!0?"CYCLE":m.cycle===!1?"NO CYCLE":"","getCycle"),a=n(({sequence:m,schemaName:C})=>{var v,G;if(m.ownedByNone)return"OWNED BY NONE";let N=(v=m.ownedByColumn)==null?void 0:v[0];if(N){let[g,A]=((G=N.name)==null?void 0:G.split("."))||[];return`OWNED BY ${[C,g,A].filter(Boolean).map(R).join(".")}`}return""},"getOwnedBy"),f=n(({sequence:m,oldSequence:C})=>{let N=s.omitBy(m,(v,G)=>s.isEqual(v,C[G]));return m.minValue>C.minValue?{...N,restart:m.start}:N},"getModifiedSequence");return{getSequencesScript:P,createSequenceScript:U,dropSequenceScript:h,alterSequenceScript:K}}});var bt=_((Mn,Rt)=>{Rt.exports=({_:s,getColumnsList:$,checkAllKeysDeactivated:O})=>{let u=n((p,l)=>p?" TEMPORARY":l?" UNLOGGED":"","getTableTemporaryValue"),R=n(p=>{let l=n(i=>i?`${i} -`:"","wrap"),r=[{key:"inherits",getValue:h("INHERITS")},{key:"partitionBounds",getValue:h("")},{key:"partitioning",getValue:P},{key:"usingMethod",getValue:h("USING")},{key:"storage_parameter",getValue:S},{key:"on_commit",getValue:K},{key:"table_tablespace_name",getValue:h("TABLESPACE")},{key:"selectStatement",getValue:h("AS")}].map(i=>l(i.getValue(p[i.key],p))).filter(Boolean).join("");return s.trim(r)?` ${s.trim(r)}`:""},"getTableOptions"),P=n((p,{isActivated:l})=>{if(p&&p.partitionMethod){let r=p.partitionBy==="keys"?U(p,l):` (${p.partitioning_expression})`;return`PARTITION BY ${p.partitionMethod}${r}`}},"getPartitioning"),U=n((p,l)=>{let r=O(p.compositePartitionKey);return $(p.compositePartitionKey,r,l)},"getPartitionKeys"),K=n((p,l)=>{if(p&&l.temporary)return`ON COMMIT ${p}`},"getOnCommit"),h=n(p=>l=>{if(l)return`${p} ${l}`},"getBasicValue"),x=["toast_autovacuum_enabled","toast_vacuum_index_cleanup","toast_vacuum_truncate","toast_autovacuum_vacuum_threshold","toast_autovacuum_vacuum_scale_factor","toast_autovacuum_vacuum_insert_threshold","toast_autovacuum_vacuum_insert_scale_factor","toast_autovacuum_vacuum_cost_delay","toast_autovacuum_vacuum_cost_limit","toast_autovacuum_freeze_min_age","toast_autovacuum_freeze_max_age","toast_autovacuum_freeze_table_age","toast_autovacuum_multixact_freeze_min_age","toast_autovacuum_multixact_freeze_max_age","toast_autovacuum_multixact_freeze_table_age","toast_log_autovacuum_min_duration"],S=n(p=>{if(s.isEmpty(p))return"";let l=["autovacuum","toast","id"];return s.chain(p).toPairs().flatMap(([r,i])=>r==="autovacuum"||r==="toast"?s.toPairs(i):[[r,i]]).reject(([r])=>s.includes(l,r)).map(([r,i])=>{if(!(!i&&i!==0))return s.includes(x,r)?`toast.${r.slice(6)}=${i}`:`${r}=${i}`}).compact().join(`, +`+m.replace(/\n$/,""),"wrapOptionsBlock"),r=n(({sequence:m})=>m.ifNotExist?" IF NOT EXISTS":"","getIfNotExists"),i=n(({sequence:m})=>m.temporary?" TEMPORARY":m.unlogged?" UNLOGGED":"","getSequenceType"),I=n(({sequence:m})=>m.temporary?"":m.unlogged===!0?"UNLOGGED":m.unlogged===!1?"LOGGED":"","getAlterSequenceType"),c=n(({sequence:m})=>m.cycle===!0?"CYCLE":m.cycle===!1?"NO CYCLE":"","getCycle"),a=n(({sequence:m,schemaName:C})=>{var F,G;if(m.ownedByNone)return"OWNED BY NONE";let N=(F=m.ownedByColumn)==null?void 0:F[0];if(N){let[g,A]=((G=N.name)==null?void 0:G.split("."))||[];return`OWNED BY ${[C,g,A].filter(Boolean).map(R).join(".")}`}return""},"getOwnedBy"),f=n(({sequence:m,oldSequence:C})=>{let N=s.omitBy(m,(F,G)=>s.isEqual(F,C[G]));return m.minValue>C.minValue?{...N,restart:m.start}:N},"getModifiedSequence");return{getSequencesScript:P,createSequenceScript:U,dropSequenceScript:h,alterSequenceScript:M}}});var bt=_((Mn,Rt)=>{"use strict";Rt.exports=({_:s,getColumnsList:$,checkAllKeysDeactivated:O})=>{let u=n((p,l)=>p?" TEMPORARY":l?" UNLOGGED":"","getTableTemporaryValue"),R=n(p=>{let l=n(i=>i?`${i} +`:"","wrap"),r=[{key:"inherits",getValue:h("INHERITS")},{key:"partitionBounds",getValue:h("")},{key:"partitioning",getValue:P},{key:"usingMethod",getValue:h("USING")},{key:"storage_parameter",getValue:S},{key:"on_commit",getValue:M},{key:"table_tablespace_name",getValue:h("TABLESPACE")},{key:"selectStatement",getValue:h("AS")}].map(i=>l(i.getValue(p[i.key],p))).filter(Boolean).join("");return s.trim(r)?` ${s.trim(r)}`:""},"getTableOptions"),P=n((p,{isActivated:l})=>{if(p&&p.partitionMethod){let r=p.partitionBy==="keys"?U(p,l):` (${p.partitioning_expression})`;return`PARTITION BY ${p.partitionMethod}${r}`}},"getPartitioning"),U=n((p,l)=>{let r=O(p.compositePartitionKey);return $(p.compositePartitionKey,r,l)},"getPartitionKeys"),M=n((p,l)=>{if(p&&l.temporary)return`ON COMMIT ${p}`},"getOnCommit"),h=n(p=>l=>{if(l)return`${p} ${l}`},"getBasicValue"),x=["toast_autovacuum_enabled","toast_vacuum_index_cleanup","toast_vacuum_truncate","toast_autovacuum_vacuum_threshold","toast_autovacuum_vacuum_scale_factor","toast_autovacuum_vacuum_insert_threshold","toast_autovacuum_vacuum_insert_scale_factor","toast_autovacuum_vacuum_cost_delay","toast_autovacuum_vacuum_cost_limit","toast_autovacuum_freeze_min_age","toast_autovacuum_freeze_max_age","toast_autovacuum_freeze_table_age","toast_autovacuum_multixact_freeze_min_age","toast_autovacuum_multixact_freeze_max_age","toast_autovacuum_multixact_freeze_table_age","toast_log_autovacuum_min_duration"],S=n(p=>{if(s.isEmpty(p))return"";let l=["autovacuum","toast","id"];return s.chain(p).toPairs().flatMap(([r,i])=>r==="autovacuum"||r==="toast"?s.toPairs(i):[[r,i]]).reject(([r])=>s.includes(l,r)).map(([r,i])=>{if(!(!i&&i!==0))return s.includes(x,r)?`toast.${r.slice(6)}=${i}`:`${r}=${i}`}).compact().join(`, `).trim().thru(r=>{if(r)return`WITH ( ${r} -)`}).value()},"getStorageParameters");return{getTableTemporaryValue:u,getTableOptions:R}}});var ht=_((Yn,Lt)=>{Lt.exports=({_:s,commentIfDeactivated:$,assignTemplates:O,templates:u,getNamePrefixedWithSchemaName:R,wrapComment:P})=>{let U=["composite","enum","range_udt","domain"],K=n((r,i)=>{let I=R(r.name,r.schemaName),c=O(u.comment,{object:"TYPE",objectName:I,comment:P(r.comment)});switch(r.type){case"composite":return O(u.createCompositeType,{name:I,columnDefinitions:s.join(i,`, +)`}).value()},"getStorageParameters");return{getTableTemporaryValue:u,getTableOptions:R}}});var ht=_((Yn,Lt)=>{"use strict";Lt.exports=({_:s,commentIfDeactivated:$,assignTemplates:O,templates:u,getNamePrefixedWithSchemaName:R,wrapComment:P})=>{let U=["composite","enum","range_udt","domain"],M=n((r,i)=>{let I=R(r.name,r.schemaName),c=O(u.comment,{object:"TYPE",objectName:I,comment:P(r.comment)});switch(r.type){case"composite":return O(u.createCompositeType,{name:I,columnDefinitions:s.join(i,`, `),comment:r.comment?c:""});case"enum":return O(u.createEnumType,{name:I,values:s.map(r.enum,a=>`'${a}'`).join(", "),comment:r.comment?c:""});case"range_udt":return O(u.createRangeType,{name:I,subtype:r.rangeSubtype,options:x(r),comment:r.comment?c:""});case"domain":{let a=O(u.comment,{object:"DOMAIN",objectName:I,comment:P(r.comment)});return O(u.createDomainType,{name:I,underlyingType:r.underlyingType,notNull:r.nullable?"":" NOT NULL",collate:r.collation?` COLLATE ${r.collation}`:"",default:r.default?` DEFAULT ${r.default}`:"",constraints:S(r),comment:r.comment?a:""})}default:return""}},"getPlainUdt"),h=n(r=>U.includes(r.type),"isNotPlainType"),x=n(r=>{let i=n(c=>c?` ${c}`:"","wrap"),I=[{key:"operatorClass",getValue:p("SUBTYPE_OPCLASS")},{key:"collation",getValue:p("COLLATION")},{key:"canonicalFunction",getValue:p("CANONICAL")},{key:"subtypeDiffFunction",getValue:p("SUBTYPE_DIFF")},{key:"multiRangeType",getValue:p("MULTIRANGE_TYPE_NAME")}].map(c=>i(c.getValue(r[c.key]))).filter(Boolean).join(`, `);return s.trim(I)?`, `+s.trim(I):""},"getRangeOptions"),S=n(r=>s.map(r.checkConstraints,i=>i.name?` CONSTRAINT ${i.name} CHECK (${i.expression})`:` - CHECK (${i.expression})`).join(""),"getDomainConstraints"),p=n(r=>i=>{if(i)return`${r}=${i}`},"getBasicValue");return{getUserDefinedType:n((r,i)=>$(K(r,i),{isActivated:r.isActivated}),"getUserDefinedType"),isNotPlainType:h}}});var Ut=_((qn,Pt)=>{Pt.exports=({_:s,wrapInQuotes:$,checkAllKeysDeactivated:O,getColumnsList:u})=>{let R=n(({name:S,sortOrder:p,nullsOrder:l,collation:r,opclass:i})=>{let I=p?` ${p}`:"",c=l?` ${l}`:"",a=s.includes(r,'"')?r:`"${r}"`,f=r?` COLLATE ${a}`:"",m=i?` ${i}`:"";return`${$(S)}${f}${m}${I}${c}`},"mapIndexKey"),P=n((S=[],p)=>{let l=O(S);return u(S,l,p,R)},"getIndexKeys"),U=n((S,p)=>{var f;let l=u(S.include||[],O(S.include||[]),p),r=(f=S.include)!=null&&f.length?` INCLUDE ${s.trim(l)}`:"",i=h(S),I=i?` WITH ( + CHECK (${i.expression})`).join(""),"getDomainConstraints"),p=n(r=>i=>{if(i)return`${r}=${i}`},"getBasicValue");return{getUserDefinedType:n((r,i)=>$(M(r,i),{isActivated:r.isActivated}),"getUserDefinedType"),isNotPlainType:h}}});var Ut=_((qn,Pt)=>{"use strict";Pt.exports=({_:s,wrapInQuotes:$,checkAllKeysDeactivated:O,getColumnsList:u})=>{let R=n(({name:S,sortOrder:p,nullsOrder:l,collation:r,opclass:i})=>{let I=p?` ${p}`:"",c=l?` ${l}`:"",a=s.includes(r,'"')?r:`"${r}"`,f=r?` COLLATE ${a}`:"",m=i?` ${i}`:"";return`${$(S)}${f}${m}${I}${c}`},"mapIndexKey"),P=n((S=[],p)=>{let l=O(S);return u(S,l,p,R)},"getIndexKeys"),U=n((S,p)=>{var f;let l=u(S.include||[],O(S.include||[]),p),r=(f=S.include)!=null&&f.length?` INCLUDE ${s.trim(l)}`:"",i=h(S),I=i?` WITH ( ${i})`:"",c=S.index_tablespace_name?` TABLESPACE ${S.index_tablespace_name}`:"",a=S.where?` WHERE ${S.where}`:"";return s.compact([" ",r,I,c,a]).join(` -`)},"getIndexOptions"),K={btree:{index_fillfactor:"fillfactor",deduplicate_items:"deduplicate_items"},hash:{index_fillfactor:"fillfactor"},spgist:{index_fillfactor:"fillfactor"},gist:{index_fillfactor:"fillfactor",index_buffering:"buffering"},gin:{fastupdate:"fastupdate",gin_pending_list_limit:"gin_pending_list_limit"},brin:{pages_per_range:"pages_per_range",autosummarize:"autosummarize"}},h=n(S=>{let p=K[S.index_method];return s.chain(p).toPairs().map(([l,r])=>{let i=(S.index_storage_parameter||{})[l];if(!(s.isNil(i)||i===""))return`${r}=${x(i)}`}).compact().join(`, - `).value()},"getWithOptions"),x=n(S=>s.isBoolean(S)?S?"ON":"OFF":S,"getValue");return{getIndexKeys:P,getIndexOptions:U,getWithOptions:h}}});var Ft=_((kn,xt)=>{xt.exports=({_:s,assignTemplates:$,templates:O,commentIfDeactivated:u,wrapComment:R,wrapInQuotes:P})=>{let U=n((g,A)=>`${g}(${A})`,"addLength"),K=n((g,A,M)=>s.isNumber(M)?`${g}(${A},${M})`:`${g}(${A})`,"addScalePrecision"),h=n((g,A)=>s.isNumber(A)?`${g}(${A})`:g,"addPrecision"),x=n((g,A)=>A?`${g} ${A}`:g,"addWithTimezone"),S=n(({type:g,typeModifier:A,srid:M})=>{let V=M?`, ${M}`:"";return A&&A!==""?`${g}(${A}${V})`:g},"addTypeModifier"),p=n((g,A)=>{let M=(A==null?void 0:A.map(V=>`[${(V==null?void 0:V.array_size_limit)??""}]`).join("").trim())||"";return`${g}${M}`},"addArrayDecorator"),l=n(g=>["char","varchar","bit","varbit"].includes(g),"canHaveLength"),r=n(g=>g==="numeric","canHavePrecision"),i=n(g=>["time","timestamp"].includes(g),"canHaveTimePrecision"),I=n(g=>g==="numeric","canHaveScale"),c=n(g=>["geography","geometry"].includes(g),"canHaveTypeModifier"),a=n((g,A)=>(l(g)&&s.isNumber(A.length)?g=U(g,A.length):r(g)&&I(g)&&s.isNumber(A.precision)?g=K(g,A.precision,A.scale):r(g)&&s.isNumber(A.precision)?g=h(g,A.precision):c(g)?g=S({type:g,typeModifier:A.typeModifier,srid:A.srid}):i(g)&&(s.isNumber(A.timePrecision)||A.timezone)&&(g=x(h(g,A.timePrecision),A.timezone)),p(g,A.array_type)),"decorateType"),f=n(g=>["char","varchar","text","bit","varbit"].includes(g),"isString"),m=n(g=>["date","time","timestamp","interval"].includes(g),"isDateTime"),C=n((g,A,M)=>{let V=["current_timestamp","null"];return(f(g)||m(g))&&!V.includes(s.toLower(A))&&!M?R(A):A},"decorateDefault"),N=n((g,A)=>s.chain(A).filter("comment").map(M=>{let V=$(O.comment,{object:"COLUMN",objectName:`${g}.${P(M.name)}`,comment:R(M.comment)});return u(V,M)}).join(` -`).value(),"getColumnComments"),v={"v13.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v12.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v11.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v10.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"}};return{decorateType:a,decorateDefault:C,getColumnComments:N,replaceTypeByVersion:n((g,A)=>{let M=v[A];return s.get(M,g)||g},"replaceTypeByVersion")}}});var Kt=_((wn,vt)=>{vt.exports=({_:s,assignTemplates:$,templates:O,getNamePrefixedWithSchemaName:u,wrap:R,commentIfDeactivated:P})=>{let U=n(({dbVersion:p,triggers:l,tableName:r})=>s.map(l,K(p,r)).join(` -`).trim(),"getTriggersScript"),K=n((p,l)=>r=>{let i=h(r),I=x(r);return $(O.createTrigger,{orReplace:r.triggerOrReplace?" OR REPLACE":"",constraint:r.triggerConstraint?" CONSTRAINT":"",actionTiming:r.triggerType??"",functionKey:p==="v10.x"?"PROCEDURE":"FUNCTION",functionName:r.triggerFunction,name:r.name,tableName:l,events:i,options:I})},"getTriggerScript"),h=n(p=>{var l;return(l=p.triggerEvents)==null?void 0:l.map(r=>{if(r.triggerEvent!=="UPDATE"||s.isEmpty(p.triggerUpdateColumns))return r.triggerEvent;let i=s.chain(p.triggerUpdateColumns).filter("isActivated").map(({name:a})=>a).join(", ").thru(a=>a&&`OF ${a}`).value(),I=s.chain(p.triggerUpdateColumns).reject("isActivated").map(({name:a})=>a).join(", ").thru(a=>!i&&a?`OF ${a}`:a).value(),c=I&&P(I,{isActivated:!1,isPartOfLine:!0});return`UPDATE ${i} ${c}`}).join(" OR ")},"getTriggerEvents"),x=n(p=>{let l="";if(p.triggerConstraint&&(p.triggerReferencedTable&&(l+=R(`FROM ${p.triggerReferencedTable}`," ",` +`)},"getIndexOptions"),M={btree:{index_fillfactor:"fillfactor",deduplicate_items:"deduplicate_items"},hash:{index_fillfactor:"fillfactor"},spgist:{index_fillfactor:"fillfactor"},gist:{index_fillfactor:"fillfactor",index_buffering:"buffering"},gin:{fastupdate:"fastupdate",gin_pending_list_limit:"gin_pending_list_limit"},brin:{pages_per_range:"pages_per_range",autosummarize:"autosummarize"}},h=n(S=>{let p=M[S.index_method];return s.chain(p).toPairs().map(([l,r])=>{let i=(S.index_storage_parameter||{})[l];if(!(s.isNil(i)||i===""))return`${r}=${x(i)}`}).compact().join(`, + `).value()},"getWithOptions"),x=n(S=>s.isBoolean(S)?S?"ON":"OFF":S,"getValue");return{getIndexKeys:P,getIndexOptions:U,getWithOptions:h}}});var Ft=_((kn,xt)=>{"use strict";xt.exports=({_:s,assignTemplates:$,templates:O,commentIfDeactivated:u,wrapComment:R,wrapInQuotes:P})=>{let U=n((g,A)=>`${g}(${A})`,"addLength"),M=n((g,A,V)=>s.isNumber(V)?`${g}(${A},${V})`:`${g}(${A})`,"addScalePrecision"),h=n((g,A)=>s.isNumber(A)?`${g}(${A})`:g,"addPrecision"),x=n((g,A)=>A?`${g} ${A}`:g,"addWithTimezone"),S=n(({type:g,typeModifier:A,srid:V})=>{let v=V?`, ${V}`:"";return A&&A!==""?`${g}(${A}${v})`:g},"addTypeModifier"),p=n((g,A)=>{let V=(A==null?void 0:A.map(v=>`[${(v==null?void 0:v.array_size_limit)??""}]`).join("").trim())||"";return`${g}${V}`},"addArrayDecorator"),l=n(g=>["char","varchar","bit","varbit"].includes(g),"canHaveLength"),r=n(g=>g==="numeric","canHavePrecision"),i=n(g=>["time","timestamp"].includes(g),"canHaveTimePrecision"),I=n(g=>g==="numeric","canHaveScale"),c=n(g=>["geography","geometry"].includes(g),"canHaveTypeModifier"),a=n((g,A)=>(l(g)&&s.isNumber(A.length)?g=U(g,A.length):r(g)&&I(g)&&s.isNumber(A.precision)?g=M(g,A.precision,A.scale):r(g)&&s.isNumber(A.precision)?g=h(g,A.precision):c(g)?g=S({type:g,typeModifier:A.typeModifier,srid:A.srid}):i(g)&&(s.isNumber(A.timePrecision)||A.timezone)&&(g=x(h(g,A.timePrecision),A.timezone)),p(g,A.array_type)),"decorateType"),f=n(g=>["char","varchar","text","bit","varbit"].includes(g),"isString"),m=n(g=>["date","time","timestamp","interval"].includes(g),"isDateTime"),C=n((g,A,V)=>{let v=["current_timestamp","null"];return(f(g)||m(g))&&!v.includes(s.toLower(A))&&!V?R(A):A},"decorateDefault"),N=n((g,A)=>s.chain(A).filter("comment").map(V=>{let v=$(O.comment,{object:"COLUMN",objectName:`${g}.${P(V.name)}`,comment:R(V.comment)});return u(v,V)}).join(` +`).value(),"getColumnComments"),F={"v13.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v12.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v11.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"},"v10.x":{int4multirange:"int4range",int8multirange:"int8range",nummultirange:"numrange",datemultirange:"daterange",tsmultirange:"tsrange",tstzmultirange:"tstzrange"}};return{decorateType:a,decorateDefault:C,getColumnComments:N,replaceTypeByVersion:n((g,A)=>{let V=F[A];return s.get(V,g)||g},"replaceTypeByVersion")}}});var Kt=_((wn,vt)=>{"use strict";vt.exports=({_:s,assignTemplates:$,templates:O,getNamePrefixedWithSchemaName:u,wrap:R,commentIfDeactivated:P})=>{let U=n(({dbVersion:p,triggers:l,tableName:r})=>s.map(l,M(p,r)).join(` +`).trim(),"getTriggersScript"),M=n((p,l)=>r=>{let i=h(r),I=x(r);return $(O.createTrigger,{orReplace:r.triggerOrReplace?" OR REPLACE":"",constraint:r.triggerConstraint?" CONSTRAINT":"",actionTiming:r.triggerType??"",functionKey:p==="v10.x"?"PROCEDURE":"FUNCTION",functionName:r.triggerFunction,name:r.name,tableName:l,events:i,options:I})},"getTriggerScript"),h=n(p=>{var l;return(l=p.triggerEvents)==null?void 0:l.map(r=>{if(r.triggerEvent!=="UPDATE"||s.isEmpty(p.triggerUpdateColumns))return r.triggerEvent;let i=s.chain(p.triggerUpdateColumns).filter("isActivated").map(({name:a})=>a).join(", ").thru(a=>a&&`OF ${a}`).value(),I=s.chain(p.triggerUpdateColumns).reject("isActivated").map(({name:a})=>a).join(", ").thru(a=>!i&&a?`OF ${a}`:a).value(),c=I&&P(I,{isActivated:!1,isPartOfLine:!0});return`UPDATE ${i} ${c}`}).join(" OR ")},"getTriggerEvents"),x=n(p=>{let l="";if(p.triggerConstraint&&(p.triggerReferencedTable&&(l+=R(`FROM ${p.triggerReferencedTable}`," ",` `)),l+=R(p.triggerDeferrable?"DEFERRABLE":"NOT DEFERRABLE"," ",` `),p.triggerDeferrable&&p.triggerTimeConstraintCheck&&(l+=R(p.triggerTimeConstraintCheck," ",` `))),p.triggerReferencing){let r="REFERENCING";p.triggerBeforeImageTransitionRelation&&(r+=` OLD TABLE ${p.triggerBeforeImageTransitionRelation}`),p.triggerAfterImageTransitionRelation&&(r+=` NEW TABLE ${p.triggerAfterImageTransitionRelation}`),l+=R(r," ",` `)}return l+=R(p.triggerConstraint||p.triggerType==="INSTEAD OF"?"FOR EACH ROW":p.triggerEachRowStatement||"FOR EACH STATEMENT"," ",` `),p.triggerCondition&&(l+=R(`WHEN ${p.triggerCondition}`," ",` -`)),l},"getTriggerOptions");return{getTriggersScript:U,hydrateTriggers:n((p,l={})=>{var r;return(((r=s.find(p,"triggers"))==null?void 0:r.triggers)||[]).map(i=>{let I=l[i.triggerReferencedTable];if(!I)return{...i,triggerReferencedTable:""};let c=u(I.code||I.collectionName,I.bucketName);return{...i,triggerReferencedTable:c}})},"hydrateTriggers")}}});var Vt=_((Wn,Mt)=>{Mt.exports=()=>({getLocaleProperties:n($=>{let O=["v13.x","v14.x","v15.x"].includes($.dbVersion);return O&&$.locale?{locale:$.locale}:!O&&$.locale?{collate:$.locale,characterClassification:$.locale}:{collate:$.collate,characterClassification:$.characterClassification}},"getLocaleProperties")})});var qt=_((jn,Bt)=>{var on=et(),Yt=nt(),y=at(),{Sequence:Xn}=Se();Bt.exports=(s,$,O)=>{let u=O.require("lodash"),{tab:R,commentIfDeactivated:P,checkAllKeysDeactivated:U,divideIntoActivatedAndDeactivated:K,hasType:h,wrap:x,clean:S,wrapComment:p,getFunctionArguments:l,wrapInQuotes:r,getNamePrefixedWithSchemaName:i,getColumnsList:I,getViewData:c}=ue()(u),a=Tt(),{generateConstraintsString:f,foreignKeysToString:m,foreignActiveKeysToString:C,createKeyConstraint:N,getConstraintsWarnings:v,additionalPropertiesForForeignKey:G}=Nt()({_:u,commentIfDeactivated:P,checkAllKeysDeactivated:U,assignTemplates:a,getColumnsList:I,wrapInQuotes:r}),g=At()(u,S),{getFunctionsScript:A}=$t()({_:u,templates:y,assignTemplates:a,getFunctionArguments:l,getNamePrefixedWithSchemaName:i,wrapComment:p}),{getProceduresScript:M}=St()({_:u,templates:y,assignTemplates:a,getFunctionArguments:l,getNamePrefixedWithSchemaName:i}),{getSequencesScript:V,createSequenceScript:le,dropSequenceScript:ge,alterSequenceScript:te}=Ot()({_:u,templates:y,assignTemplates:a,getNamePrefixedWithSchemaName:i,wrapInQuotes:r}),{getTableTemporaryValue:He,getTableOptions:We}=bt()({_:u,checkAllKeysDeactivated:U,getColumnsList:I}),{getUserDefinedType:o,isNotPlainType:E}=ht()({_:u,commentIfDeactivated:P,assignTemplates:a,templates:y,getNamePrefixedWithSchemaName:i,wrapComment:p}),{getIndexKeys:b,getIndexOptions:F,getWithOptions:w}=Ut()({_:u,wrapInQuotes:r,checkAllKeysDeactivated:U,getColumnsList:I}),{decorateType:ae,decorateDefault:ne,getColumnComments:Ee,replaceTypeByVersion:_t}=Ft()({_:u,wrap:x,assignTemplates:a,templates:y,commentIfDeactivated:P,wrapInQuotes:r,wrapComment:p}),{getTriggersScript:De,hydrateTriggers:Xe}=Kt()({_:u,wrap:x,assignTemplates:a,templates:y,getNamePrefixedWithSchemaName:i,commentIfDeactivated:P}),{getLocaleProperties:kt}=Vt()();return{createDatabase(e){if(!e.databaseName)return"";let{locale:t,collate:d,characterClassification:T}=kt(e);return a(y.createDatabase,{name:r(e.databaseName),template:e.template?` +`)),l},"getTriggerOptions");return{getTriggersScript:U,hydrateTriggers:n((p,l={})=>{var r;return(((r=s.find(p,"triggers"))==null?void 0:r.triggers)||[]).map(i=>{let I=l[i.triggerReferencedTable];if(!I)return{...i,triggerReferencedTable:""};let c=u(I.code||I.collectionName,I.bucketName);return{...i,triggerReferencedTable:c}})},"hydrateTriggers")}}});var Vt=_((Wn,Mt)=>{"use strict";Mt.exports=()=>({getLocaleProperties:n($=>{let O=["v13.x","v14.x","v15.x"].includes($.dbVersion);return O&&$.locale?{locale:$.locale}:!O&&$.locale?{collate:$.locale,characterClassification:$.locale}:{collate:$.collate,characterClassification:$.characterClassification}},"getLocaleProperties")})});var qt=_((jn,Bt)=>{"use strict";var on=et(),Yt=nt(),y=at(),{Sequence:Xn}=Se();Bt.exports=(s,$,O)=>{let u=O.require("lodash"),{tab:R,commentIfDeactivated:P,checkAllKeysDeactivated:U,divideIntoActivatedAndDeactivated:M,hasType:h,wrap:x,clean:S,wrapComment:p,getFunctionArguments:l,wrapInQuotes:r,getNamePrefixedWithSchemaName:i,getColumnsList:I,getViewData:c}=ue()(u),a=Tt(),{generateConstraintsString:f,foreignKeysToString:m,foreignActiveKeysToString:C,createKeyConstraint:N,getConstraintsWarnings:F,additionalPropertiesForForeignKey:G}=Nt()({_:u,commentIfDeactivated:P,checkAllKeysDeactivated:U,assignTemplates:a,getColumnsList:I,wrapInQuotes:r}),g=At()(u,S),{getFunctionsScript:A}=$t()({_:u,templates:y,assignTemplates:a,getFunctionArguments:l,getNamePrefixedWithSchemaName:i,wrapComment:p}),{getProceduresScript:V}=St()({_:u,templates:y,assignTemplates:a,getFunctionArguments:l,getNamePrefixedWithSchemaName:i}),{getSequencesScript:v,createSequenceScript:le,dropSequenceScript:ge,alterSequenceScript:te}=Ot()({_:u,templates:y,assignTemplates:a,getNamePrefixedWithSchemaName:i,wrapInQuotes:r}),{getTableTemporaryValue:He,getTableOptions:We}=bt()({_:u,checkAllKeysDeactivated:U,getColumnsList:I}),{getUserDefinedType:o,isNotPlainType:E}=ht()({_:u,commentIfDeactivated:P,assignTemplates:a,templates:y,getNamePrefixedWithSchemaName:i,wrapComment:p}),{getIndexKeys:b,getIndexOptions:K,getWithOptions:w}=Ut()({_:u,wrapInQuotes:r,checkAllKeysDeactivated:U,getColumnsList:I}),{decorateType:ae,decorateDefault:ne,getColumnComments:Ee,replaceTypeByVersion:_t}=Ft()({_:u,wrap:x,assignTemplates:a,templates:y,commentIfDeactivated:P,wrapInQuotes:r,wrapComment:p}),{getTriggersScript:De,hydrateTriggers:Xe}=Kt()({_:u,wrap:x,assignTemplates:a,templates:y,getNamePrefixedWithSchemaName:i,commentIfDeactivated:P}),{getLocaleProperties:kt}=Vt()();return{createDatabase(e){if(!e.databaseName)return"";let{locale:t,collate:d,characterClassification:T}=kt(e);return a(y.createDatabase,{name:r(e.databaseName),template:e.template?` TEMPLATE ${e.template}`:"",encoding:e.encoding?` ENCODING ${e.encoding}`:"",locale:t?` LOCALE '${e.locale}'`:"",collate:d?` LC_COLLATE '${e.collate}'`:"",characterClassification:T?` LC_CTYPE '${T}'`:"",tablespace:e.tablespace?` - TABLESPACE '${e.tablespace}'`:""})},createSchema({schemaName:e,ifNotExist:t,comments:d,udfs:T,procedures:L,sequences:B}){let Y=a(y.comment,{object:"SCHEMA",objectName:r(e),comment:p(d)}),k=a(y.createSchema,{name:r(e),ifNotExist:t?" IF NOT EXISTS":"",comment:d?Y:""}),H=A(e,T),W=M(e,L);return u.chain([k,H,W]).compact().map(u.trim).join(` + TABLESPACE '${e.tablespace}'`:""})},createSchema({schemaName:e,ifNotExist:t,comments:d,udfs:T,procedures:L,sequences:B}){let Y=a(y.comment,{object:"SCHEMA",objectName:r(e),comment:p(d)}),k=a(y.createSchema,{name:r(e),ifNotExist:t?" IF NOT EXISTS":"",comment:d?Y:""}),H=A(e,T),W=V(e,L);return u.chain([k,H,W]).compact().map(u.trim).join(` -`).trim().value()},createTable({name:e,columns:t,checkConstraints:d,foreignKeyConstraints:T,schemaData:L,columnDefinitions:B,keyConstraints:Y,inherits:k,description:H,ifNotExist:W,usingMethod:z,on_commit:X,partitioning:q,storage_parameter:Z,table_tablespace_name:J,temporary:j,unlogged:ee,selectStatement:ie,triggers:re,partitionOf:D,partitionBounds:oe},se){let Te=W?" IF NOT EXISTS":"",ce=i(e,L.schemaName),Q=a(y.comment,{object:"TABLE",objectName:ce,comment:p(H)}),Ne=K(Y.filter(({errorMessage:me})=>!me).map(N(y,se)),me=>me.statement),ye=v(Y.filter(({errorMessage:me})=>me)),pe=`${f(Ne,se)}${ye}`,je=D?pe==null?void 0:pe.slice(1):pe,Gt=K(T,me=>me.statement),ze=f(Gt,se),wt=` +`).trim().value()},createTable({name:e,columns:t,checkConstraints:d,foreignKeyConstraints:T,schemaData:L,columnDefinitions:B,keyConstraints:Y,inherits:k,description:H,ifNotExist:W,usingMethod:z,on_commit:X,partitioning:q,storage_parameter:Z,table_tablespace_name:J,temporary:j,unlogged:ee,selectStatement:ie,triggers:re,partitionOf:D,partitionBounds:oe},se){let Te=W?" IF NOT EXISTS":"",ce=i(e,L.schemaName),Q=a(y.comment,{object:"TABLE",objectName:ce,comment:p(H)}),Ne=M(Y.filter(({errorMessage:me})=>!me).map(N(y,se)),me=>me.statement),ye=F(Y.filter(({errorMessage:me})=>me)),pe=`${f(Ne,se)}${ye}`,je=D?pe==null?void 0:pe.slice(1):pe,Gt=M(T,me=>me.statement),ze=f(Gt,se),wt=` `+Ee(ce,B),Ht=D?y.createTablePartitionOf:y.createTable,Wt=D&&!pe?` `:`, `,Qe=u.isEmpty(d)?"":x(u.join(d,`, @@ -63,8 +63,8 @@ var Qt=Object.defineProperty;var n=(s,$)=>Qt(s,"name",{value:$,configurable:!0}) `).trim()+` `,{isActivated:se})},convertColumnDefinition(e){let t=_t(e.type,e.dbVersion),d=e.nullable?"":" NOT NULL",T=e.primaryKey?" "+N(y,!0)(e.primaryKeyOptions).statement:"",L=e.unique?" "+N(y,!0)(e.uniqueKeyOptions).statement:"",B=e.collationRule?` COLLATE "${e.collationRule}"`:"",Y=Array.isArray(e.array_type)&&e.array_type.length>0,k=u.isUndefined(e.default)?"":" DEFAULT "+ne(t,e.default,Y),H=e.dbVersion>=12&&e.generatedColumn&&e.columnGenerationExpression?a(y.generatedColumnClause,{generationExpression:e.columnGenerationExpression}):"";return P(a(y.columnDefinition,{name:r(e.name),type:ae(t,e),generatedColumnClause:H,notNull:d,primaryKey:T,uniqueKey:L,collation:B,defaultValue:k}),{isActivated:e.isActivated})},createIndex(e,t,d,T=!0){let L=t.unique&&t.index_method==="btree",B=r(t.indxName),Y=L?" UNIQUE":"",k=t.concurrently?" CONCURRENTLY":"",H=t.ifNotExist?" IF NOT EXISTS":"",W=t.only?" ONLY":"",z=t.index_method?` USING ${u.toUpper(t.index_method)}`:"",{getDbVersion:X}=ue()(u),q=X(u.get(d,"dbVersion","")),Z=L&&t.nullsDistinct&&q>=15?` - ${t.nullsDistinct}`:"",J=b(t.index_method==="btree"?t.columns:u.map(t.columns,ee=>u.omit(ee,"sortOrder","nullsOrder")),T),j=F(t,T);return P(a(y.index,{unique:Y,concurrently:k,ifNotExist:H,name:B,only:W,using:z,keys:J,options:j,nullsDistinct:Z,tableName:i(e,t.schemaName)}),{isActivated:t.isActivated})},createCheckConstraint(e){return a(y.checkConstraint,{name:e.name?`CONSTRAINT ${r(e.name)}`:"",expression:u.trim(e.expression).replace(/^\(([\s\S]*)\)$/,"$1"),noInherit:e.noInherit?" NO INHERIT":""})},createForeignKeyConstraint({name:e,foreignKey:t,primaryTable:d,primaryKey:T,primaryTableActivated:L,foreignTableActivated:B,foreignSchemaName:Y,primarySchemaName:k,customProperties:H,isActivated:W},z,X){let q=U(T),Z=U(t),J=!q&&!Z&&L&&B,{foreignOnDelete:j,foreignOnUpdate:ee,foreignMatch:ie,deferrable:re,deferrableConstraintCheckTime:D}=G(H),oe=a(y.createForeignKeyConstraint,{primaryTable:i(d,k||X.schemaName),name:e?`CONSTRAINT ${r(e)}`:"",foreignKey:J?m(t):C(t),primaryKey:J?m(T):C(T),onDelete:j?` ON DELETE ${j}`:"",onUpdate:ee?` ON UPDATE ${ee}`:"",match:ie?` MATCH ${ie}`:"",deferrable:re?` ${re}`:"",deferrableConstraintCheckTime:re==="DEFERRABLE"&&D?` ${D}`:""});return{statement:u.trim(oe),isActivated:J&&W}},createForeignKey({name:e,foreignTable:t,foreignKey:d,primaryTable:T,primaryKey:L,primaryTableActivated:B,foreignTableActivated:Y,foreignSchemaName:k,primarySchemaName:H,customProperties:W,isActivated:z},X,q){let Z=U(L),J=U(d),j=!Z&&!J&&B&&Y,{foreignOnDelete:ee,foreignOnUpdate:ie,foreignMatch:re,deferrable:D,deferrableConstraintCheckTime:oe}=G(W),se=a(y.createForeignKey,{primaryTable:i(T,H||q.schemaName),foreignTable:i(t,k||q.schemaName),name:e?r(e):"",foreignKey:j?m(d):C(d),primaryKey:j?m(L):C(L),onDelete:ee?` ON DELETE ${ee}`:"",onUpdate:ie?` ON UPDATE ${ie}`:"",match:re?` MATCH ${re}`:"",deferrable:D?` ${D}`:"",deferrableConstraintCheckTime:D==="DEFERRABLE"&&oe?` ${oe}`:""});return{statement:u.trim(se),isActivated:j&&z}},createView(e,t,d){var oe,se,Te,ce;let T=i(e.name,e.schemaName),L=a(y.comment,{object:"VIEW",objectName:T,comment:p(e.comment)}),Y=U(e.keys||[])||!d,{columns:k,tables:H}=c(e.keys),W=k.map(Q=>Q.statement).join(`, - `);if(!Y){let Q=K(k,ye=>ye.statement),Ne=Q.deactivatedItems.length?P(Q.deactivatedItems.join(`, + ${t.nullsDistinct}`:"",J=b(t.index_method==="btree"?t.columns:u.map(t.columns,ee=>u.omit(ee,"sortOrder","nullsOrder")),T),j=K(t,T);return P(a(y.index,{unique:Y,concurrently:k,ifNotExist:H,name:B,only:W,using:z,keys:J,options:j,nullsDistinct:Z,tableName:i(e,t.schemaName)}),{isActivated:t.isActivated})},createCheckConstraint(e){return a(y.checkConstraint,{name:e.name?`CONSTRAINT ${r(e.name)}`:"",expression:u.trim(e.expression).replace(/^\(([\s\S]*)\)$/,"$1"),noInherit:e.noInherit?" NO INHERIT":""})},createForeignKeyConstraint({name:e,foreignKey:t,primaryTable:d,primaryKey:T,primaryTableActivated:L,foreignTableActivated:B,foreignSchemaName:Y,primarySchemaName:k,customProperties:H,isActivated:W},z,X){let q=U(T),Z=U(t),J=!q&&!Z&&L&&B,{foreignOnDelete:j,foreignOnUpdate:ee,foreignMatch:ie,deferrable:re,deferrableConstraintCheckTime:D}=G(H),oe=a(y.createForeignKeyConstraint,{primaryTable:i(d,k||X.schemaName),name:e?`CONSTRAINT ${r(e)}`:"",foreignKey:J?m(t):C(t),primaryKey:J?m(T):C(T),onDelete:j?` ON DELETE ${j}`:"",onUpdate:ee?` ON UPDATE ${ee}`:"",match:ie?` MATCH ${ie}`:"",deferrable:re?` ${re}`:"",deferrableConstraintCheckTime:re==="DEFERRABLE"&&D?` ${D}`:""});return{statement:u.trim(oe),isActivated:J&&W}},createForeignKey({name:e,foreignTable:t,foreignKey:d,primaryTable:T,primaryKey:L,primaryTableActivated:B,foreignTableActivated:Y,foreignSchemaName:k,primarySchemaName:H,customProperties:W,isActivated:z},X,q){let Z=U(L),J=U(d),j=!Z&&!J&&B&&Y,{foreignOnDelete:ee,foreignOnUpdate:ie,foreignMatch:re,deferrable:D,deferrableConstraintCheckTime:oe}=G(W),se=a(y.createForeignKey,{primaryTable:i(T,H||q.schemaName),foreignTable:i(t,k||q.schemaName),name:e?r(e):"",foreignKey:j?m(d):C(d),primaryKey:j?m(L):C(L),onDelete:ee?` ON DELETE ${ee}`:"",onUpdate:ie?` ON UPDATE ${ie}`:"",match:re?` MATCH ${re}`:"",deferrable:D?` ${D}`:"",deferrableConstraintCheckTime:D==="DEFERRABLE"&&oe?` ${oe}`:""});return{statement:u.trim(se),isActivated:j&&z}},createView(e,t,d){var oe,se,Te,ce;let T=i(e.name,e.schemaName),L=a(y.comment,{object:"VIEW",objectName:T,comment:p(e.comment)}),Y=U(e.keys||[])||!d,{columns:k,tables:H}=c(e.keys),W=k.map(Q=>Q.statement).join(`, + `);if(!Y){let Q=M(k,ye=>ye.statement),Ne=Q.deactivatedItems.length?P(Q.deactivatedItems.join(`, `),{isActivated:!1,isPartOfLine:!0}):"";W=Q.activatedItems.join(`, `)+Ne}let z=u.trim(e.selectStatement)?u.trim(R(e.selectStatement)):a(y.viewSelectStatement,{tableName:H.join(", "),keys:W}),X=(oe=e.viewOptions)!=null&&oe.check_option?`check_option=${(se=e.viewOptions)==null?void 0:se.check_option}`:"",q=(Te=e.viewOptions)!=null&&Te.security_barrier?"security_barrier":"",Z=15,{getDbVersion:J}=ue()(u),j=(ce=e.viewOptions)!=null&&ce.security_invoker&&J(t.dbVersion)>=Z?"security_invoker":"",ee=X||q||j?` WITH (${u.compact([X,q,j]).join(",")})`:"",ie=n(Q=>Q.withCheckOption&&Q.checkTestingScope?` @@ -72,4 +72,4 @@ var Qt=Object.defineProperty;var n=(s,$)=>Qt(s,"name",{value:$,configurable:!0}) WITH CHECK OPTION`:"","getCheckOption"),re=P(a(y.createView,{name:T,orReplace:e.orReplace?" OR REPLACE":"",temporary:e.temporary?" TEMPORARY":"",checkOption:ie(e),comment:e.comment?L:"",withOptions:ee,selectStatement:z}),{isActivated:!Y}),D=De({dbVersion:e.dbVersion,tableName:T,triggers:e.triggers});return[re,D].map(u.trim).join(` `).trim()+` -`},dropView(e){let t={viewName:e};return a(y.dropView,t)},createViewIndex(){return""},createUdt(e){let t=u.map(e.properties,this.convertColumnDefinition);return o(e,t)},getDefaultType(e){return on[e]},getTypesDescriptors(){return Yt},hasType(e){return h(Yt,e)},hydrateDatabase({modelData:e}){return e=u.get(e,"0",{}),{databaseName:e.database_name,tablespace:e.tablespace_name,encoding:e.encoding,template:e.template,collate:e.LC_COLLATE,characterClassification:e.LC_CTYPE,dbVersion:e.dbVersion,locale:e.locale}},hydrateColumn({columnDefinition:e,jsonSchema:t,schemaData:d,definitionJsonSchema:T={},parentJsonSchema:L}){let B=u.includes(["char","varchar","text"],e.type)?t.collationRule:"",Y=["time","timestamp"],k=u.includes(Y,e.type)?t.timePrecision:"",H=u.includes(Y,e.type)?t.timezone:"",W=e.type==="interval"?t.intervalOptions:"",{getDbVersion:z}=ue()(u),X=z(d.dbVersion),q=u.omit(g.hydratePrimaryKeyOptions(u.first(t.primaryKeyOptions)||{},e.name,e.isActivated,L),"columns"),Z=u.omit(g.hydrateUniqueOptions({options:u.first(t.uniqueKeyOptions)||{},columnName:e.name,isActivated:e.isActivated,jsonSchema:L,dbVersion:X}),"columns");return{name:e.name,type:e.type,primaryKey:g.isInlinePrimaryKey(t),primaryKeyOptions:q,unique:g.isInlineUnique(t),uniqueKeyOptions:Z,nullable:e.nullable,default:e.default,comment:t.refDescription||t.description||T.description,isActivated:e.isActivated,scale:e.scale,precision:e.precision,length:e.length,enum:t.enum,array_type:t.array_type,unit:t.unit,rangeSubtype:t.rangeSubtype,operatorClass:t.operatorClass,collation:t.collation,canonicalFunction:t.canonicalFunction,subtypeDiffFunction:t.subtypeDiffFunction,multiRangeType:t.multiRangeType,schemaName:d.schemaName,underlyingType:t.underlyingType,checkConstraints:t.checkConstraints,typeModifier:t.typeModifier,srid:t.srid,collationRule:B,timePrecision:k,timezone:H,intervalOptions:W,dbVersion:X,generatedColumn:!!t.generatedColumn,columnGenerationExpression:t.columnGenerationExpression}},hydrateJsonSchemaColumn(e,t){return!e.$ref||u.isEmpty(t)||E(t)?e:(e=u.omit(e,"$ref"),{...t,...e})},hydrateIndex(e,t,d){return{...e,schemaName:d.schemaName}},hydrateViewIndex(e){return{}},hydrateCheckConstraint(e){return{name:e.chkConstrName,expression:e.constrExpression,noInherit:e.noInherit}},hydrateSchema(e,t){let d=u.get(t,"modelData.0.dbVersion");return{schemaName:e.name,ifNotExist:e.ifNotExist,comments:e.description,udfs:(t==null?void 0:t.udfs)||[],procedures:(t==null?void 0:t.procedures)||[],sequences:(t==null?void 0:t.sequences)||[],dbVersion:d}},hydrateTable({tableData:e,entityData:t,jsonSchema:d}){let T=t[0],L=u.chain(T.inherits).map(({parentTable:q})=>u.get(e,`relatedSchemas[${q}]`,"")).compact().map(q=>q.code||q.collectionName).join(", ").thru(q=>q?`(${q})`:"").value(),B=u.first(T.partitioning)||{},Y=g.getKeys(B.compositePartitionKey,d),k=u.get(e,`relatedSchemas[${T.partitionOf}]`),H=k?i(k.collectionName,k.bucketName):"",W=Xe(t,e.relatedSchemas),{getDbVersion:z}=ue()(u),X=z(u.get(e,"dbData.dbVersion",""));return{...e,triggers:W,partitionOf:H,keyConstraints:g.getTableKeyConstraints(d,X),inherits:L,selectStatement:u.trim(T.selectStatement),partitioning:u.assign({},B,{compositePartitionKey:Y}),...u.pick(T,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","table_tablespace_name","partitionBounds")}},hydrateViewColumn(e){return{name:e.name,tableName:e.entityName,alias:e.alias,isActivated:e.isActivated,dbName:e.dbName}},hydrateView({viewData:e,entityData:t,relatedSchemas:d}){let T=t[0],L=Xe(t,d);return{name:e.name,keys:e.keys,comment:T.description,orReplace:T.orReplace,temporary:T.temporary,recursive:T.recursive,viewOptions:T.viewOptions,selectStatement:T.selectStatement,withCheckOption:T.withCheckOption,checkTestingScope:T.withCheckOption?T.checkTestingScope:"",schemaName:e.schemaData.schemaName,triggers:L}},commentIfDeactivated(e,t,d){return e},alterColumnType(e,t,d,T){let L=d;return T.length?L+=`(${T.length})`:T.precision&&T.scale?L+=`(${T.precision},${T.scale})`:T.precision&&(L+=`(${T.precision})`),a(y.alterColumnType,{tableName:e,columnName:t,dataType:L})},setNotNullConstraint(e,t){return a(y.addNotNullConstraint,{tableName:e,columnName:t})},dropNotNullConstraint(e,t){return a(y.dropNotNullConstraint,{tableName:e,columnName:t})},renameColumn(e,t,d){return a(y.renameColumn,{tableName:e,oldColumnName:t,newColumnName:d})},addCheckConstraint(e,t,d){let T={tableName:e,constraintName:t,expression:d};return a(y.addCheckConstraint,T)},dropConstraint(e,t){let d={tableName:e,constraintName:t};return a(y.dropConstraint,d)},updateTableComment(e,t){let d={tableName:e,comment:t};return a(y.updateCommentOnTable,d)},dropTableComment(e){let t={tableName:e,comment:"NULL"};return a(y.updateCommentOnTable,t)},updateColumnComment(e,t){let d={columnName:e,comment:t};return a(y.updateCommentOnColumn,d)},dropColumnComment(e){let t={columnName:e,comment:"NULL"};return a(y.updateCommentOnColumn,t)},updateSchemaComment(e,t){let d={schemaName:e,comment:t};return a(y.updateCommentOnSchema,d)},dropSchemaComment(e){let t={schemaName:e,comment:"NULL"};return a(y.updateCommentOnSchema,t)},updateViewComment(e,t){let d={viewName:e,comment:t};return a(y.updateCommentOnView,d)},dropViewComment(e){let t={viewName:e,comment:"NULL"};return a(y.updateCommentOnView,t)},createSchemaOnly(e){let t={schemaName:e};return a(y.createSchemaOnly,t)},dropSchema(e){let t={schemaName:e};return a(y.dropSchema,t)},dropTable(e){let t={tableName:e};return a(y.dropTable,t)},addColumn(e,t){let d={tableName:e,columnDefinition:t};return a(y.addColumn,d)},dropColumn(e,t){let d={tableName:e,columnName:t};return a(y.dropColumn,d)},dropDomain(e){let t={udtName:e};return a(y.dropDomain,t)},dropType(e){let t={udtName:e};return a(y.dropType,t)},alterTypeAddAttribute(e,t){let d={udtName:e,columnDefinition:t};return a(y.alterTypeAddAttribute,d)},alterTypeDropAttribute(e,t){let d={udtName:e,attributeName:t};return a(y.alterTypeDropAttribute,d)},alterTypeRenameAttribute(e,t,d){let T={udtName:e,oldAttributeName:t,newAttributeName:d};return a(y.alterTypeRenameAttribute,T)},alterTypeChangeAttributeType(e,t,d){let T={udtName:e,attributeName:t,newDataType:d};return a(y.alterTypeChangeAttributeType,T)},dropForeignKey(e,t){let d={tableName:e,fkConstraintName:t};return a(y.dropForeignKey,d)},createKeyConstraint(e,t,d){let T=N(y,t)(d);return{statement:a(y.addPkConstraint,{constraintStatement:(T.statement||"").trim(),tableName:e}),isActivated:T.isActivated}},dropKeyConstraint(e,t){let d={tableName:e,constraintName:t};return a(y.dropConstraint,d)},createSchemaSequences({schemaName:e,sequences:t}){return V({schemaName:e,sequences:t})},createSchemaSequence({schemaName:e,sequence:t}){return le({schemaName:e,sequence:t})},dropSchemaSequence({schemaName:e,sequence:t}){return ge({schemaName:e,sequence:t})},alterSchemaSequence({schemaName:e,sequence:t,oldSequence:d}){return te({schemaName:e,sequence:t,oldSequence:d})},dropIndex({indexName:e}){let t={indexName:e};return a(y.dropIndex,t)},alterIndexRename({schemaName:e,oldIndexName:t,newIndexName:d}){let T=r(e),L=i(r(t),T),B=r(d),Y={oldIndexName:L,newIndexName:B};return a(y.alterIndexRename,Y)},alterIndexTablespace({schemaName:e,indexName:t,tablespaceName:d}){let T=r(e),B={indexName:i(r(t),T),tablespaceName:d};return a(y.alterIndexTablespace,B)},alterIndexStorageParams({schemaName:e,indexName:t,index:d}){let T=r(e),L=i(r(t),T),B=w(d),Y={indexName:L,options:B};return a(y.alterIndexStorageParams,Y)},reindexIndex({schemaName:e,indexName:t}){let d=r(e),L={indexName:i(r(t),d)};return a(y.reindexIndex,L)}}}});module.exports=qt(); +`},dropView(e){let t={viewName:e};return a(y.dropView,t)},createViewIndex(){return""},createUdt(e){let t=u.map(e.properties,this.convertColumnDefinition);return o(e,t)},getDefaultType(e){return on[e]},getTypesDescriptors(){return Yt},hasType(e){return h(Yt,e)},hydrateDatabase({modelData:e}){return e=u.get(e,"0",{}),{databaseName:e.database_name,tablespace:e.tablespace_name,encoding:e.encoding,template:e.template,collate:e.LC_COLLATE,characterClassification:e.LC_CTYPE,dbVersion:e.dbVersion,locale:e.locale}},hydrateColumn({columnDefinition:e,jsonSchema:t,schemaData:d,definitionJsonSchema:T={},parentJsonSchema:L}){let B=u.includes(["char","varchar","text"],e.type)?t.collationRule:"",Y=["time","timestamp"],k=u.includes(Y,e.type)?t.timePrecision:"",H=u.includes(Y,e.type)?t.timezone:"",W=e.type==="interval"?t.intervalOptions:"",{getDbVersion:z}=ue()(u),X=z(d.dbVersion),q=u.omit(g.hydratePrimaryKeyOptions(u.first(t.primaryKeyOptions)||{},e.name,e.isActivated,L),"columns"),Z=u.omit(g.hydrateUniqueOptions({options:u.first(t.uniqueKeyOptions)||{},columnName:e.name,isActivated:e.isActivated,jsonSchema:L,dbVersion:X}),"columns");return{name:e.name,type:e.type,primaryKey:g.isInlinePrimaryKey(t),primaryKeyOptions:q,unique:g.isInlineUnique(t),uniqueKeyOptions:Z,nullable:e.nullable,default:e.default,comment:t.refDescription||t.description||T.description,isActivated:e.isActivated,scale:e.scale,precision:e.precision,length:e.length,enum:t.enum,array_type:t.array_type,unit:t.unit,rangeSubtype:t.rangeSubtype,operatorClass:t.operatorClass,collation:t.collation,canonicalFunction:t.canonicalFunction,subtypeDiffFunction:t.subtypeDiffFunction,multiRangeType:t.multiRangeType,schemaName:d.schemaName,underlyingType:t.underlyingType,checkConstraints:t.checkConstraints,typeModifier:t.typeModifier,srid:t.srid,collationRule:B,timePrecision:k,timezone:H,intervalOptions:W,dbVersion:X,generatedColumn:!!t.generatedColumn,columnGenerationExpression:t.columnGenerationExpression}},hydrateJsonSchemaColumn(e,t){return!e.$ref||u.isEmpty(t)||E(t)?e:(e=u.omit(e,"$ref"),{...t,...e})},hydrateIndex(e,t,d){return{...e,schemaName:d.schemaName}},hydrateViewIndex(e){return{}},hydrateCheckConstraint(e){return{name:e.chkConstrName,expression:e.constrExpression,noInherit:e.noInherit}},hydrateSchema(e,t){let d=u.get(t,"modelData.0.dbVersion");return{schemaName:e.name,ifNotExist:e.ifNotExist,comments:e.description,udfs:(t==null?void 0:t.udfs)||[],procedures:(t==null?void 0:t.procedures)||[],sequences:(t==null?void 0:t.sequences)||[],dbVersion:d}},hydrateTable({tableData:e,entityData:t,jsonSchema:d}){let T=t[0],L=u.chain(T.inherits).map(({parentTable:q})=>u.get(e,`relatedSchemas[${q}]`,"")).compact().map(q=>q.code||q.collectionName).join(", ").thru(q=>q?`(${q})`:"").value(),B=u.first(T.partitioning)||{},Y=g.getKeys(B.compositePartitionKey,d),k=u.get(e,`relatedSchemas[${T.partitionOf}]`),H=k?i(k.collectionName,k.bucketName):"",W=Xe(t,e.relatedSchemas),{getDbVersion:z}=ue()(u),X=z(u.get(e,"dbData.dbVersion",""));return{...e,triggers:W,partitionOf:H,keyConstraints:g.getTableKeyConstraints(d,X),inherits:L,selectStatement:u.trim(T.selectStatement),partitioning:u.assign({},B,{compositePartitionKey:Y}),...u.pick(T,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","table_tablespace_name","partitionBounds")}},hydrateViewColumn(e){return{name:e.name,tableName:e.entityName,alias:e.alias,isActivated:e.isActivated,dbName:e.dbName}},hydrateView({viewData:e,entityData:t,relatedSchemas:d}){let T=t[0],L=Xe(t,d);return{name:e.name,keys:e.keys,comment:T.description,orReplace:T.orReplace,temporary:T.temporary,recursive:T.recursive,viewOptions:T.viewOptions,selectStatement:T.selectStatement,withCheckOption:T.withCheckOption,checkTestingScope:T.withCheckOption?T.checkTestingScope:"",schemaName:e.schemaData.schemaName,triggers:L}},commentIfDeactivated(e,t,d){return e},alterColumnType(e,t,d,T){let L=d;return T.length?L+=`(${T.length})`:T.precision&&T.scale?L+=`(${T.precision},${T.scale})`:T.precision&&(L+=`(${T.precision})`),a(y.alterColumnType,{tableName:e,columnName:t,dataType:L})},setNotNullConstraint(e,t){return a(y.addNotNullConstraint,{tableName:e,columnName:t})},dropNotNullConstraint(e,t){return a(y.dropNotNullConstraint,{tableName:e,columnName:t})},renameColumn(e,t,d){return a(y.renameColumn,{tableName:e,oldColumnName:t,newColumnName:d})},addCheckConstraint(e,t,d){let T={tableName:e,constraintName:t,expression:d};return a(y.addCheckConstraint,T)},dropConstraint(e,t){let d={tableName:e,constraintName:t};return a(y.dropConstraint,d)},updateTableComment(e,t){let d={tableName:e,comment:t};return a(y.updateCommentOnTable,d)},dropTableComment(e){let t={tableName:e,comment:"NULL"};return a(y.updateCommentOnTable,t)},updateColumnComment(e,t){let d={columnName:e,comment:t};return a(y.updateCommentOnColumn,d)},dropColumnComment(e){let t={columnName:e,comment:"NULL"};return a(y.updateCommentOnColumn,t)},updateSchemaComment(e,t){let d={schemaName:e,comment:t};return a(y.updateCommentOnSchema,d)},dropSchemaComment(e){let t={schemaName:e,comment:"NULL"};return a(y.updateCommentOnSchema,t)},updateViewComment(e,t){let d={viewName:e,comment:t};return a(y.updateCommentOnView,d)},dropViewComment(e){let t={viewName:e,comment:"NULL"};return a(y.updateCommentOnView,t)},createSchemaOnly(e){let t={schemaName:e};return a(y.createSchemaOnly,t)},dropSchema(e){let t={schemaName:e};return a(y.dropSchema,t)},dropTable(e){let t={tableName:e};return a(y.dropTable,t)},addColumn(e,t){let d={tableName:e,columnDefinition:t};return a(y.addColumn,d)},dropColumn(e,t){let d={tableName:e,columnName:t};return a(y.dropColumn,d)},dropDomain(e){let t={udtName:e};return a(y.dropDomain,t)},dropType(e){let t={udtName:e};return a(y.dropType,t)},alterTypeAddAttribute(e,t){let d={udtName:e,columnDefinition:t};return a(y.alterTypeAddAttribute,d)},alterTypeDropAttribute(e,t){let d={udtName:e,attributeName:t};return a(y.alterTypeDropAttribute,d)},alterTypeRenameAttribute(e,t,d){let T={udtName:e,oldAttributeName:t,newAttributeName:d};return a(y.alterTypeRenameAttribute,T)},alterTypeChangeAttributeType(e,t,d){let T={udtName:e,attributeName:t,newDataType:d};return a(y.alterTypeChangeAttributeType,T)},dropForeignKey(e,t){let d={tableName:e,fkConstraintName:t};return a(y.dropForeignKey,d)},createKeyConstraint(e,t,d){let T=N(y,t)(d);return{statement:a(y.addPkConstraint,{constraintStatement:(T.statement||"").trim(),tableName:e}),isActivated:T.isActivated}},dropKeyConstraint(e,t){let d={tableName:e,constraintName:t};return a(y.dropConstraint,d)},createSchemaSequences({schemaName:e,sequences:t}){return v({schemaName:e,sequences:t})},createSchemaSequence({schemaName:e,sequence:t}){return le({schemaName:e,sequence:t})},dropSchemaSequence({schemaName:e,sequence:t}){return ge({schemaName:e,sequence:t})},alterSchemaSequence({schemaName:e,sequence:t,oldSequence:d}){return te({schemaName:e,sequence:t,oldSequence:d})},dropIndex({indexName:e}){let t={indexName:e};return a(y.dropIndex,t)},alterIndexRename({schemaName:e,oldIndexName:t,newIndexName:d}){let T=r(e),L=i(r(t),T),B=r(d),Y={oldIndexName:L,newIndexName:B};return a(y.alterIndexRename,Y)},alterIndexTablespace({schemaName:e,indexName:t,tablespaceName:d}){let T=r(e),B={indexName:i(r(t),T),tablespaceName:d};return a(y.alterIndexTablespace,B)},alterIndexStorageParams({schemaName:e,indexName:t,index:d}){let T=r(e),L=i(r(t),T),B=w(d),Y={indexName:L,options:B};return a(y.alterIndexStorageParams,Y)},reindexIndex({schemaName:e,indexName:t}){let d=r(e),L={indexName:i(r(t),d)};return a(y.reindexIndex,L)}}}});module.exports=qt(); diff --git a/localization/en.json b/localization/en.json index eb08d35..9e23304 100644 --- a/localization/en.json +++ b/localization/en.json @@ -16,7 +16,7 @@ "TOOLBAR___ADD_ATTRIBUTE": "Add Column", "TOOLBAR___INSERT_FIELD": "Insert Column", "TOOLBAR___APPEND_FIELD": "Append Column", - "TOOLBAR___TOGGLE_FIELD_DETAILS": "Toogle field details", + "TOOLBAR___TOGGLE_FIELD_DETAILS": "Toggle field details", "TOOLBAR___SHOW_FOREIGN_MASTER": "Toggle foreign master", "TOOLBAR___SHOW_MODEL_VIEW": "Toggle model views", "TOOLBAR___DISTRIBUTE_ORTHOGONALLY": "Distribute tables orthogonally", diff --git a/package.json b/package.json index 6b26cce..4a7cc81 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "PostgreSQL", - "version": "0.2.1", + "version": "0.2.2", "author": "hackolade", "engines": { "hackolade": "6.1.2", @@ -61,24 +61,22 @@ }, "devDependencies": { "@hackolade/hck-esbuild-plugins-pack": "0.0.1", - "esbuild": "0.21.3", + "@typescript-eslint/parser": "7.11.0", + "@typescript-eslint/eslint-plugin": "7.11.0", + "esbuild": "0.20.2", "esbuild-plugin-clean": "1.0.1", - "eslint": "9.3.0", + "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", + "eslint-formatter-teamcity": "^1.0.0", + "eslint-plugin-import": "^2.26.0", "eslint-plugin-prettier": "5.1.3", + "eslint-plugin-unused-imports": "3.2.0", "lint-staged": "14.0.1", "prettier": "3.2.5", "simple-git-hooks": "2.11.1" }, "dependencies": { - "pg": "^8.7.1", - "tunnel-ssh": "^4.1.6" - }, - "overrides": { - "tunnel-ssh": { - "cpu-features": "npm:-@0.0.1", - "ssh2": "npm:-@0.0.1" - } + "pg": "^8.7.1" }, "release": true } \ No newline at end of file diff --git a/polyglot/adapter.json b/polyglot/adapter.json index 89d9cc5..c3466ec 100644 --- a/polyglot/adapter.json +++ b/polyglot/adapter.json @@ -126,5 +126,27 @@ } } ] + }, + "postConvert": { + "modify": { + "field": [ + { + "from": { + "type": "jsonObject" + }, + "to": { + "subtype": "object" + } + }, + { + "from": { + "type": "jsonArray" + }, + "to": { + "subtype": "array" + } + } + ] + } } } diff --git a/properties_pane/field_level/fieldLevelConfig.json b/properties_pane/field_level/fieldLevelConfig.json index a5e6da6..d9c3b2b 100644 --- a/properties_pane/field_level/fieldLevelConfig.json +++ b/properties_pane/field_level/fieldLevelConfig.json @@ -5425,6 +5425,24 @@ making sure that you maintain a proper JSON format. "propertyType": "details", "template": "textarea" }, + { + "propertyName": "Min Properties", + "propertyKeyword": "minProperties", + "propertyType": "numeric", + "dependency": { + "key": "subtype", + "value": "object" + } + }, + { + "propertyName": "Max Properties", + "propertyKeyword": "maxProperties", + "propertyType": "numeric", + "dependency": { + "key": "subtype", + "value": "object" + } + }, { "propertyName": "Array type", "propertyType": "group", diff --git a/reverse_engineering/api.js b/reverse_engineering/api.js index 7e20d60..5a8a57a 100644 --- a/reverse_engineering/api.js +++ b/reverse_engineering/api.js @@ -1,9 +1,5 @@ -"use strict";var Le=Object.defineProperty;var aa=Object.getOwnPropertyDescriptor;var oa=Object.getOwnPropertyNames;var ca=Object.prototype.hasOwnProperty;var i=(t,e)=>Le(t,"name",{value:e,configurable:!0});var ua=(t,e)=>()=>(t&&(e=t(t=0)),e);var h=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),la=(t,e)=>{for(var r in e)Le(t,r,{get:e[r],enumerable:!0})},pa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oa(e))!ca.call(t,s)&&s!==r&&Le(t,s,{get:()=>e[s],enumerable:!(n=aa(e,s))||n.enumerable});return t};var ha=t=>pa(Le({},"__esModule",{value:!0}),t);var an=h((Gh,sn)=>{var fa=i(({title:t,logger:e,hiddenKeys:r})=>({info(n,s={}){e.log("info",{message:n,...s},t,r)},progress(n,s="",a=""){e.progress({message:n,containerName:s,entityName:a})},error(n){e.log("error",da(n),t)}}),"createLogger"),da=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");sn.exports={createLogger:fa}});var cn=h((Hh,on)=>{var ue=1e3,le=ue*60,pe=le*60,he=pe*24,_a=he*365.25;on.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return ma(t);if(r==="number"&&isNaN(t)===!1)return e.long?ya(t):ga(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function ma(t){if(t=String(t),!(t.length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*_a;case"days":case"day":case"d":return r*he;case"hours":case"hour":case"hrs":case"hr":case"h":return r*pe;case"minutes":case"minute":case"mins":case"min":case"m":return r*le;case"seconds":case"second":case"secs":case"sec":case"s":return r*ue;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}i(ma,"parse");function ga(t){return t>=he?Math.round(t/he)+"d":t>=pe?Math.round(t/pe)+"h":t>=le?Math.round(t/le)+"m":t>=ue?Math.round(t/ue)+"s":t+"ms"}i(ga,"fmtShort");function ya(t){return Pe(t,he,"day")||Pe(t,pe,"hour")||Pe(t,le,"minute")||Pe(t,ue,"second")||t+" ms"}i(ya,"fmtLong");function Pe(t,e,r){if(!(t{E=un.exports=ot.debug=ot.default=ot;E.coerce=ba;E.disable=Ta;E.enable=Sa;E.enabled=va;E.humanize=cn();E.names=[];E.skips=[];E.formatters={};var at;function Ea(t){var e=0,r;for(r in t)e=(e<<5)-e+t.charCodeAt(r),e|=0;return E.colors[Math.abs(e)%E.colors.length]}i(Ea,"selectColor");function ot(t){function e(){if(e.enabled){var r=e,n=+new Date,s=n-(at||n);r.diff=s,r.prev=at,r.curr=n,at=n;for(var a=new Array(arguments.length),o=0;o{x=pn.exports=ct();x.log=Ca;x.formatArgs=wa;x.save=Oa;x.load=ln;x.useColors=Aa;x.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:Na();x.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function Aa(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}i(Aa,"useColors");x.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}};function wa(t){var e=this.useColors;if(t[0]=(e?"%c":"")+this.namespace+(e?" %c":" ")+t[0]+(e?"%c ":" ")+"+"+x.humanize(this.diff),!!e){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,function(a){a!=="%%"&&(n++,a==="%c"&&(s=n))}),t.splice(s,0,r)}}i(wa,"formatArgs");function Ca(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}i(Ca,"log");function Oa(t){try{t==null?x.storage.removeItem("debug"):x.storage.debug=t}catch{}}i(Oa,"save");function ln(){var t;try{t=x.storage.debug}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}i(ln,"load");x.enable(ln());function Na(){try{return window.localStorage}catch{}}i(Na,"localstorage")});var mn=h((O,_n)=>{var fn=require("tty"),fe=require("util");O=_n.exports=ct();O.init=Ma;O.log=La;O.formatArgs=xa;O.save=Pa;O.load=dn;O.useColors=Ra;O.colors=[6,2,3,4,5,1];O.inspectOpts=Object.keys(process.env).filter(function(t){return/^debug_/i.test(t)}).reduce(function(t,e){var r=e.substring(6).toLowerCase().replace(/_([a-z])/g,function(s,a){return a.toUpperCase()}),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});var J=parseInt(process.env.DEBUG_FD,10)||2;J!==1&&J!==2&&fe.deprecate(function(){},"except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();var Ia=J===1?process.stdout:J===2?process.stderr:qa(J);function Ra(){return"colors"in O.inspectOpts?!!O.inspectOpts.colors:fn.isatty(J)}i(Ra,"useColors");O.formatters.o=function(t){return this.inspectOpts.colors=this.useColors,fe.inspect(t,this.inspectOpts).split(` -`).map(function(e){return e.trim()}).join(" ")};O.formatters.O=function(t){return this.inspectOpts.colors=this.useColors,fe.inspect(t,this.inspectOpts)};function xa(t){var e=this.namespace,r=this.useColors;if(r){var n=this.color,s=" \x1B[3"+n+";1m"+e+" \x1B[0m";t[0]=s+t[0].split(` -`).join(` -`+s),t.push("\x1B[3"+n+"m+"+O.humanize(this.diff)+"\x1B[0m")}else t[0]=new Date().toUTCString()+" "+e+" "+t[0]}i(xa,"formatArgs");function La(){return Ia.write(fe.format.apply(fe,arguments)+` -`)}i(La,"log");function Pa(t){t==null?delete process.env.DEBUG:process.env.DEBUG=t}i(Pa,"save");function dn(){return process.env.DEBUG}i(dn,"load");function qa(t){var e,r=process.binding("tty_wrap");switch(r.guessHandleType(t)){case"TTY":e=new fn.WriteStream(t),e._type="tty",e._handle&&e._handle.unref&&e._handle.unref();break;case"FILE":var n=require("fs");e=new n.SyncWriteStream(t,{autoClose:!1}),e._type="fs";break;case"PIPE":case"TCP":var s=require("net");e=new s.Socket({fd:t,readable:!1,writable:!0}),e.readable=!1,e.read=null,e._type="pipe",e._handle&&e._handle.unref&&e._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return e.fd=t,e._isStdio=!0,e}i(qa,"createWritableStdioStream");function Ma(t){t.inspectOpts={};for(var e=Object.keys(O.inspectOpts),r=0;r{typeof process<"u"&&process.type==="renderer"?ut.exports=hn():ut.exports=mn()});var gn=h(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.default=null});var wn=h((Jh,An)=>{var En=9007199254740991,Da="[object Arguments]",Fa="[object Function]",Ba="[object GeneratorFunction]",ka=/^(?:0|[1-9]\d*)$/;function Sn(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}i(Sn,"apply");function Ua(t,e){for(var r=-1,n=Array(t);++r1?r[s-1]:void 0,o=s>2?r[2]:void 0;for(a=t.length>3&&typeof a=="function"?(s--,a):void 0,o&&za(r[0],r[1],o)&&(a=s<3?void 0:a,s=1),e=Object(e);++n-1&&t%1==0&&t-1&&t%1==0&&t<=En}i(to,"isLength");function dt(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}i(dt,"isObject");function ro(t){return!!t&&typeof t=="object"}i(ro,"isObjectLike");var no=$a(function(t,e,r,n){Va(e,io(e),t,n)}),so=vn(function(t){return t.push(void 0,Ha),Sn(no,void 0,t)});function io(t){return ft(t)?Qa(t,!0):Wa(t)}i(io,"keysIn");An.exports=so});var On=h((Zh,Cn)=>{var ao=require("util"),oo=wn(),co=lt()("tunnel-ssh-config"),_t=i(function(t,e){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t,this.extra=e},"ConfigError");ao.inherits(_t,Error);function uo(t){var e=process.env;if(oo(t||{},{username:e.TUNNELSSH_USER||e.USER||e.USERNAME||"root",port:22,host:null,srcPort:0,srcHost:"127.0.0.1",dstPort:null,dstHost:"127.0.0.1",localHost:"127.0.0.1",localPort:t.dstPort,agent:process.env.SSH_AUTH_SOCK}),!t.host)throw new _t("host not set");if(!t.dstPort)throw new _t("dstPort not set");return co("ssh-config",function(){var r=["password","privateKey"];return Object.keys(t).reduce(function(n,s){return r.indexOf(s)===-1?n[s]=t[s]:n[s]="***HIDDEN***",n},{})}()),t}i(uo,"createConfig");Cn.exports=uo});var In=h((ef,Nn)=>{var lo=require("net"),mt=lt()("tunnel-ssh"),po=gn().Client,ho=On(),fo=require("events"),_o=i(function(){},"noop");function mo(t,e){var r=new po;return e.on("close",r.end.bind(r)),r.on("ready",function(){mt("sshConnection:ready"),e.emit("sshConnection",r,e),r.forwardOut(t.srcHost,t.srcPort,t.dstHost,t.dstPort,function(n,s){if(n){e.emit("error",n),mt("Destination port:",n);return}mt("sshStream:create"),e.emit("sshStream",s),e.pipe(s).pipe(e)})}),r}i(mo,"bindSSHConnection");function go(t,e){return e.reduce(function(r,n){return delete r[n],r},Object.assign({},t))}i(go,"omit");function yo(t){var e,r=[],n=0;return e=lo.createServer(function(s){var a;n++,s.on("error",e.emit.bind(e,"error")),s.on("close",function(){n--,n===0&&(t.keepAlive||setTimeout(function(){n===0&&e.close()},2))}),e.emit("netConnection",s,e),a=mo(t,s),a.on("error",e.emit.bind(e,"error")),s.on("sshStream",function(o){o.on("error",function(){e.close()})}),r.push(a,s);try{a.connect(go(t,["localPort","localHost"]))}catch(o){e.emit("error",o)}}),e.on("close",function(){r.forEach(function(s){s.end()})}),e}i(yo,"createServer");function Eo(t,e){var r,n;e||(e=_o);try{n=ho(t),r=yo(n),r.listen(n.localPort,n.localHost,function(s){e(s,r)})}catch(s){r=new fo.EventEmitter,setImmediate(function(){e(s),r.emit("error",s)})}return r}i(Eo,"tunnel");Nn.exports=Eo});var yt=h(Rn=>{"use strict";Rn.parse=function(t,e){return new gt(t,e).parse()};var qe=class qe{constructor(e,r){this.source=e,this.transform=r||So,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new qe(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(qe,"ArrayParser");var gt=qe;function So(t){return t}i(So,"identity")});var Et=h((sf,xn)=>{var To=yt();xn.exports={create:i(function(t,e){return{parse:i(function(){return To.parse(t,e)},"parse")}},"create")}});var qn=h((of,Pn)=>{"use strict";var vo=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,bo=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Ao=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,wo=/^-?infinity$/;Pn.exports=i(function(e){if(wo.test(e))return Number(e.replace("i","I"));var r=vo.exec(e);if(!r)return Co(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=Ln(s));var a=parseInt(r[2],10)-1,o=r[3],c=parseInt(r[4],10),u=parseInt(r[5],10),l=parseInt(r[6],10),p=r[7];p=p?1e3*parseFloat(p):0;var f,_=Oo(e);return _!=null?(f=new Date(Date.UTC(s,a,o,c,u,l,p)),St(s)&&f.setUTCFullYear(s),_!==0&&f.setTime(f.getTime()-_)):(f=new Date(s,a,o,c,u,l,p),St(s)&&f.setFullYear(s)),f},"parseDate");function Co(t){var e=bo.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=Ln(r));var s=parseInt(e[2],10)-1,a=e[3],o=new Date(r,s,a);return St(r)&&o.setFullYear(r),o}}i(Co,"getDate");function Oo(t){if(t.endsWith("+00"))return 0;var e=Ao.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}i(Oo,"timeZoneOffset");function Ln(t){return-(t-1)}i(Ln,"bcYearToNegativeYear");function St(t){return t>=0&&t<100}i(St,"is0To99")});var Dn=h((uf,Mn)=>{Mn.exports=Io;var No=Object.prototype.hasOwnProperty;function Io(t){for(var e=1;e{"use strict";var Ro=Dn();Bn.exports=Y;function Y(t){if(!(this instanceof Y))return new Y(t);Ro(this,Qo(t))}i(Y,"PostgresInterval");var xo=["seconds","minutes","hours","days","months","years"];Y.prototype.toPostgres=function(){var t=xo.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var Lo={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Po=["years","months","days"],qo=["hours","minutes","seconds"];Y.prototype.toISOString=Y.prototype.toISO=function(){var t=Po.map(r,this).join(""),e=qo.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+Lo[n]}};var Tt="([+-]?\\d+)",Mo=Tt+"\\s+years?",Do=Tt+"\\s+mons?",Fo=Tt+"\\s+days?",Bo="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",ko=new RegExp([Mo,Do,Fo,Bo].map(function(t){return"("+t+")?"}).join("\\s*")),Fn={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Uo=["hours","minutes","seconds","milliseconds"];function Go(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(Go,"parseMilliseconds");function Qo(t){if(!t)return{};var e=ko.exec(t),r=e[8]==="-";return Object.keys(Fn).reduce(function(n,s){var a=Fn[s],o=e[a];return!o||(o=s==="milliseconds"?Go(o):parseInt(o,10),!o)||(r&&~Uo.indexOf(s)&&(o*=-1),n[s]=o),n},{})}i(Qo,"parse")});var Gn=h((ff,Un)=>{"use strict";Un.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",n=0;n{var me=yt(),ge=Et(),Me=qn(),Hn=kn(),jn=Gn();function De(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(De,"allowNull");function Wn(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(Wn,"parseBool");function Ho(t){return t?me.parse(t,Wn):null}i(Ho,"parseBoolArray");function jo(t){return parseInt(t,10)}i(jo,"parseBaseTenInt");function vt(t){return t?me.parse(t,De(jo)):null}i(vt,"parseIntegerArray");function Wo(t){return t?me.parse(t,De(function(e){return Vn(e).trim()})):null}i(Wo,"parseBigIntegerArray");var Vo=i(function(t){if(!t)return null;var e=ge.create(t,function(r){return r!==null&&(r=Ct(r)),r});return e.parse()},"parsePointArray"),bt=i(function(t){if(!t)return null;var e=ge.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),D=i(function(t){if(!t)return null;var e=ge.create(t);return e.parse()},"parseStringArray"),At=i(function(t){if(!t)return null;var e=ge.create(t,function(r){return r!==null&&(r=Me(r)),r});return e.parse()},"parseDateArray"),$o=i(function(t){if(!t)return null;var e=ge.create(t,function(r){return r!==null&&(r=Hn(r)),r});return e.parse()},"parseIntervalArray"),zo=i(function(t){return t?me.parse(t,De(jn)):null},"parseByteAArray"),wt=i(function(t){return parseInt(t,10)},"parseInteger"),Vn=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),Qn=i(function(t){return t?me.parse(t,De(JSON.parse)):null},"parseJsonArray"),Ct=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),Ko=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s{"use strict";var P=1e6;function Yo(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",a,o,c,u,l,p;{if(a=e%P,e=e/P>>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(u="",l=6-c.length,p=0;p{var Zo=Jn(),T=i(function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(S,C,R){return S*Math.pow(2,R)+C};var a=r>>3,o=i(function(S){return n?~S&255:S},"inv"),c=255,u=8-r%8;e>r%8);var l=0;r%8+e>=8&&(l=s(0,o(t[a])&c,u));for(var p=e+r>>3,f=a+1;f0&&(l=s(l,o(t[p])>>8-_,_)),l},"parseBits"),Xn=i(function(t,e,r){var n=Math.pow(2,r-1)-1,s=T(t,1),a=T(t,r,1);if(a===0)return 0;var o=1,c=i(function(l,p,f){l===0&&(l=1);for(var _=1;_<=f;_++)o/=2,(p&1<0&&(l+=o);return l},"parsePrecisionBits"),u=T(t,e,r+1,!1,c);return a==Math.pow(2,r+1)-1?u===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,a-n)*u},"parseFloatFromBits"),Xo=i(function(t){return T(t,1)==1?-1*(T(t,15,1,!0)+1):T(t,15,1)},"parseInt16"),Yn=i(function(t){return T(t,1)==1?-1*(T(t,31,1,!0)+1):T(t,31,1)},"parseInt32"),ec=i(function(t){return Xn(t,23,8)},"parseFloat32"),tc=i(function(t){return Xn(t,52,11)},"parseFloat64"),rc=i(function(t){var e=T(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,T(t,16,16)),n=0,s=[],a=T(t,16),o=0;o>3,(s+=p<<3)>>3),f;console.log("ERROR: ElementType not implemented: "+l)},"parseElement"),u=i(function(l,p){var f=[],_;if(l.length>1){var S=l.shift();for(_=0;_0},"parseBool"),ic=i(function(t){t(20,Zo),t(21,Xo),t(23,Yn),t(26,Yn),t(1700,rc),t(700,ec),t(701,tc),t(16,sc),t(1114,Zn.bind(null,!1)),t(1184,Zn.bind(null,!0)),t(1e3,ye),t(1007,ye),t(1016,ye),t(1008,ye),t(1009,ye),t(25,nc)},"init");es.exports={init:ic}});var ns=h((Tf,rs)=>{rs.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var Te=h(Se=>{var ac=zn(),oc=ts(),cc=Et(),uc=ns();Se.getTypeParser=lc;Se.setTypeParser=pc;Se.arrayParser=cc;Se.builtins=uc;var Ee={text:{},binary:{}};function ss(t){return String(t)}i(ss,"noParse");function lc(t,e){return e=e||"text",Ee[e]&&Ee[e][t]||ss}i(lc,"getTypeParser");function pc(t,e,r){typeof e=="function"&&(r=e,e="text"),Ee[e][t]=r}i(pc,"setTypeParser");ac.init(function(t,e){Ee.text[t]=e});oc.init(function(t,e){Ee.binary[t]=e})});var ve=h((Af,Ot)=>{"use strict";Ot.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Z=Te(),hc=Z.getTypeParser(20,"text"),fc=Z.getTypeParser(1016,"text");Ot.exports.__defineSetter__("parseInt8",function(t){Z.setTypeParser(20,"text",t?Z.getTypeParser(23,"text"):hc),Z.setTypeParser(1016,"text",t?Z.getTypeParser(1007,"text"):fc)})});var be=h((wf,as)=>{"use strict";var dc=ve();function _c(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(_c,"escapeElement");function is(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+is(t[r]);else if(ArrayBuffer.isView(t[r])){var n=t[r];if(!(n instanceof Buffer)){var s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=_c(Fe(t[r]));return e=e+"}",e}i(is,"arrayString");var Fe=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?dc.parseInputDatesAsUTC?yc(t):gc(t):Array.isArray(t)?is(t):typeof t=="object"?mc(t,e):t.toString()},"prepareValue");function mc(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Fe(t.toPostgres(Fe),e)}return JSON.stringify(t)}i(mc,"prepareObject");function I(t,e){for(t=""+t;t.length{"use strict";var Ae=require("crypto");function Nt(t){return Ae.createHash("md5").update(t,"utf-8").digest("hex")}i(Nt,"md5");function vc(t,e,r){var n=Nt(e+t),s=Nt(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(vc,"postgresMd5PasswordHash");function bc(t){return Ae.createHash("sha256").update(t).digest()}i(bc,"sha256");function Ac(t,e){return Ae.createHmac("sha256",t).update(e).digest()}i(Ac,"hmacSha256");async function wc(t,e,r){return Ae.pbkdf2Sync(t,e,r,32,"sha256")}i(wc,"deriveKey");os.exports={postgresMd5PasswordHash:vc,randomBytes:Ae.randomBytes,deriveKey:wc,sha256:bc,hmacSha256:Ac,md5:Nt}});var hs=h((If,ps)=>{var us=require("crypto");ps.exports={postgresMd5PasswordHash:Oc,randomBytes:Cc,deriveKey:Rc,sha256:Nc,hmacSha256:Ic,md5:It};var ls=us.webcrypto||globalThis.crypto,X=ls.subtle,Rt=new TextEncoder;function Cc(t){return ls.getRandomValues(Buffer.alloc(t))}i(Cc,"randomBytes");async function It(t){try{return us.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?Rt.encode(t):t,n=await X.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}i(It,"md5");async function Oc(t,e,r){var n=await It(e+t),s=await It(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(Oc,"postgresMd5PasswordHash");async function Nc(t){return await X.digest("SHA-256",t)}i(Nc,"sha256");async function Ic(t,e){let r=await X.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await X.sign("HMAC",r,Rt.encode(e))}i(Ic,"hmacSha256");async function Rc(t,e,r){let n=await X.importKey("raw",Rt.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await X.deriveBits(s,n,32*8,["deriveBits"])}i(Rc,"deriveKey")});var Lt=h((xf,xt)=>{"use strict";var xc=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;xc?xt.exports=cs():xt.exports=hs()});var ms=h((Lf,_s)=>{"use strict";var V=Lt();function Lc(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=V.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Lc,"startSession");async function Pc(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let n=Dc(r);if(n.nonce.startsWith(t.clientNonce)){if(n.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var s="n=*,r="+t.clientNonce,a="r="+n.nonce+",s="+n.salt+",i="+n.iteration,o="c=biws,r="+n.nonce,c=s+","+a+","+o,u=Buffer.from(n.salt,"base64"),l=await V.deriveKey(e,u,n.iteration),p=await V.hmacSha256(l,"Client Key"),f=await V.sha256(p),_=await V.hmacSha256(f,c),S=Bc(Buffer.from(p),Buffer.from(_)).toString("base64"),C=await V.hmacSha256(l,"Server Key"),R=await V.hmacSha256(C,c);t.message="SASLResponse",t.serverSignature=Buffer.from(R).toString("base64"),t.response=o+",p="+S}i(Pc,"continueSession");function qc(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=Fc(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i(qc,"finalizeSession");function Mc(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(Mc,"isPrintableChars");function fs(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(fs,"isBase64");function ds(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}i(ds,"parseAttributePairs");function Dc(t){let e=ds(t),r=e.get("r");if(r){if(!Mc(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!fs(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let a=parseInt(s,10);return{nonce:r,salt:n,iteration:a}}i(Dc,"parseServerFirstMessage");function Fc(t){let r=ds(t).get("v");if(r){if(!fs(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(Fc,"parseServerFinalMessage");function Bc(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}i(Bc,"xorBuffers");_s.exports={startSession:Lc,continueSession:Pc,finalizeSession:qc}});var Pt=h((qf,gs)=>{"use strict";var kc=Te();function Be(t){this._types=t||kc,this.text={},this.binary={}}i(Be,"TypeOverrides");Be.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Be.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Be.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};gs.exports=Be});var Es=h((Df,ys)=>{"use strict";function qt(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,n=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),n=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let s=n?"":r.hostname;e.host?s&&/^%2f/i.test(s)&&(r.pathname=s+r.pathname):e.host=decodeURIComponent(s),e.port||(e.port=r.port);let a=r.pathname.slice(1)||null;e.database=a?decodeURI(a):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let o=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=o.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=o.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=o.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(qt,"parse");ys.exports=qt;qt.parse=qt});var Ft=h((Bf,vs)=>{"use strict";var Uc=require("dns"),Ts=ve(),Ss=Es().parse,L=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||Ts[t]},"val"),Gc=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return Ts.ssl},"readSSLConfigFromEnvironment"),ee=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),F=i(function(t,e,r){var n=e[r];n!=null&&t.push(r+"="+ee(n))},"add"),Dt=class Dt{constructor(e){e=typeof e=="string"?Ss(e):e||{},e.connectionString&&(e=Object.assign({},e,Ss(e.connectionString))),this.user=L("user",e),this.database=L("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(L("port",e),10),this.host=L("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:L("password",e)}),this.binary=L("binary",e),this.options=L("options",e),this.ssl=typeof e.ssl>"u"?Gc():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=L("client_encoding",e),this.replication=L("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=L("application_name",e,"PGAPPNAME"),this.fallback_application_name=L("fallback_application_name",e,!1),this.statement_timeout=L("statement_timeout",e,!1),this.lock_timeout=L("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=L("idle_in_transaction_session_timeout",e,!1),this.query_timeout=L("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];F(r,this,"user"),F(r,this,"password"),F(r,this,"port"),F(r,this,"application_name"),F(r,this,"fallback_application_name"),F(r,this,"connect_timeout"),F(r,this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(F(r,n,"sslmode"),F(r,n,"sslca"),F(r,n,"sslkey"),F(r,n,"sslcert"),F(r,n,"sslrootcert"),this.database&&r.push("dbname="+ee(this.database)),this.replication&&r.push("replication="+ee(this.replication)),this.host&&r.push("host="+ee(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+ee(this.client_encoding)),Uc.lookup(this.host,function(s,a){return s?e(s,null):(r.push("hostaddr="+ee(a)),e(null,r.join(" ")))})}};i(Dt,"ConnectionParameters");var Mt=Dt;vs.exports=Mt});var ws=h((Uf,As)=>{"use strict";var Qc=Te(),bs=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,kt=class kt{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=bs.exec(e.text):r=bs.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),n=0,s=e.length;n{"use strict";var{EventEmitter:Hc}=require("events"),Cs=ws(),Os=be(),Gt=class Gt extends Hc{constructor(e,r,n){super(),e=Os.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new Cs(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new Cs(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:Os.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(Gt,"Query");var Ut=Gt;Ns.exports=Ut});var mr=h(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.NoticeMessage=d.DataRowMessage=d.CommandCompleteMessage=d.ReadyForQueryMessage=d.NotificationResponseMessage=d.BackendKeyDataMessage=d.AuthenticationMD5Password=d.ParameterStatusMessage=d.ParameterDescriptionMessage=d.RowDescriptionMessage=d.Field=d.CopyResponse=d.CopyDataMessage=d.DatabaseError=d.copyDone=d.emptyQuery=d.replicationStart=d.portalSuspended=d.noData=d.closeComplete=d.bindComplete=d.parseComplete=void 0;d.parseComplete={name:"parseComplete",length:5};d.bindComplete={name:"bindComplete",length:5};d.closeComplete={name:"closeComplete",length:5};d.noData={name:"noData",length:5};d.portalSuspended={name:"portalSuspended",length:5};d.replicationStart={name:"replicationStart",length:4};d.emptyQuery={name:"emptyQuery",length:4};d.copyDone={name:"copyDone",length:4};var rr=class rr extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};i(rr,"DatabaseError");var Qt=rr;d.DatabaseError=Qt;var nr=class nr{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(nr,"CopyDataMessage");var Ht=nr;d.CopyDataMessage=Ht;var sr=class sr{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};i(sr,"CopyResponse");var jt=sr;d.CopyResponse=jt;var ir=class ir{constructor(e,r,n,s,a,o,c){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=a,this.dataTypeModifier=o,this.format=c}};i(ir,"Field");var Wt=ir;d.Field=Wt;var ar=class ar{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(ar,"RowDescriptionMessage");var Vt=ar;d.RowDescriptionMessage=Vt;var or=class or{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(or,"ParameterDescriptionMessage");var $t=or;d.ParameterDescriptionMessage=$t;var cr=class cr{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};i(cr,"ParameterStatusMessage");var zt=cr;d.ParameterStatusMessage=zt;var ur=class ur{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(ur,"AuthenticationMD5Password");var Kt=ur;d.AuthenticationMD5Password=Kt;var lr=class lr{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};i(lr,"BackendKeyDataMessage");var Jt=lr;d.BackendKeyDataMessage=Jt;var pr=class pr{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};i(pr,"NotificationResponseMessage");var Yt=pr;d.NotificationResponseMessage=Yt;var hr=class hr{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(hr,"ReadyForQueryMessage");var Zt=hr;d.ReadyForQueryMessage=Zt;var fr=class fr{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(fr,"CommandCompleteMessage");var Xt=fr;d.CommandCompleteMessage=Xt;var dr=class dr{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(dr,"DataRowMessage");var er=dr;d.DataRowMessage=er;var _r=class _r{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(_r,"NoticeMessage");var tr=_r;d.NoticeMessage=tr});var Rs=h(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.Writer=void 0;var yr=class yr{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(s),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(yr,"Writer");var gr=yr;ke.Writer=gr});var Ls=h(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.serialize=void 0;var Er=Rs(),v=new Er.Writer,jc=i(t=>{v.addInt16(3).addInt16(0);for(let n of Object.keys(t))v.addCString(n).addCString(t[n]);v.addCString("client_encoding").addCString("UTF8");var e=v.addCString("").flush(),r=e.length+4;return new Er.Writer().addInt32(r).add(e).flush()},"startup"),Wc=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),Vc=i(t=>v.addCString(t).flush(112),"password"),$c=i(function(t,e){return v.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),v.flush(112)},"sendSASLInitialResponseMessage"),zc=i(function(t){return v.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),Kc=i(t=>v.addCString(t).flush(81),"query"),xs=[],Jc=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||xs;for(var n=r.length,s=v.addCString(e).addCString(t.text).addInt16(n),a=0;a{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||xs,a=s.length;return v.addCString(e).addCString(r),v.addInt16(a),Yc(s,t.valueMapper),v.addInt16(a),v.add(te.flush()),v.addInt16(n?1:0),v.flush(66)},"bind"),Xc=Buffer.from([69,0,0,0,9,0,0,0,0,0]),eu=i(t=>{if(!t||!t.portal&&!t.rows)return Xc;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,a=Buffer.allocUnsafe(1+s);return a[0]=69,a.writeInt32BE(s,1),a.write(e,5,"utf-8"),a[n+5]=0,a.writeUInt32BE(r,a.length-4),a},"execute"),tu=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),Sr=i((t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},"cstringMessage"),ru=v.addCString("P").flush(68),nu=v.addCString("S").flush(68),su=i(t=>t.name?Sr(68,`${t.type}${t.name||""}`):t.type==="P"?ru:nu,"describe"),iu=i(t=>{let e=`${t.type}${t.name||""}`;return Sr(67,e)},"close"),au=i(t=>v.add(t).flush(100),"copyData"),ou=i(t=>Sr(102,t),"copyFail"),Ue=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),cu=Ue(72),uu=Ue(83),lu=Ue(88),pu=Ue(99),hu={startup:jc,password:Vc,requestSsl:Wc,sendSASLInitialResponseMessage:$c,sendSCRAMClientFinalMessage:zc,query:Kc,parse:Jc,bind:Zc,execute:eu,describe:su,close:iu,flush:i(()=>cu,"flush"),sync:i(()=>uu,"sync"),end:i(()=>lu,"end"),copyData:au,copyDone:i(()=>pu,"copyDone"),copyFail:ou,cancel:tu};Ge.serialize=hu});var Ps=h(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.BufferReader=void 0;var fu=Buffer.allocUnsafe(0),vr=class vr{constructor(e=0){this.offset=e,this.buffer=fu,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(vr,"BufferReader");var Tr=vr;Qe.BufferReader=Tr});var Ds=h(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Parser=void 0;var b=mr(),du=Ps(),br=1,_u=4,qs=br+_u,Ms=Buffer.allocUnsafe(0),wr=class wr{constructor(e){if(this.buffer=Ms,this.bufferLength=0,this.bufferOffset=0,this.reader=new du.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+qs<=n;){let a=this.buffer[s],o=this.buffer.readUInt32BE(s+br),c=br+o;if(c+s<=n){let u=this.handlePacket(s+qs,a,o,this.buffer);r(u),s+=c}else break}s===n?(this.buffer=Ms,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let a=this.buffer.byteLength*2;for(;r>=a;)a*=2;s=Buffer.allocUnsafe(a)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){switch(r){case 50:return b.bindComplete;case 49:return b.parseComplete;case 51:return b.closeComplete;case 110:return b.noData;case 115:return b.portalSuspended;case 99:return b.copyDone;case 87:return b.replicationStart;case 73:return b.emptyQuery;case 68:return this.parseDataRowMessage(e,n,s);case 67:return this.parseCommandCompleteMessage(e,n,s);case 90:return this.parseReadyForQueryMessage(e,n,s);case 65:return this.parseNotificationMessage(e,n,s);case 82:return this.parseAuthenticationResponse(e,n,s);case 83:return this.parseParameterStatusMessage(e,n,s);case 75:return this.parseBackendKeyData(e,n,s);case 69:return this.parseErrorMessage(e,n,s,"error");case 78:return this.parseErrorMessage(e,n,s,"notice");case 84:return this.parseRowDescriptionMessage(e,n,s);case 116:return this.parseParameterDescriptionMessage(e,n,s);case 71:return this.parseCopyInMessage(e,n,s);case 72:return this.parseCopyOutMessage(e,n,s);case 100:return this.parseCopyData(e,n,s);default:return new b.DatabaseError("received invalid response: "+r.toString(16),n,"error")}}parseReadyForQueryMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.string(1);return new b.ReadyForQueryMessage(r,s)}parseCommandCompleteMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.cstring();return new b.CommandCompleteMessage(r,s)}parseCopyData(e,r,n){let s=n.slice(e,e+(r-4));return new b.CopyDataMessage(r,s)}parseCopyInMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyInResponse")}parseCopyOutMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyOutResponse")}parseCopyMessage(e,r,n,s){this.reader.setBuffer(e,n);let a=this.reader.byte()!==0,o=this.reader.int16(),c=new b.CopyResponse(r,s,a,o);for(let u=0;u{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.DatabaseError=Q.serialize=Q.parse=void 0;var mu=mr();Object.defineProperty(Q,"DatabaseError",{enumerable:!0,get:i(function(){return mu.DatabaseError},"get")});var gu=Ls();Object.defineProperty(Q,"serialize",{enumerable:!0,get:i(function(){return gu.serialize},"get")});var yu=Ds();function Eu(t,e){let r=new yu.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}i(Eu,"parse");Q.parse=Eu});var Fs={};la(Fs,{default:()=>Su});var Su,Bs=ua(()=>{Su={}});var ks=h((rd,Or)=>{Or.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:n}=(Bs(),ha(Fs));return new n(e)}},"getStream");Or.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var Rr=h((id,Us)=>{"use strict";var sd=require("net"),Tu=require("events").EventEmitter,{parse:vu,serialize:N}=Cr(),{getStream:bu,getSecureStream:Au}=ks(),wu=N.flush(),Cu=N.sync(),Ou=N.end(),Ir=class Ir extends Tu{constructor(e){super(),e=e||{},this.stream=e.stream||bu(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=i(function(a){n._ending&&(a.code==="ECONNRESET"||a.code==="EPIPE")||n.emit("error",a)},"reportStreamError");if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(a){var o=a.toString("utf8");switch(o){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:n.stream};n.ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key));var u=require("net");u.isIP&&u.isIP(r)===0&&(c.servername=r);try{n.stream=Au(c)}catch(l){return n.emit("error",l)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){vu(e,r=>{var n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(N.requestSsl())}startup(e){this.stream.write(N.startup(e))}cancel(e,r){this._send(N.cancel(e,r))}password(e){this._send(N.password(e))}sendSASLInitialResponseMessage(e,r){this._send(N.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(N.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(N.query(e))}parse(e){this._send(N.parse(e))}bind(e){this._send(N.bind(e))}execute(e){this._send(N.execute(e))}flush(){this.stream.writable&&this.stream.write(wu)}sync(){this._ending=!0,this._send(Cu)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(Ou,()=>{this.stream.end()})}close(e){this._send(N.close(e))}describe(e){this._send(N.describe(e))}sendCopyFromChunk(e){this._send(N.copyData(e))}endCopyFrom(){this._send(N.copyDone())}sendCopyFail(e){this._send(N.copyFail(e))}};i(Ir,"Connection");var Nr=Ir;Us.exports=Nr});var js=h((od,Hs)=>{"use strict";var{Transform:Nu}=require("stream"),{StringDecoder:Iu}=require("string_decoder"),H=Symbol("last"),je=Symbol("decoder");function Ru(t,e,r){let n;if(this.overflow){if(n=this[je].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[H]+=this[je].write(t),n=this[H].split(this.matcher);this[H]=n.pop();for(let s=0;sthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(Ru,"transform");function xu(t){if(this[H]+=this[je].end(),this[H])try{Qs(this,this.mapper(this[H]))}catch(e){return t(e)}t()}i(xu,"flush");function Qs(t,e){e!==void 0&&t.push(e)}i(Qs,"push");function Gs(t){return t}i(Gs,"noop");function Lu(t,e,r){switch(t=t||/\r?\n/,e=e||Gs,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=Gs)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Ru,r.flush=xu,r.readableObjectMode=!0;let n=new Nu(r);return n[H]="",n[je]=new Iu("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,a){this._writableState.errorEmitted=!1,a(s)},n}i(Lu,"split");Hs.exports=Lu});var $s=h((ud,U)=>{"use strict";var Ws=require("path"),Pu=require("stream").Stream,qu=js(),Vs=require("util"),Mu=5432,We=process.platform==="win32",we=process.stderr,Du=56,Fu=7,Bu=61440,ku=32768;function Uu(t){return(t&Bu)==ku}i(Uu,"isRegFile");var re=["host","port","database","user","password"],xr=re.length,Gu=re[xr-1];function Lr(){var t=we instanceof Pu&&we.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` -`);we.write(Vs.format.apply(Vs,e))}}i(Lr,"warn");Object.defineProperty(U.exports,"isWin",{get:i(function(){return We},"get"),set:i(function(t){We=t},"set")});U.exports.warnTo=function(t){var e=we;return we=t,e};U.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(We?Ws.join(e.APPDATA||"./","postgresql","pgpass.conf"):Ws.join(e.HOME||"./",".pgpass"));return r};U.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:We?!0:(e=e||"",Uu(t.mode)?t.mode&(Du|Fu)?(Lr('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Lr('WARNING: password file "%s" is not a plain file',e),!1))};var Qu=U.exports.match=function(t,e){return re.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||Mu)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};U.exports.getPassword=function(t,e,r){var n,s=e.pipe(qu());function a(u){var l=Hu(u);l&&ju(l)&&Qu(t,l)&&(n=l[Gu],s.end())}i(a,"onLine");var o=i(function(){e.destroy(),r(n)},"onEnd"),c=i(function(u){e.destroy(),Lr("WARNING: error on reading file: %s",u),r(void 0)},"onErr");e.on("error",c),s.on("data",a).on("end",o).on("error",c)};var Hu=U.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,a=0,o={},c=!1,u=i(function(p,f,_){var S=t.substring(f,_);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(S=S.replace(/\\([:\\])/g,"$1")),o[re[p]]=S},"addToObj"),l=0;l=0&&e==":"&&r!=="\\"&&(u(n,s,l+1),s=l+2,n+=1)}return o=Object.keys(o).length===xr?o:null,o},ju=U.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r{"use strict";var pd=require("path"),zs=require("fs"),Ve=$s();Pr.exports=function(t,e){var r=Ve.getFileName();zs.stat(r,function(n,s){if(n||!Ve.usePgPass(s,r))return e(void 0);var a=zs.createReadStream(r);Ve.getPassword(t,a,e)})};Pr.exports.warnTo=Ve.warnTo});var Xs=h((fd,Zs)=>{"use strict";var Wu=require("events").EventEmitter,Js=be(),qr=ms(),Vu=Pt(),$u=Ft(),Ys=Is(),zu=ve(),Ku=Rr(),Ju=Lt(),Mr=class Mr extends Wu{constructor(e){super(),this.connectionParameters=new $u(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new Vu(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new Ku({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||zu.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(n=>{process.nextTick(()=>{n.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{r.emit("error",n)});else if(this.password!==null)e();else try{Ks()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await Ju.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=qr.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await qr.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{qr.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Js.escapeIdentifier(e)}escapeLiteral(e){return Js.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,n){var s,a,o,c,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,a=s=e,typeof r=="function"&&(s.callback=s.callback||r)):(o=this.connectionParameters.query_timeout,s=new Ys(e,r,n),s.callback||(a=new this._Promise((l,p)=>{s.callback=(f,_)=>f?p(f):l(_)}).catch(l=>{throw Error.captureStackTrace(l),l}))),o&&(u=s.callback,c=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{s.handleError(l,this.connection)}),u(l),s.callback=()=>{};var p=this.queryQueue.indexOf(s);p>-1&&this.queryQueue.splice(p,1),this._pulseQueryQueue()},o),s.callback=(l,p)=>{clearTimeout(c),u(l,p)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),a):(this.queryQueue.push(s),this._pulseQueryQueue(),a):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),a)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(Mr,"Client");var $e=Mr;$e.Query=Ys;Zs.exports=$e});var ni=h((_d,ri)=>{"use strict";var Yu=require("events").EventEmitter,ei=i(function(){},"NOOP"),ti=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),Br=class Br{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}};i(Br,"IdleItem");var Dr=Br,kr=class kr{constructor(e){this.callback=e}};i(kr,"PendingItem");var ne=kr;function Zu(){throw new Error("Release called on client which has already been released to the pool.")}i(Zu,"throwOnDoubleRelease");function ze(t,e){if(e)return{callback:e,result:void 0};let r,n,s=i(function(o,c){o?r(o):n(c)},"cb"),a=new t(function(o,c){n=o,r=c}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:a}}i(ze,"promisify");function Xu(t,e){return i(function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)},"idleListener")}i(Xu,"makeIdleListener");var Ur=class Ur extends Yu{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||Gr().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=ti(this._idle,n=>n.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=ze(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ne(r.callback)),n;let s=i((c,u,l)=>{clearTimeout(o),r.callback(c,u,l)},"queueCallback"),a=new ne(s),o=setTimeout(()=>{ti(this._pendingQueue,c=>c.callback===s),a.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(a),n}return this.newClient(new ne(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=Xu(this,r);this.log("checking client timeout");let s,a=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),a=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(s&&clearTimeout(s),r.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(c=>c!==r),a&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,ei);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(l=>l.client===r)!==-1&&this._acquireClient(r,new ne((l,p,f)=>f()),n,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,n,!0)}})}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,a=>{if(a)return e.release(a),r.callback(a,void 0,ei);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&Zu(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let a;this.options.idleTimeoutMillis&&(a=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&a.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Dr(e,r,a)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let a=ze(this.Promise,e);return setImmediate(function(){return a.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),a.result}typeof r=="function"&&(n=r,r=void 0);let s=ze(this.Promise,n);return n=s.callback,this.connect((a,o)=>{if(a)return n(a);let c=!1,u=i(l=>{c||(c=!0,o.release(l),n(l))},"onError");o.once("error",u),this.log("dispatching query");try{o.query(e,r,(l,p)=>{if(this.log("query dispatched"),o.removeListener("error",u),!c)return c=!0,o.release(l),l?n(l):n(void 0,p)})}catch(l){return o.release(l),n(l)}}),s.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let r=ze(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(Ur,"Pool");var Fr=Ur;ri.exports=Fr});var ai=h((gd,ii)=>{"use strict";var si=require("events").EventEmitter,el=require("util"),Qr=be(),se=ii.exports=function(t,e,r){si.call(this),t=Qr.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};el.inherits(se,si);var tl={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};se.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var n=tl[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};se.prototype.then=function(t,e){return this._getPromise().then(t,e)};se.prototype.catch=function(t){return this._getPromise().catch(t)};se.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};se.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(a,o,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),a)return e.handleError(a);e._emitRowEvents&&(c.length>1?o.forEach((u,l)=>{u.forEach(p=>{e.emit("row",p,c[l])})}):o.forEach(function(u){e.emit("row",u,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var n=(this.values||[]).map(Qr.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let a=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(a)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(a){return a?r(a):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let a=new Error("Query values must be an array");return r(a)}var s=this.values.map(Qr.prepareValue);t.native.query(this.text,s,r)}else t.native.query(this.text,r)}});var pi=h((Ed,li)=>{"use strict";var oi;try{oi=require("pg-native")}catch(t){throw t}var rl=Pt(),ci=require("events").EventEmitter,nl=require("util"),sl=Ft(),ui=ai(),q=li.exports=function(t){ci.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new rl(t.types),this.native=new oi({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new sl(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};q.Query=ui;nl.inherits(q,ci);q.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};q.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(a){e._queryable=!1,e._errorAllQueries(a),e.emit("error",a)}),e.native.on("notification",function(a){e.emit("notification",{channel:a.relname,payload:a.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};q.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e()})})};q.prototype.query=function(t,e,r){var n,s,a,o,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")a=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(a=this.connectionParameters.query_timeout,n=new ui(t,e,r),!n.callback){let u,l;s=new this._Promise((p,f)=>{u=p,l=f}).catch(p=>{throw Error.captureStackTrace(p),p}),n.callback=(p,f)=>p?l(p):u(f)}return a&&(c=n.callback,o=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),c(u),n.callback=()=>{};var l=this._queryQueue.indexOf(n);l>-1&&this._queryQueue.splice(l,1),this._pulseQueryQueue()},a),n.callback=(u,l)=>{clearTimeout(o),c(u,l)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};q.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(n,s){t=i(a=>a?s(a):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};q.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};q.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};q.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};q.prototype.ref=function(){};q.prototype.unref=function(){};q.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};q.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var Hr=h((Td,hi)=>{"use strict";hi.exports=pi()});var Gr=h((vd,Ce)=>{"use strict";var il=Xs(),al=ve(),ol=Rr(),cl=ni(),{DatabaseError:ul}=Cr(),{escapeIdentifier:ll,escapeLiteral:pl}=be(),hl=i(t=>{var e;return e=class extends cl{constructor(n){super(n,t)}},i(e,"BoundPool"),e},"poolFactory"),jr=i(function(t){this.defaults=al,this.Client=t,this.Query=this.Client.Query,this.Pool=hl(this.Client),this._pools=[],this.Connection=ol,this.types=Te(),this.DatabaseError=ul,this.escapeIdentifier=ll,this.escapeLiteral=pl},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?Ce.exports=new jr(Hr()):(Ce.exports=new jr(il),Object.defineProperty(Ce.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new jr(Hr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Ce.exports,"native",{value:t}),t}}))});var di=h((Ad,fi)=>{var $=require("fs"),fl=In(),dl=Gr(),_l="The server does not support SSL connections",ml="28000",gl=i(t=>{let e={username:t.ssh_user,host:t.ssh_host,port:t.ssh_port,dstHost:t.host,dstPort:t.port,localHost:"127.0.0.1",localPort:t.port,keepAlive:!0};return t.ssh_method==="privateKey"?Object.assign({},e,{privateKey:$.readFileSync(t.ssh_key_file),passphrase:t.ssh_key_passphrase}):Object.assign({},e,{password:t.ssh_password})},"getSshConfig"),yl=i(t=>new Promise((e,r)=>{fl(gl(t),(n,s)=>{n?r(n):e({tunnel:s,info:Object.assign({},t,{host:"127.0.0.1"})})})}),"connectViaSsh"),El=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let n={checkServerIdentity(s,a){e.info("Certificate",{hostname:s,cert:{subject:a.subject,issuer:a.issuer,valid_from:a.valid_from,valid_to:a.valid_to}})}};return $.existsSync(t.certAuthority)&&(n.ca=$.readFileSync(t.certAuthority).toString()),$.existsSync(t.clientCert)&&(n.cert=$.readFileSync(t.clientCert).toString()),$.existsSync(t.clientPrivateKey)&&(n.key=$.readFileSync(t.clientPrivateKey).toString()),n},"getSslOptions"),Sl=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),Tl=i(async(t,e)=>{let r=null;if(t.ssh){let{info:a,tunnel:o}=await yl(t);r=o,t=a}t=Object.assign({},t,{sslType:Sl(t.sslType)});let n={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:El(t,e),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await Wr(n,e),sshTunnel:r}},"createClient"),vl=i((t,e,r)=>{var n;if(r.message===_l&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),Wr({...t,isRetry:!0,ssl:!1},e);if(((n=r.code)==null?void 0:n.toString())===ml&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),Wr({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),Wr=i((t,e)=>{let r=new dl.Pool(t);return r.connect().then(n=>(n.release(),r)).catch(async n=>{if(await r.end(),t.isRetry)throw n;return vl(t,e,n)})},"createConnectionPool");fi.exports={createClient:Tl}});var $r=h((Cd,gi)=>{var Vr=i(t=>` +"use strict";var be=Object.defineProperty;var di=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var mi=Object.prototype.hasOwnProperty;var i=(t,e)=>be(t,"name",{value:e,configurable:!0});var gi=(t,e)=>()=>(t&&(e=t(t=0)),e);var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),yi=(t,e)=>{for(var r in e)be(t,r,{get:e[r],enumerable:!0})},Ei=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fi(e))!mi.call(t,n)&&n!==r&&be(t,n,{get:()=>e[n],enumerable:!(s=di(e,n))||s.enumerable});return t};var Si=t=>Ei(be({},"__esModule",{value:!0}),t);var Fr=_((Ql,Dr)=>{"use strict";var Ti=i(({title:t,logger:e,hiddenKeys:r})=>({info(s,n={}){e.log("info",{message:s,...n},t,r)},progress(s,n="",a=""){e.progress({message:s,containerName:n,entityName:a})},error(s){e.log("error",bi(s),t)}}),"createLogger"),bi=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");Dr.exports={createLogger:Ti}});var Ke=_(Br=>{"use strict";Br.parse=function(t,e){return new $e(t,e).parse()};var Ae=class Ae{constructor(e,r){this.source=e,this.transform=r||Ai,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,s,n;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!n)this.dimension++,this.dimension>1&&(s=new Ae(this.source.substr(this.position-1),this.transform),this.entries.push(s.parse(!0)),this.position+=s.position-2);else if(r.value==="}"&&!n){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(n&&this.newEntry(!0),n=!n):r.value===","&&!n?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(Ae,"ArrayParser");var $e=Ae;function Ai(t){return t}i(Ai,"identity")});var Je=_((Vl,kr)=>{var vi=Ke();kr.exports={create:function(t,e){return{parse:function(){return vi.parse(t,e)}}}}});var Qr=_((zl,Gr)=>{"use strict";var wi=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,Ni=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Ci=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Ri=/^-?infinity$/;Gr.exports=i(function(e){if(Ri.test(e))return Number(e.replace("i","I"));var r=wi.exec(e);if(!r)return Oi(e)||null;var s=!!r[8],n=parseInt(r[1],10);s&&(n=Ur(n));var a=parseInt(r[2],10)-1,o=r[3],c=parseInt(r[4],10),l=parseInt(r[5],10),u=parseInt(r[6],10),p=r[7];p=p?1e3*parseFloat(p):0;var h,d=Ii(e);return d!=null?(h=new Date(Date.UTC(n,a,o,c,l,u,p)),Ye(n)&&h.setUTCFullYear(n),d!==0&&h.setTime(h.getTime()-d)):(h=new Date(n,a,o,c,l,u,p),Ye(n)&&h.setFullYear(n)),h},"parseDate");function Oi(t){var e=Ni.exec(t);if(e){var r=parseInt(e[1],10),s=!!e[4];s&&(r=Ur(r));var n=parseInt(e[2],10)-1,a=e[3],o=new Date(r,n,a);return Ye(r)&&o.setFullYear(r),o}}i(Oi,"getDate");function Ii(t){if(t.endsWith("+00"))return 0;var e=Ci.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var s=r==="-"?-1:1,n=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return n*s*1e3}}i(Ii,"timeZoneOffset");function Ur(t){return-(t-1)}i(Ur,"bcYearToNegativeYear");function Ye(t){return t>=0&&t<100}i(Ye,"is0To99")});var jr=_((Kl,Hr)=>{Hr.exports=Li;var xi=Object.prototype.hasOwnProperty;function Li(t){for(var e=1;e{"use strict";var Pi=jr();Vr.exports=V;function V(t){if(!(this instanceof V))return new V(t);Pi(this,Wi(t))}i(V,"PostgresInterval");var qi=["seconds","minutes","hours","days","months","years"];V.prototype.toPostgres=function(){var t=qi.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var Mi={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Di=["years","months","days"],Fi=["hours","minutes","seconds"];V.prototype.toISOString=V.prototype.toISO=function(){var t=Di.map(r,this).join(""),e=Fi.map(r,this).join("");return"P"+t+"T"+e;function r(s){var n=this[s]||0;return s==="seconds"&&this.milliseconds&&(n=(n+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),n+Mi[s]}};var Ze="([+-]?\\d+)",Bi=Ze+"\\s+years?",ki=Ze+"\\s+mons?",Ui=Ze+"\\s+days?",Gi="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Qi=new RegExp([Bi,ki,Ui,Gi].map(function(t){return"("+t+")?"}).join("\\s*")),Wr={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Hi=["hours","minutes","seconds","milliseconds"];function ji(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(ji,"parseMilliseconds");function Wi(t){if(!t)return{};var e=Qi.exec(t),r=e[8]==="-";return Object.keys(Wr).reduce(function(s,n){var a=Wr[n],o=e[a];return!o||(o=n==="milliseconds"?ji(o):parseInt(o,10),!o)||(r&&~Hi.indexOf(n)&&(o*=-1),s[n]=o),s},{})}i(Wi,"parse")});var Kr=_((Xl,$r)=>{"use strict";$r.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",s=0;s{var ae=Ke(),oe=Je(),ve=Qr(),Yr=zr(),Zr=Kr();function we(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(we,"allowNull");function Xr(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(Xr,"parseBool");function Vi(t){return t?ae.parse(t,Xr):null}i(Vi,"parseBoolArray");function zi(t){return parseInt(t,10)}i(zi,"parseBaseTenInt");function Xe(t){return t?ae.parse(t,we(zi)):null}i(Xe,"parseIntegerArray");function $i(t){return t?ae.parse(t,we(function(e){return es(e).trim()})):null}i($i,"parseBigIntegerArray");var Ki=i(function(t){if(!t)return null;var e=oe.create(t,function(r){return r!==null&&(r=st(r)),r});return e.parse()},"parsePointArray"),et=i(function(t){if(!t)return null;var e=oe.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),P=i(function(t){if(!t)return null;var e=oe.create(t);return e.parse()},"parseStringArray"),tt=i(function(t){if(!t)return null;var e=oe.create(t,function(r){return r!==null&&(r=ve(r)),r});return e.parse()},"parseDateArray"),Ji=i(function(t){if(!t)return null;var e=oe.create(t,function(r){return r!==null&&(r=Yr(r)),r});return e.parse()},"parseIntervalArray"),Yi=i(function(t){return t?ae.parse(t,we(Zr)):null},"parseByteAArray"),rt=i(function(t){return parseInt(t,10)},"parseInteger"),es=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),Jr=i(function(t){return t?ae.parse(t,we(JSON.parse)):null},"parseJsonArray"),st=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),Zi=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",s=!1,n=2;n{"use strict";var I=1e6;function ea(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),s="";e<0&&(e=~e+(r===0),r=~r+1>>>0,s="-");var n="",a,o,c,l,u,p;{if(a=e%I,e=e/I>>>0,o=4294967296*a+r,r=o/I>>>0,c=""+(o-I*r),r===0&&e===0)return s+c+n;for(l="",u=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/I>>>0,c=""+(o-I*r),r===0&&e===0)return s+c+n;for(l="",u=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/I>>>0,c=""+(o-I*r),r===0&&e===0)return s+c+n;for(l="",u=6-c.length,p=0;p{var ta=ns(),S=i(function(t,e,r,s,n){r=r||0,s=s||!1,n=n||function(E,w,O){return E*Math.pow(2,O)+w};var a=r>>3,o=i(function(E){return s?~E&255:E},"inv"),c=255,l=8-r%8;e>r%8);var u=0;r%8+e>=8&&(u=n(0,o(t[a])&c,l));for(var p=e+r>>3,h=a+1;h0&&(u=n(u,o(t[p])>>8-d,d)),u},"parseBits"),os=i(function(t,e,r){var s=Math.pow(2,r-1)-1,n=S(t,1),a=S(t,r,1);if(a===0)return 0;var o=1,c=i(function(u,p,h){u===0&&(u=1);for(var d=1;d<=h;d++)o/=2,(p&1<0&&(u+=o);return u},"parsePrecisionBits"),l=S(t,e,r+1,!1,c);return a==Math.pow(2,r+1)-1?l===0?n===0?1/0:-1/0:NaN:(n===0?1:-1)*Math.pow(2,a-s)*l},"parseFloatFromBits"),ra=i(function(t){return S(t,1)==1?-1*(S(t,15,1,!0)+1):S(t,15,1)},"parseInt16"),is=i(function(t){return S(t,1)==1?-1*(S(t,31,1,!0)+1):S(t,31,1)},"parseInt32"),sa=i(function(t){return os(t,23,8)},"parseFloat32"),na=i(function(t){return os(t,52,11)},"parseFloat64"),ia=i(function(t){var e=S(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,S(t,16,16)),s=0,n=[],a=S(t,16),o=0;o>3,(n+=p<<3)>>3),h;console.log("ERROR: ElementType not implemented: "+u)},"parseElement"),l=i(function(u,p){var h=[],d;if(u.length>1){var E=u.shift();for(d=0;d0},"parseBool"),ca=i(function(t){t(20,ta),t(21,ra),t(23,is),t(26,is),t(1700,ia),t(700,sa),t(701,na),t(16,oa),t(1114,as.bind(null,!1)),t(1184,as.bind(null,!0)),t(1e3,ce),t(1007,ce),t(1016,ce),t(1008,ce),t(1009,ce),t(25,aa)},"init");cs.exports={init:ca}});var ps=_((op,ls)=>{ls.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var pe=_(le=>{var ua=rs(),la=us(),pa=Je(),ha=ps();le.getTypeParser=_a;le.setTypeParser=da;le.arrayParser=pa;le.builtins=ha;var ue={text:{},binary:{}};function hs(t){return String(t)}i(hs,"noParse");function _a(t,e){return e=e||"text",ue[e]&&ue[e][t]||hs}i(_a,"getTypeParser");function da(t,e,r){typeof e=="function"&&(r=e,e="text"),ue[e][t]=r}i(da,"setTypeParser");ua.init(function(t,e){ue.text[t]=e});la.init(function(t,e){ue.binary[t]=e})});var he=_((lp,nt)=>{"use strict";nt.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var z=pe(),fa=z.getTypeParser(20,"text"),ma=z.getTypeParser(1016,"text");nt.exports.__defineSetter__("parseInt8",function(t){z.setTypeParser(20,"text",t?z.getTypeParser(23,"text"):fa),z.setTypeParser(1016,"text",t?z.getTypeParser(1007,"text"):ma)})});var _e=_((pp,ds)=>{"use strict";var ga=he();function ya(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(ya,"escapeElement");function _s(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+_s(t[r]);else if(ArrayBuffer.isView(t[r])){var s=t[r];if(!(s instanceof Buffer)){var n=Buffer.from(s.buffer,s.byteOffset,s.byteLength);n.length===s.byteLength?s=n:s=n.slice(s.byteOffset,s.byteOffset+s.byteLength)}e+="\\\\x"+s.toString("hex")}else e+=ya(Ne(t[r]));return e=e+"}",e}i(_s,"arrayString");var Ne=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?ga.parseInputDatesAsUTC?Ta(t):Sa(t):Array.isArray(t)?_s(t):typeof t=="object"?Ea(t,e):t.toString()},"prepareValue");function Ea(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Ne(t.toPostgres(Ne),e)}return JSON.stringify(t)}i(Ea,"prepareObject");function C(t,e){for(t=""+t;t.length{"use strict";var de=require("crypto");function it(t){return de.createHash("md5").update(t,"utf-8").digest("hex")}i(it,"md5");function wa(t,e,r){var s=it(e+t),n=it(Buffer.concat([Buffer.from(s),r]));return"md5"+n}i(wa,"postgresMd5PasswordHash");function Na(t){return de.createHash("sha256").update(t).digest()}i(Na,"sha256");function Ca(t,e){return de.createHmac("sha256",t).update(e).digest()}i(Ca,"hmacSha256");async function Ra(t,e,r){return de.pbkdf2Sync(t,e,r,32,"sha256")}i(Ra,"deriveKey");fs.exports={postgresMd5PasswordHash:wa,randomBytes:de.randomBytes,deriveKey:Ra,sha256:Na,hmacSha256:Ca,md5:it}});var Ss=_((fp,Es)=>{var gs=require("crypto");Es.exports={postgresMd5PasswordHash:Ia,randomBytes:Oa,deriveKey:Pa,sha256:xa,hmacSha256:La,md5:at};var ys=gs.webcrypto||globalThis.crypto,$=ys.subtle,ot=new TextEncoder;function Oa(t){return ys.getRandomValues(Buffer.alloc(t))}i(Oa,"randomBytes");async function at(t){try{return gs.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?ot.encode(t):t,s=await $.digest("MD5",r);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}}i(at,"md5");async function Ia(t,e,r){var s=await at(e+t),n=await at(Buffer.concat([Buffer.from(s),r]));return"md5"+n}i(Ia,"postgresMd5PasswordHash");async function xa(t){return await $.digest("SHA-256",t)}i(xa,"sha256");async function La(t,e){let r=await $.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await $.sign("HMAC",r,ot.encode(e))}i(La,"hmacSha256");async function Pa(t,e,r){let s=await $.importKey("raw",ot.encode(t),"PBKDF2",!1,["deriveBits"]),n={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await $.deriveBits(n,s,32*8,["deriveBits"])}i(Pa,"deriveKey")});var ut=_((gp,ct)=>{"use strict";var qa=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;qa?ct.exports=ms():ct.exports=Ss()});var vs=_((yp,As)=>{"use strict";var H=ut();function Ma(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=H.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Ma,"startSession");async function Da(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let s=ka(r);if(s.nonce.startsWith(t.clientNonce)){if(s.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var n="n=*,r="+t.clientNonce,a="r="+s.nonce+",s="+s.salt+",i="+s.iteration,o="c=biws,r="+s.nonce,c=n+","+a+","+o,l=Buffer.from(s.salt,"base64"),u=await H.deriveKey(e,l,s.iteration),p=await H.hmacSha256(u,"Client Key"),h=await H.sha256(p),d=await H.hmacSha256(h,c),E=Ga(Buffer.from(p),Buffer.from(d)).toString("base64"),w=await H.hmacSha256(u,"Server Key"),O=await H.hmacSha256(w,c);t.message="SASLResponse",t.serverSignature=Buffer.from(O).toString("base64"),t.response=o+",p="+E}i(Da,"continueSession");function Fa(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=Ua(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i(Fa,"finalizeSession");function Ba(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(Ba,"isPrintableChars");function Ts(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(Ts,"isBase64");function bs(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],s=e.substring(2);return[r,s]}))}i(bs,"parseAttributePairs");function ka(t){let e=bs(t),r=e.get("r");if(r){if(!Ba(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let s=e.get("s");if(s){if(!Ts(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let n=e.get("i");if(n){if(!/^[1-9][0-9]*$/.test(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let a=parseInt(n,10);return{nonce:r,salt:s,iteration:a}}i(ka,"parseServerFirstMessage");function Ua(t){let r=bs(t).get("v");if(r){if(!Ts(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(Ua,"parseServerFinalMessage");function Ga(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,s)=>t[s]^e[s]))}i(Ga,"xorBuffers");As.exports={startSession:Ma,continueSession:Da,finalizeSession:Fa}});var lt=_((Sp,ws)=>{"use strict";var Qa=pe();function Ce(t){this._types=t||Qa,this.text={},this.binary={}}i(Ce,"TypeOverrides");Ce.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Ce.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Ce.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};ws.exports=Ce});var Cs=_((bp,Ns)=>{"use strict";function pt(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,s=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),s=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let n=s?"":r.hostname;e.host?n&&/^%2f/i.test(n)&&(r.pathname=n+r.pathname):e.host=decodeURIComponent(n),e.port||(e.port=r.port);let a=r.pathname.slice(1)||null;e.database=a?decodeURI(a):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let o=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=o.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=o.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=o.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(pt,"parse");Ns.exports=pt;pt.parse=pt});var dt=_((vp,Is)=>{"use strict";var Ha=require("dns"),Os=he(),Rs=Cs().parse,R=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||Os[t]},"val"),ja=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return Os.ssl},"readSSLConfigFromEnvironment"),K=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),q=i(function(t,e,r){var s=e[r];s!=null&&t.push(r+"="+K(s))},"add"),_t=class _t{constructor(e){e=typeof e=="string"?Rs(e):e||{},e.connectionString&&(e=Object.assign({},e,Rs(e.connectionString))),this.user=R("user",e),this.database=R("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(R("port",e),10),this.host=R("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:R("password",e)}),this.binary=R("binary",e),this.options=R("options",e),this.ssl=typeof e.ssl>"u"?ja():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=R("client_encoding",e),this.replication=R("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=R("application_name",e,"PGAPPNAME"),this.fallback_application_name=R("fallback_application_name",e,!1),this.statement_timeout=R("statement_timeout",e,!1),this.lock_timeout=R("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=R("idle_in_transaction_session_timeout",e,!1),this.query_timeout=R("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];q(r,this,"user"),q(r,this,"password"),q(r,this,"port"),q(r,this,"application_name"),q(r,this,"fallback_application_name"),q(r,this,"connect_timeout"),q(r,this,"options");var s=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(q(r,s,"sslmode"),q(r,s,"sslca"),q(r,s,"sslkey"),q(r,s,"sslcert"),q(r,s,"sslrootcert"),this.database&&r.push("dbname="+K(this.database)),this.replication&&r.push("replication="+K(this.replication)),this.host&&r.push("host="+K(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+K(this.client_encoding)),Ha.lookup(this.host,function(n,a){return n?e(n,null):(r.push("hostaddr="+K(a)),e(null,r.join(" ")))})}};i(_t,"ConnectionParameters");var ht=_t;Is.exports=ht});var Ps=_((Np,Ls)=>{"use strict";var Wa=pe(),xs=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,mt=class mt{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=xs.exec(e.text):r=xs.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),s=0,n=e.length;s{"use strict";var{EventEmitter:Va}=require("events"),qs=Ps(),Ms=_e(),yt=class yt extends Va{constructor(e,r,s){super(),e=Ms.normalizeQueryConfig(e,r,s),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new qs(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new qs(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(s){this._canceledDueToError=s;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:Ms.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(yt,"Query");var gt=yt;Ds.exports=gt});var zt=_(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.NoticeMessage=f.DataRowMessage=f.CommandCompleteMessage=f.ReadyForQueryMessage=f.NotificationResponseMessage=f.BackendKeyDataMessage=f.AuthenticationMD5Password=f.ParameterStatusMessage=f.ParameterDescriptionMessage=f.RowDescriptionMessage=f.Field=f.CopyResponse=f.CopyDataMessage=f.DatabaseError=f.copyDone=f.emptyQuery=f.replicationStart=f.portalSuspended=f.noData=f.closeComplete=f.bindComplete=f.parseComplete=void 0;f.parseComplete={name:"parseComplete",length:5};f.bindComplete={name:"bindComplete",length:5};f.closeComplete={name:"closeComplete",length:5};f.noData={name:"noData",length:5};f.portalSuspended={name:"portalSuspended",length:5};f.replicationStart={name:"replicationStart",length:4};f.emptyQuery={name:"emptyQuery",length:4};f.copyDone={name:"copyDone",length:4};var Pt=class Pt extends Error{constructor(e,r,s){super(e),this.length=r,this.name=s}};i(Pt,"DatabaseError");var Et=Pt;f.DatabaseError=Et;var qt=class qt{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(qt,"CopyDataMessage");var St=qt;f.CopyDataMessage=St;var Mt=class Mt{constructor(e,r,s,n){this.length=e,this.name=r,this.binary=s,this.columnTypes=new Array(n)}};i(Mt,"CopyResponse");var Tt=Mt;f.CopyResponse=Tt;var Dt=class Dt{constructor(e,r,s,n,a,o,c){this.name=e,this.tableID=r,this.columnID=s,this.dataTypeID=n,this.dataTypeSize=a,this.dataTypeModifier=o,this.format=c}};i(Dt,"Field");var bt=Dt;f.Field=bt;var Ft=class Ft{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(Ft,"RowDescriptionMessage");var At=Ft;f.RowDescriptionMessage=At;var Bt=class Bt{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(Bt,"ParameterDescriptionMessage");var vt=Bt;f.ParameterDescriptionMessage=vt;var kt=class kt{constructor(e,r,s){this.length=e,this.parameterName=r,this.parameterValue=s,this.name="parameterStatus"}};i(kt,"ParameterStatusMessage");var wt=kt;f.ParameterStatusMessage=wt;var Ut=class Ut{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(Ut,"AuthenticationMD5Password");var Nt=Ut;f.AuthenticationMD5Password=Nt;var Gt=class Gt{constructor(e,r,s){this.length=e,this.processID=r,this.secretKey=s,this.name="backendKeyData"}};i(Gt,"BackendKeyDataMessage");var Ct=Gt;f.BackendKeyDataMessage=Ct;var Qt=class Qt{constructor(e,r,s,n){this.length=e,this.processId=r,this.channel=s,this.payload=n,this.name="notification"}};i(Qt,"NotificationResponseMessage");var Rt=Qt;f.NotificationResponseMessage=Rt;var Ht=class Ht{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(Ht,"ReadyForQueryMessage");var Ot=Ht;f.ReadyForQueryMessage=Ot;var jt=class jt{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(jt,"CommandCompleteMessage");var It=jt;f.CommandCompleteMessage=It;var Wt=class Wt{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(Wt,"DataRowMessage");var xt=Wt;f.DataRowMessage=xt;var Vt=class Vt{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(Vt,"NoticeMessage");var Lt=Vt;f.NoticeMessage=Lt});var Bs=_(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.Writer=void 0;var Kt=class Kt{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(n),s.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(Kt,"Writer");var $t=Kt;Re.Writer=$t});var Us=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.serialize=void 0;var Jt=Bs(),T=new Jt.Writer,za=i(t=>{T.addInt16(3).addInt16(0);for(let s of Object.keys(t))T.addCString(s).addCString(t[s]);T.addCString("client_encoding").addCString("UTF8");var e=T.addCString("").flush(),r=e.length+4;return new Jt.Writer().addInt32(r).add(e).flush()},"startup"),$a=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),Ka=i(t=>T.addCString(t).flush(112),"password"),Ja=i(function(t,e){return T.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),T.flush(112)},"sendSASLInitialResponseMessage"),Ya=i(function(t){return T.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),Za=i(t=>T.addCString(t).flush(81),"query"),ks=[],Xa=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||ks;for(var s=r.length,n=T.addCString(e).addCString(t.text).addInt16(s),a=0;a{let e=t.portal||"",r=t.statement||"",s=t.binary||!1,n=t.values||ks,a=n.length;return T.addCString(e).addCString(r),T.addInt16(a),eo(n,t.valueMapper),T.addInt16(a),T.add(J.flush()),T.addInt16(s?1:0),T.flush(66)},"bind"),ro=Buffer.from([69,0,0,0,9,0,0,0,0,0]),so=i(t=>{if(!t||!t.portal&&!t.rows)return ro;let e=t.portal||"",r=t.rows||0,s=Buffer.byteLength(e),n=4+s+1+4,a=Buffer.allocUnsafe(1+n);return a[0]=69,a.writeInt32BE(n,1),a.write(e,5,"utf-8"),a[s+5]=0,a.writeUInt32BE(r,a.length-4),a},"execute"),no=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),Yt=i((t,e)=>{let s=4+Buffer.byteLength(e)+1,n=Buffer.allocUnsafe(1+s);return n[0]=t,n.writeInt32BE(s,1),n.write(e,5,"utf-8"),n[s]=0,n},"cstringMessage"),io=T.addCString("P").flush(68),ao=T.addCString("S").flush(68),oo=i(t=>t.name?Yt(68,`${t.type}${t.name||""}`):t.type==="P"?io:ao,"describe"),co=i(t=>{let e=`${t.type}${t.name||""}`;return Yt(67,e)},"close"),uo=i(t=>T.add(t).flush(100),"copyData"),lo=i(t=>Yt(102,t),"copyFail"),Oe=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),po=Oe(72),ho=Oe(83),_o=Oe(88),fo=Oe(99),mo={startup:za,password:Ka,requestSsl:$a,sendSASLInitialResponseMessage:Ja,sendSCRAMClientFinalMessage:Ya,query:Za,parse:Xa,bind:to,execute:so,describe:oo,close:co,flush:()=>po,sync:()=>ho,end:()=>_o,copyData:uo,copyDone:()=>fo,copyFail:lo,cancel:no};Ie.serialize=mo});var Gs=_(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.BufferReader=void 0;var go=Buffer.allocUnsafe(0),Xt=class Xt{constructor(e=0){this.offset=e,this.buffer=go,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(Xt,"BufferReader");var Zt=Xt;xe.BufferReader=Zt});var js=_(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Parser=void 0;var b=zt(),yo=Gs(),er=1,Eo=4,Qs=er+Eo,Hs=Buffer.allocUnsafe(0),rr=class rr{constructor(e){if(this.buffer=Hs,this.bufferLength=0,this.bufferOffset=0,this.reader=new yo.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let s=this.bufferOffset+this.bufferLength,n=this.bufferOffset;for(;n+Qs<=s;){let a=this.buffer[n],o=this.buffer.readUInt32BE(n+er),c=er+o;if(c+n<=s){let l=this.handlePacket(n+Qs,a,o,this.buffer);r(l),n+=c}else break}n===s?(this.buffer=Hs,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=s-n,this.bufferOffset=n)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let n;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)n=this.buffer;else{let a=this.buffer.byteLength*2;for(;r>=a;)a*=2;n=Buffer.allocUnsafe(a)}this.buffer.copy(n,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=n,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,s,n){switch(r){case 50:return b.bindComplete;case 49:return b.parseComplete;case 51:return b.closeComplete;case 110:return b.noData;case 115:return b.portalSuspended;case 99:return b.copyDone;case 87:return b.replicationStart;case 73:return b.emptyQuery;case 68:return this.parseDataRowMessage(e,s,n);case 67:return this.parseCommandCompleteMessage(e,s,n);case 90:return this.parseReadyForQueryMessage(e,s,n);case 65:return this.parseNotificationMessage(e,s,n);case 82:return this.parseAuthenticationResponse(e,s,n);case 83:return this.parseParameterStatusMessage(e,s,n);case 75:return this.parseBackendKeyData(e,s,n);case 69:return this.parseErrorMessage(e,s,n,"error");case 78:return this.parseErrorMessage(e,s,n,"notice");case 84:return this.parseRowDescriptionMessage(e,s,n);case 116:return this.parseParameterDescriptionMessage(e,s,n);case 71:return this.parseCopyInMessage(e,s,n);case 72:return this.parseCopyOutMessage(e,s,n);case 100:return this.parseCopyData(e,s,n);default:return new b.DatabaseError("received invalid response: "+r.toString(16),s,"error")}}parseReadyForQueryMessage(e,r,s){this.reader.setBuffer(e,s);let n=this.reader.string(1);return new b.ReadyForQueryMessage(r,n)}parseCommandCompleteMessage(e,r,s){this.reader.setBuffer(e,s);let n=this.reader.cstring();return new b.CommandCompleteMessage(r,n)}parseCopyData(e,r,s){let n=s.slice(e,e+(r-4));return new b.CopyDataMessage(r,n)}parseCopyInMessage(e,r,s){return this.parseCopyMessage(e,r,s,"copyInResponse")}parseCopyOutMessage(e,r,s){return this.parseCopyMessage(e,r,s,"copyOutResponse")}parseCopyMessage(e,r,s,n){this.reader.setBuffer(e,s);let a=this.reader.byte()!==0,o=this.reader.int16(),c=new b.CopyResponse(r,n,a,o);for(let l=0;l{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.DatabaseError=U.serialize=U.parse=void 0;var So=zt();Object.defineProperty(U,"DatabaseError",{enumerable:!0,get:function(){return So.DatabaseError}});var To=Us();Object.defineProperty(U,"serialize",{enumerable:!0,get:function(){return To.serialize}});var bo=js();function Ao(t,e){let r=new bo.Parser;return t.on("data",s=>r.parse(s,e)),new Promise(s=>t.on("end",()=>s()))}i(Ao,"parse");U.parse=Ao});var Ws={};yi(Ws,{default:()=>vo});var vo,Vs=gi(()=>{vo={}});var zs=_((Qp,nr)=>{nr.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:s}=(Vs(),Si(Ws));return new s(e)}},"getStream");nr.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var or=_((Wp,$s)=>{"use strict";var jp=require("net"),wo=require("events").EventEmitter,{parse:No,serialize:N}=sr(),{getStream:Co,getSecureStream:Ro}=zs(),Oo=N.flush(),Io=N.sync(),xo=N.end(),ar=class ar extends wo{constructor(e){super(),e=e||{},this.stream=e.stream||Co(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(s){s==="message"&&(r._emitMessage=!0)})}connect(e,r){var s=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){s._keepAlive&&s.stream.setKeepAlive(!0,s._keepAliveInitialDelayMillis),s.emit("connect")});let n=i(function(a){s._ending&&(a.code==="ECONNRESET"||a.code==="EPIPE")||s.emit("error",a)},"reportStreamError");if(this.stream.on("error",n),this.stream.on("close",function(){s.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(a){var o=a.toString("utf8");switch(o){case"S":break;case"N":return s.stream.end(),s.emit("error",new Error("The server does not support SSL connections"));default:return s.stream.end(),s.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:s.stream};s.ssl!==!0&&(Object.assign(c,s.ssl),"key"in s.ssl&&(c.key=s.ssl.key));var l=require("net");l.isIP&&l.isIP(r)===0&&(c.servername=r);try{s.stream=Ro(c)}catch(u){return s.emit("error",u)}s.attachListeners(s.stream),s.stream.on("error",n),s.emit("sslconnect")})}attachListeners(e){No(e,r=>{var s=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(s,r)})}requestSsl(){this.stream.write(N.requestSsl())}startup(e){this.stream.write(N.startup(e))}cancel(e,r){this._send(N.cancel(e,r))}password(e){this._send(N.password(e))}sendSASLInitialResponseMessage(e,r){this._send(N.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(N.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(N.query(e))}parse(e){this._send(N.parse(e))}bind(e){this._send(N.bind(e))}execute(e){this._send(N.execute(e))}flush(){this.stream.writable&&this.stream.write(Oo)}sync(){this._ending=!0,this._send(Io)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(xo,()=>{this.stream.end()})}close(e){this._send(N.close(e))}describe(e){this._send(N.describe(e))}sendCopyFromChunk(e){this._send(N.copyData(e))}endCopyFrom(){this._send(N.copyDone())}sendCopyFail(e){this._send(N.copyFail(e))}};i(ar,"Connection");var ir=ar;$s.exports=ir});var Zs=_((zp,Ys)=>{"use strict";var{Transform:Lo}=require("stream"),{StringDecoder:Po}=require("string_decoder"),G=Symbol("last"),Pe=Symbol("decoder");function qo(t,e,r){let s;if(this.overflow){if(s=this[Pe].write(t).split(this.matcher),s.length===1)return r();s.shift(),this.overflow=!1}else this[G]+=this[Pe].write(t),s=this[G].split(this.matcher);this[G]=s.pop();for(let n=0;nthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(qo,"transform");function Mo(t){if(this[G]+=this[Pe].end(),this[G])try{Js(this,this.mapper(this[G]))}catch(e){return t(e)}t()}i(Mo,"flush");function Js(t,e){e!==void 0&&t.push(e)}i(Js,"push");function Ks(t){return t}i(Ks,"noop");function Do(t,e,r){switch(t=t||/\r?\n/,e=e||Ks,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=Ks)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=qo,r.flush=Mo,r.readableObjectMode=!0;let s=new Lo(r);return s[G]="",s[Pe]=new Po("utf8"),s.matcher=t,s.mapper=e,s.maxLength=r.maxLength,s.skipOverflow=r.skipOverflow||!1,s.overflow=!1,s._destroy=function(n,a){this._writableState.errorEmitted=!1,a(n)},s}i(Do,"split");Ys.exports=Do});var tn=_((Kp,B)=>{"use strict";var Xs=require("path"),Fo=require("stream").Stream,Bo=Zs(),en=require("util"),ko=5432,qe=process.platform==="win32",fe=process.stderr,Uo=56,Go=7,Qo=61440,Ho=32768;function jo(t){return(t&Qo)==Ho}i(jo,"isRegFile");var Y=["host","port","database","user","password"],cr=Y.length,Wo=Y[cr-1];function ur(){var t=fe instanceof Fo&&fe.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` +`);fe.write(en.format.apply(en,e))}}i(ur,"warn");Object.defineProperty(B.exports,"isWin",{get:function(){return qe},set:function(t){qe=t}});B.exports.warnTo=function(t){var e=fe;return fe=t,e};B.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(qe?Xs.join(e.APPDATA||"./","postgresql","pgpass.conf"):Xs.join(e.HOME||"./",".pgpass"));return r};B.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:qe?!0:(e=e||"",jo(t.mode)?t.mode&(Uo|Go)?(ur('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(ur('WARNING: password file "%s" is not a plain file',e),!1))};var Vo=B.exports.match=function(t,e){return Y.slice(0,-1).reduce(function(r,s,n){return n==1&&Number(t[s]||ko)===Number(e[s])?r&&!0:r&&(e[s]==="*"||e[s]===t[s])},!0)};B.exports.getPassword=function(t,e,r){var s,n=e.pipe(Bo());function a(l){var u=zo(l);u&&$o(u)&&Vo(t,u)&&(s=u[Wo],n.end())}i(a,"onLine");var o=i(function(){e.destroy(),r(s)},"onEnd"),c=i(function(l){e.destroy(),ur("WARNING: error on reading file: %s",l),r(void 0)},"onErr");e.on("error",c),n.on("data",a).on("end",o).on("error",c)};var zo=B.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",s=0,n=0,a=0,o={},c=!1,l=i(function(p,h,d){var E=t.substring(h,d);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(E=E.replace(/\\([:\\])/g,"$1")),o[Y[p]]=E},"addToObj"),u=0;u=0&&e==":"&&r!=="\\"&&(l(s,n,u+1),n=u+2,s+=1)}return o=Object.keys(o).length===cr?o:null,o},$o=B.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r{"use strict";var Yp=require("path"),rn=require("fs"),Me=tn();lr.exports=function(t,e){var r=Me.getFileName();rn.stat(r,function(s,n){if(s||!Me.usePgPass(n,r))return e(void 0);var a=rn.createReadStream(r);Me.getPassword(t,a,e)})};lr.exports.warnTo=Me.warnTo});var cn=_((Xp,on)=>{"use strict";var Ko=require("events").EventEmitter,nn=_e(),pr=vs(),Jo=lt(),Yo=dt(),an=Fs(),Zo=he(),Xo=or(),ec=ut(),hr=class hr extends Ko{constructor(e){super(),this.connectionParameters=new Yo(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new Jo(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new Xo({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||Zo.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,s=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let n=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(n)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{s._ending=!0,s.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?s.connect(this.host+"/.s.PGSQL."+this.port):s.connect(this.port,this.host),s.on("connect",function(){r.ssl?s.requestSsl():s.startup(r.getStartupConf())}),s.on("sslconnect",function(){s.startup(r.getStartupConf())}),this._attachListeners(s),s.once("end",()=>{let n=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(n),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(n):this._handleErrorEvent(n):this._connectionError||this._handleErrorEvent(n)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,s)=>{this._connect(n=>{n?s(n):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(s=>{if(s!==void 0){if(typeof s!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=s}else this.connectionParameters.password=this.password=null;e()}).catch(s=>{r.emit("error",s)});else if(this.password!==null)e();else try{sn()(this.connectionParameters,n=>{n!==void 0&&(this.connectionParameters.password=this.password=n),e()})}catch(s){this.emit("error",s)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await ec.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=pr.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await pr.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{pr.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},s=e.application_name||e.fallback_application_name;return s&&(r.application_name=s),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var s=this.connection;this.host&&this.host.indexOf("/")===0?s.connect(this.host+"/.s.PGSQL."+this.port):s.connect(this.port,this.host),s.on("connect",function(){s.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,s){return this._types.setTypeParser(e,r,s)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return nn.escapeIdentifier(e)}escapeLiteral(e){return nn.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,s){var n,a,o,c,l;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,a=n=e,typeof r=="function"&&(n.callback=n.callback||r)):(o=this.connectionParameters.query_timeout,n=new an(e,r,s),n.callback||(a=new this._Promise((u,p)=>{n.callback=(h,d)=>h?p(h):u(d)}).catch(u=>{throw Error.captureStackTrace(u),u}))),o&&(l=n.callback,c=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),l(u),n.callback=()=>{};var p=this.queryQueue.indexOf(n);p>-1&&this.queryQueue.splice(p,1),this._pulseQueryQueue()},o),n.callback=(u,p)=>{clearTimeout(c),l(u,p)}),this.binary&&!n.binary&&(n.binary=!0),n._result&&!n._result._types&&(n._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"),this.connection)}),a):(this.queryQueue.push(n),this._pulseQueryQueue(),a):(process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),a)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(hr,"Client");var De=hr;De.Query=an;on.exports=De});var hn=_((th,pn)=>{"use strict";var tc=require("events").EventEmitter,un=i(function(){},"NOOP"),ln=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),fr=class fr{constructor(e,r,s){this.client=e,this.idleListener=r,this.timeoutId=s}};i(fr,"IdleItem");var _r=fr,mr=class mr{constructor(e){this.callback=e}};i(mr,"PendingItem");var Z=mr;function rc(){throw new Error("Release called on client which has already been released to the pool.")}i(rc,"throwOnDoubleRelease");function Fe(t,e){if(e)return{callback:e,result:void 0};let r,s,n=i(function(o,c){o?r(o):s(c)},"cb"),a=new t(function(o,c){s=o,r=c}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:n,result:a}}i(Fe,"promisify");function sc(t,e){return i(function r(s){s.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",s)}),t._remove(e),t.emit("error",s,e)},"idleListener")}i(sc,"makeIdleListener");var gr=class gr extends tc{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||yr().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let s=r.client;s.ref&&s.ref();let n=r.idleListener;return this._acquireClient(s,e,n,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=ln(this._idle,s=>s.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(s=>s!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let n=new Error("Cannot use a pool after calling end on the pool");return e?e(n):this.Promise.reject(n)}let r=Fe(this.Promise,e),s=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new Z(r.callback)),s;let n=i((c,l,u)=>{clearTimeout(o),r.callback(c,l,u)},"queueCallback"),a=new Z(n),o=setTimeout(()=>{ln(this._pendingQueue,c=>c.callback===n),a.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(a),s}return this.newClient(new Z(r.callback)),s}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let s=sc(this,r);this.log("checking client timeout");let n,a=!1;this.options.connectionTimeoutMillis&&(n=setTimeout(()=>{this.log("ending client due to timeout"),a=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(n&&clearTimeout(n),r.on("error",s),o)this.log("client failed to connect",o),this._clients=this._clients.filter(c=>c!==r),a&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,un);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(u=>u.client===r)!==-1&&this._acquireClient(r,new Z((u,p,h)=>h()),s,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,s,!0)}})}_acquireClient(e,r,s,n){n&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,s),e.removeListener("error",s),r.timedOut?n&&this.options.verify?this.options.verify(e,e.release):e.release():n&&this.options.verify?this.options.verify(e,a=>{if(a)return e.release(a),r.callback(a,void 0,un);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let s=!1;return n=>{s&&rc(),s=!0,this._release(e,r,n)}}_release(e,r,s){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",s,e),s||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let a;this.options.idleTimeoutMillis&&(a=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&a.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new _r(e,r,a)),this._pulseQueue()}query(e,r,s){if(typeof e=="function"){let a=Fe(this.Promise,e);return setImmediate(function(){return a.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),a.result}typeof r=="function"&&(s=r,r=void 0);let n=Fe(this.Promise,s);return s=n.callback,this.connect((a,o)=>{if(a)return s(a);let c=!1,l=i(u=>{c||(c=!0,o.release(u),s(u))},"onError");o.once("error",l),this.log("dispatching query");try{o.query(e,r,(u,p)=>{if(this.log("query dispatched"),o.removeListener("error",l),!c)return c=!0,o.release(u),u?s(u):s(void 0,p)})}catch(u){return o.release(u),s(u)}}),n.result}end(e){if(this.log("ending"),this.ending){let s=new Error("Called end on pool more than once");return e?e(s):this.Promise.reject(s)}this.ending=!0;let r=Fe(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(gr,"Pool");var dr=gr;pn.exports=dr});var fn=_((sh,dn)=>{"use strict";var _n=require("events").EventEmitter,nc=require("util"),Er=_e(),X=dn.exports=function(t,e,r){_n.call(this),t=Er.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(s){s==="row"&&(this._emitRowEvents=!0)}.bind(this))};nc.inherits(X,_n);var ic={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};X.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var s=ic[r]||r;t[s]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};X.prototype.then=function(t,e){return this._getPromise().then(t,e)};X.prototype.catch=function(t){return this._getPromise().catch(t)};X.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};X.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(a,o,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),a)return e.handleError(a);e._emitRowEvents&&(c.length>1?o.forEach((l,u)=>{l.forEach(p=>{e.emit("row",p,c[u])})}):o.forEach(function(l){e.emit("row",l,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var s=(this.values||[]).map(Er.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let a=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(a)}return t.native.execute(this.name,s,r)}return t.native.prepare(this.name,this.text,s.length,function(a){return a?r(a):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,s,r))})}else if(this.values){if(!Array.isArray(this.values)){let a=new Error("Query values must be an array");return r(a)}var n=this.values.map(Er.prepareValue);t.native.query(this.text,n,r)}else this.queryMode==="extended"?t.native.query(this.text,[],r):t.native.query(this.text,r)}});var Sn=_((ih,En)=>{"use strict";var mn;try{mn=require("pg-native")}catch(t){throw t}var ac=lt(),gn=require("events").EventEmitter,oc=require("util"),cc=dt(),yn=fn(),x=En.exports=function(t){gn.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new ac(t.types),this.native=new mn({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new cc(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};x.Query=yn;oc.inherits(x,gn);x.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};x.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,s){if(e.connectionParameters.nativeConnectionString&&(s=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(s,function(n){if(n)return e.native.end(),t(n);e._connected=!0,e.native.on("error",function(a){e._queryable=!1,e._errorAllQueries(a),e.emit("error",a)}),e.native.on("notification",function(a){e.emit("notification",{channel:a.relname,payload:a.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};x.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(s=>{s?r(s):e()})})};x.prototype.query=function(t,e,r){var s,n,a,o,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")a=t.query_timeout||this.connectionParameters.query_timeout,n=s=t,typeof e=="function"&&(t.callback=e);else if(a=this.connectionParameters.query_timeout,s=new yn(t,e,r),!s.callback){let l,u;n=new this._Promise((p,h)=>{l=p,u=h}).catch(p=>{throw Error.captureStackTrace(p),p}),s.callback=(p,h)=>p?u(p):l(h)}return a&&(c=s.callback,o=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{s.handleError(l,this.connection)}),c(l),s.callback=()=>{};var u=this._queryQueue.indexOf(s);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},a),s.callback=(l,u)=>{clearTimeout(o),c(l,u)}),this._queryable?this._ending?(s.native=this.native,process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"))}),n):(this._queryQueue.push(s),this._pulseQueryQueue(),n):(s.native=this.native,process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"))}),n)};x.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(s,n){t=i(a=>a?n(a):s(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};x.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};x.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};x.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};x.prototype.ref=function(){};x.prototype.unref=function(){};x.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};x.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var Sr=_((oh,Tn)=>{"use strict";Tn.exports=Sn()});var yr=_((ch,me)=>{"use strict";var uc=cn(),lc=he(),pc=or(),hc=hn(),{DatabaseError:_c}=sr(),{escapeIdentifier:dc,escapeLiteral:fc}=_e(),mc=i(t=>{var e;return e=class extends hc{constructor(s){super(s,t)}},i(e,"BoundPool"),e},"poolFactory"),Tr=i(function(t){this.defaults=lc,this.Client=t,this.Query=this.Client.Query,this.Pool=mc(this.Client),this._pools=[],this.Connection=pc,this.types=pe(),this.DatabaseError=_c,this.escapeIdentifier=dc,this.escapeLiteral=fc},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?me.exports=new Tr(Sr()):(me.exports=new Tr(uc),Object.defineProperty(me.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new Tr(Sr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(me.exports,"native",{value:t}),t}}))});var An=_((lh,bn)=>{"use strict";var ee=require("fs"),gc=yr(),yc="The server does not support SSL connections",Ec="28000",Sc=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let s={checkServerIdentity(n,a){e.info("Certificate",{hostname:n,cert:{subject:a.subject,issuer:a.issuer,valid_from:a.valid_from,valid_to:a.valid_to}})}};return ee.existsSync(t.certAuthority)&&(s.ca=ee.readFileSync(t.certAuthority).toString()),ee.existsSync(t.clientCert)&&(s.cert=ee.readFileSync(t.clientCert).toString()),ee.existsSync(t.clientPrivateKey)&&(s.key=ee.readFileSync(t.clientPrivateKey).toString()),s},"getSslOptions"),Tc=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),bc=i(async(t,e,r)=>{let s=!1;if(t.ssh){let{options:o}=await e.openTunnel({sshAuthMethod:t.ssh_method==="privateKey"?"IDENTITY_FILE":"USER_PASSWORD",sshTunnelHostname:t.ssh_host,sshTunnelPort:t.ssh_port,sshTunnelUsername:t.ssh_user,sshTunnelPassword:t.ssh_password,sshTunnelIdentityFile:t.ssh_key_file,sshTunnelPassphrase:t.ssh_key_passphrase,host:t.host,port:t.port});t={...t,...o},s=!0}t=Object.assign({},t,{sslType:Tc(t.sslType)});let n={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:Sc(t,r),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await br(n,r),isSshTunnel:s}},"createClient"),Ac=i((t,e,r)=>{var s;if(r.message===yc&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),br({...t,isRetry:!0,ssl:!1},e);if(((s=r.code)==null?void 0:s.toString())===Ec&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),br({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),br=i((t,e)=>{let r=new gc.Pool(t);return r.connect().then(s=>(s.release(),r)).catch(async s=>{if(await r.end(),t.isRetry)throw s;return Ac(t,e,s)})},"createConnectionPool");bn.exports={createClient:bc}});var vr=_((hh,Nn)=>{"use strict";var Ar=i(t=>` SELECT indexname, index_method, index_unique, @@ -76,7 +72,7 @@ number_of_keys, where_expression, tablespace_name; - `,"getGET_TABLE_INDEXES"),_i=i(t=>` + `,"getGET_TABLE_INDEXES"),vn=i(t=>` SELECT obj_description(oid, 'pg_proc') AS description, proname AS function_name, provolatile AS volatility, @@ -88,7 +84,7 @@ prorows AS estimated_rows, prosrc AS body, ${t===10?"CASE WHEN proiswindow is true THEN 'w' ELSE '' END AS kind":"prokind AS kind"} - FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),mi={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` + FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),wn={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` SELECT tables.table_name, tables.table_type FROM information_schema.tables AS tables INNER JOIN (SELECT @@ -133,9 +129,9 @@ FROM pg_catalog.pg_attribute AS pg_attribute LEFT JOIN pg_catalog.pg_description AS pg_description ON (pg_description.objsubid=pg_attribute.attnum AND pg_description.objoid = pg_attribute.attrelid) - WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1)",GET_ROWS_COUNT:i(t=>`SELECT COUNT(*) AS quantity FROM ${t};`,"GET_ROWS_COUNT"),GET_SAMPLED_DATA:i((t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,"GET_SAMPLED_DATA"),GET_SAMPLED_DATA_SIZE:i((t,e)=>` + WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1)",GET_ROWS_COUNT:t=>`SELECT COUNT(*) AS quantity FROM ${t};`,GET_SAMPLED_DATA:(t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,GET_SAMPLED_DATA_SIZE:(t,e)=>` SELECT sum(pg_column_size(_hackolade_tmp_sampling_tbl.*)) AS _hackolade_tmp_sampling_tbl_size - FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,"GET_SAMPLED_DATA_SIZE"),GET_INHERITS_PARENT_TABLE_NAME:` + FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,GET_INHERITS_PARENT_TABLE_NAME:` SELECT pc.relname AS parent_table_name FROM pg_catalog.pg_inherits AS pi INNER JOIN pg_catalog.pg_class AS pc ON pc.oid = pi.inhparent @@ -153,7 +149,7 @@ ON pcon.conindid = pc.oid LEFT JOIN pg_catalog.pg_tablespace AS pt ON pc.reltablespace = pt.oid - WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:Vr(),GET_TABLE_INDEXES_V_10:Vr(10),GET_TABLE_INDEXES_V_15:Vr(15),GET_TABLE_FOREIGN_KEYS:` + WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:Ar(),GET_TABLE_INDEXES_V_10:Ar(10),GET_TABLE_INDEXES_V_15:Ar(15),GET_TABLE_FOREIGN_KEYS:` SELECT pcon.conname AS relationship_name, pcon.conkey AS table_columns_positions, pcon.confdeltype AS relationship_on_delete, @@ -193,7 +189,7 @@ udt_name FROM information_schema.parameters WHERE specific_name = $1 - ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:_i(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:_i(10),GET_USER_DEFINED_TYPES:` + ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:vn(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:vn(10),GET_USER_DEFINED_TYPES:` SELECT pg_type.typrelid AS pg_class_oid, pg_type.typname AS name, pg_type.typtype AS type, @@ -369,4 +365,4 @@ WHERE pg_class.relkind = 'S' AND information_schema."sequences".sequence_schema = $1 ORDER BY sequence_name, column_name; - `},bl=i(t=>(Object.entries(mi).find(([r,n])=>t===n)||[])[0]||"Custom query","getQueryName");gi.exports={getQueryName:bl,...mi}});var Ei=h((Nd,yi)=>{var Al=$r(),z=null,Ke=null;yi.exports={initializeClient(t,e){z=t,Ke=e,z.on("error",r=>e.error(r))},isClientInitialized(){return!!z},releaseClient(){return z?new Promise(t=>{z.end(()=>{z=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let n=Al.getQueryName(t);Ke.info("Execute query",{queryName:n,params:e});let s=Date.now(),a=await z.query(t,e),o=Date.now()-s;Ke.info("Query executed",{queryName:n,params:e,duration:o,rowsCount:a.rowCount});let c=a.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(n){return n.query=t,n.params=e,Ke.error(n),null}}}});var vi=h((Id,Ti)=>{var Si=i(t=>{let e=t.reduce((n,s)=>s.properties?{...n,[s.name]:{...s,...Si(s.properties)}}:{...n,[s.name]:s},{}),r=Object.entries(e).filter(([n,s])=>s.required).map(([n])=>n);return{properties:e,required:r}},"getJsonSchema");Ti.exports={getJsonSchema:Si}});var zr=h((xd,bi)=>{var j=null,wl=i(t=>{j=t.require("lodash")},"setDependencies"),Oe={column_default:"default",is_nullable:{keyword:"required",values:{YES:!1,NO:!0}},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:i((t,e)=>e!==-1&&ql(t.data_type),"check")},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:"length",description:"description",domain_name:"domain_name"},Cl=i((t,e,r)=>{var n;return(n=Oe[e])!=null&&n.check?Oe[e].check(t,r)?r:"":j.get(Oe,`${e}.values.${r}`,r)},"getColumnValue"),Ol=i(t=>e=>j.chain(e).toPairs().map(([r,n])=>{var s;return[((s=Oe[r])==null?void 0:s.keyword)||Oe[r],Cl(e,r,n)]}).filter(([r,n])=>r&&!j.isNil(n)).fromPairs().thru(Nl(t)).value(),"mapColumnData"),Nl=i(t=>e=>({...e,...Il(t,e)}),"setColumnType"),Il=i((t,e)=>e.type==="ARRAY"?Rl(t,e):e.type==="USER-DEFINED"?Je(t,e.udt_name):e.domain_name?Je(t,e.domain_name):Je(t,e.type),"getType"),Rl=i((t,e)=>({...Je(t,e.udt_name.slice(1)),array_type:j.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),Je=i((t,e)=>{switch(e){case"bigint":case"bigserial":case"smallint":case"integer":case"numeric":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"int8":return{type:"numeric",mode:"bigint"};case"int2":return{type:"numeric",mode:"smallint"};case"int4":return{type:"numeric",mode:"integer"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return j.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),xl=i((t,e)=>{let r=j.first(e)||{};return t.map(n=>{if(n.type!=="json")return n;let s=r[n.name],a=Ll(s),o=Pl(a);return{...n,subtype:o}})},"setSubtypeFromSampledJsonValues"),Ll=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),Pl=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),ql=i(t=>j.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");bi.exports={setDependencies:wl,mapColumnData:Ol,setSubtypeFromSampledJsonValues:xl}});var Ne=h((Pd,Ai)=>{var Ml=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],ie=null,Dl=i(t=>{ie=t.require("lodash")},"setDependencies"),Fl=i(t=>ie.chain(t).toPairs().reject(([e,r])=>ie.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),Bl=i(t=>e=>{var r;return(r=ie.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),kl=i(t=>/\s|\W/.test(t)||ie.includes(Ml,ie.toUpper(t))?`"${t}"`:t,"wrapInQuotes");Ai.exports={clearEmptyPropertiesInObject:Fl,setDependencies:Dl,getColumnNameByPosition:Bl,wrapInQuotes:kl}});var Oi=h((Md,Ci)=>{var{getColumnNameByPosition:Ul}=Ne(),Kr=null,Gl=i(t=>{Kr=t.require("lodash")},"setDependencies"),wi=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Ql=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";case"p":return"PARTIAL";default:return""}},"prepareMatch"),Hl=i((t,e,r,n)=>Kr.map(t,s=>({relationshipName:s.relationship_name,dbName:s.foreign_table_schema,parentCollection:s.foreign_table_name,parentField:s.foreign_columns,childDbName:r,childCollection:e,childField:Kr.map(s.table_columns_positions,Ul(n)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:wi(s.relationship_on_delete),relationshipOnUpdate:wi(s.relationship_on_update),relationshipMatch:Ql(s.relationship_match)}})),"prepareForeignKeys");Ci.exports={setDependencies:Gl,prepareForeignKeys:Hl}});var Ri=h((Fd,Ii)=>{var Ye=null,jl=i(t=>{Ye=t.require("lodash")},"setDependencies"),Ni=i(t=>Ye.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:Wl(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),Wl=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),Vl=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),$l=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),zl=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Kl=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:Ni(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:Ye.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:Vl(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:zl(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:$l(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),Jl=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:Ye.toLower(t.external_language),inputArgs:Ni(e),body:t.routine_definition}),"mapProcedureData");Ii.exports={setDependencies:jl,mapFunctionData:Kl,mapProcedureData:Jl}});var Mi=h((kd,qi)=>{var{clearEmptyPropertiesInObject:Ie,getColumnNameByPosition:Ze}=Ne(),y=null,Yl=i(t=>{y=t.require("lodash")},"setDependencies"),Li=i((t,e)=>{if(!t&&!e)return null;let r=xi(t),n=xi(e==null?void 0:e.toast_options),s=r.fillfactor,a=r.parallel_workers,o=r.autovacuum_enabled,c=Ie({vacuum_index_cleanup:r.vacuum_index_cleanup,vacuum_truncate:r.vacuum_truncate,autovacuum_vacuum_threshold:r.autovacuum_vacuum_threshold,autovacuum_vacuum_scale_factor:r.autovacuum_vacuum_scale_factor,autovacuum_vacuum_insert_threshold:r.autovacuum_vacuum_insert_threshold,autovacuum_vacuum_insert_scale_factor:r.autovacuum_vacuum_insert_scale_factor,autovacuum_analyze_threshold:r.autovacuum_analyze_threshold,autovacuum_analyze_scale_factor:r.autovacuum_analyze_scale_factor,autovacuum_vacuum_cost_delay:r.autovacuum_vacuum_cost_delay,autovacuum_vacuum_cost_limit:r.autovacuum_vacuum_cost_limit,autovacuum_freeze_min_age:r.autovacuum_freeze_min_age,autovacuum_freeze_max_age:r.autovacuum_freeze_max_age,autovacuum_freeze_table_age:r.autovacuum_freeze_table_age,autovacuum_multixact_freeze_min_age:r.autovacuum_multixact_freeze_min_age,autovacuum_multixact_freeze_max_age:r.autovacuum_multixact_freeze_max_age,autovacuum_multixact_freeze_table_age:r.autovacuum_multixact_freeze_table_age,log_autovacuum_min_duration:r.log_autovacuum_min_duration}),u=r.user_catalog_table,l=n.autovacuum_enabled,p=Ie({toast_tuple_target:r.toast_tuple_target,toast_vacuum_index_cleanup:n.vacuum_index_cleanup,toast_vacuum_truncate:n.vacuum_truncate,toast_autovacuum_vacuum_threshold:n.autovacuum_vacuum_threshold,toast_autovacuum_vacuum_scale_factor:n.autovacuum_vacuum_scale_factor,toast_autovacuum_vacuum_insert_threshold:n.autovacuum_vacuum_insert_threshold,toast_autovacuum_vacuum_insert_scale_factor:n.autovacuum_vacuum_insert_scale_factor,toast_autovacuum_vacuum_cost_delay:n.autovacuum_vacuum_cost_delay,toast_autovacuum_vacuum_cost_limit:n.autovacuum_vacuum_cost_limit,toast_autovacuum_freeze_min_age:n.autovacuum_freeze_min_age,toast_autovacuum_freeze_max_age:n.autovacuum_freeze_max_age,toast_autovacuum_freeze_table_age:n.autovacuum_freeze_table_age,toast_autovacuum_multixact_freeze_min_age:n.autovacuum_multixact_freeze_min_age,toast_autovacuum_multixact_freeze_max_age:n.autovacuum_multixact_freeze_max_age,toast_autovacuum_multixact_freeze_table_age:n.autovacuum_multixact_freeze_table_age,toast_log_autovacuum_min_duration:n.log_autovacuum_min_duration}),f={fillfactor:s,parallel_workers:a,autovacuum_enabled:o,autovacuum:y.isEmpty(c)?null:c,toast_autovacuum_enabled:l,toast:y.isEmpty(p)?null:p,user_catalog_table:u};return Ie(f)},"prepareStorageParameters"),Zl=i((t,e)=>{if(!t)return null;let r=Xl(t),n=y.some(t.partition_attributes_positions,o=>o===0),s=n?"partitioning_expression":"compositePartitionKey",a=n?ep(t,e):y.map(t.partition_attributes_positions,Ze(e));return[{partitionMethod:r,partitionBy:n?"expression":"keys",[s]:a}]},"prepareTablePartition"),Xl=i(t=>{switch(t.partition_method){case"h":return"HASH";case"l":return"LIST";case"r":return"RANGE";default:return""}},"getPartitionMethod"),ep=i((t,e)=>{let r=0,n=y.split(t.expressions,",");return y.chain(t.partition_attributes_positions).map(s=>{if(s===0){let a=n[r];return r++,a}return Ze(e)(s)}).join(",").value()},"getPartitionExpression"),Pi=i(t=>y.split(t,"="),"splitByEqualitySymbol"),tp=i(t=>y.find(t,{type:"json"}),"checkHaveJsonTypes"),rp=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),np=i((t,e,r)=>y.reduce(t,(n,s)=>{switch(s.constraint_type){case"c":return{...n,chkConstr:[...n.chkConstr,ap(s)]};case"p":return{...n,primaryKey:[...n.primaryKey,sp(s,e)]};case"u":return{...n,uniqueKey:[...n.uniqueKey,ip(s,e,r)]};default:return n}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),sp=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:y.map(t.constraint_keys,Ze(e)),indexStorageParameters:y.join(t.storage_parameters,","),indexTablespace:t.tablespace}),"getPrimaryKeyConstraint"),ip=i((t,e,r)=>{let n=y.find(r,a=>a.indexname===t.constraint_name),s=n!=null&&n.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"";return{constraintName:t.constraint_name,compositeUniqueKey:y.map(t.constraint_keys,Ze(e)),indexStorageParameters:y.join(t.storage_parameters,","),indexTablespace:t.tablespace,indexComment:t.description,...s&&{nullsDistinct:s}}},"getUniqueKeyConstraint"),ap=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,noInherit:t.no_inherit,constrDescription:t.description}),"getCheckConstraint"),op=i(t=>y.map(t,e=>{let r=cp(e),n=y.slice(r,0,e.number_of_keys),s=y.chain(r).slice(e.number_of_keys).map(c=>y.pick(c,"name")).value(),a=e.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"",o={indxName:e.indexname,index_method:e.index_method,unique:e.index_unique??!1,index_tablespace_name:e.tablespace_name||"",index_storage_parameter:lp(e.storage_parameters),where:e.where_expression||"",include:s,columns:e.index_method==="btree"?n:y.map(n,c=>y.omit(c,"sortOrder","nullsOrder")),...a&&{nullsDistinct:a}};return Ie(o)}),"prepareTableIndexes"),cp=i(t=>y.chain(t.columns).map((e,r)=>{if(!e)return;let n=y.get(t,`ascendings.${r}`,!1)?"ASC":"DESC",s=up(y.get(t,`nulls_first.${r}`)),a=y.get(t,`opclasses.${r}`,""),o=y.get(t,`collations.${r}`,"");return{name:e,sortOrder:n,nullsOrder:s,opclass:a,collation:o}}).compact().value(),"mapIndexColumns"),up=i(t=>y.isNil(t)?"":t?"NULLS FIRST":"NULLS LAST","getNullsOrder"),lp=i(t=>{if(!t)return null;let e=y.fromPairs(y.map(t,n=>Pi(n))),r={index_fillfactor:e.fillfactor,deduplicate_items:e.deduplicate_items,index_buffering:e.index_buffering,fastupdate:e.fastupdate,gin_pending_list_limit:e.gin_pending_list_limit,pages_per_range:e.pages_per_range,autosummarize:e.autosummarize};return Ie(r)},"getIndexStorageParameters"),pp=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",n=(t==null?void 0:t.relpersistence)==="u",s=Li(t==null?void 0:t.reloptions,e),a=t==null?void 0:t.spcname,o=t.partition_expr;return{temporary:r,unlogged:n,storage_parameter:s,table_tablespace_name:a,partitionBounds:o}},"prepareTableLevelData"),hp=i(t=>{switch(fp(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),fp=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),xi=i(t=>y.chain(t).map(Pi).map(([e,r])=>[e,hp(r)]).fromPairs().value()||{},"prepareOptions"),dp=i((t,e)=>y.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");qi.exports={prepareStorageParameters:Li,prepareTablePartition:Zl,setDependencies:Yl,checkHaveJsonTypes:tp,prepareTableConstraints:np,prepareTableLevelData:pp,prepareTableIndexes:op,getSampleDocSize:rp,prepareTableInheritance:dp}});var Fi=h((Gd,Di)=>{var{mapColumnData:_p}=zr(),B=null,mp=i(t=>{B=t.require("lodash")},"setDependencies"),gp=i((t,e)=>B.chain(t).map(r=>{switch(r.type){case"e":return yp(r);case"r":return Ep(r);case"c":return Sp(r);default:return null}}).compact().concat(B.map(e,vp)).value(),"getUserDefinedTypes"),yp=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Ep=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Sp=i(t=>{let e=B.map(t.columns,_p([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),Tp=i(t=>t.type==="c","isTypeComposite"),vp=i(t=>{var e;return{name:t.domain_name,type:"domain",underlyingType:B.flow(Ap(t),wp(t),Cp(t),Op(t))(bp(t)),collation:t.collation_name||"",default:t.domain_default||"",required:(e=B.first(t.constraints))==null?void 0:e.not_null,checkConstraints:B.map(t.constraints,Np)}},"mapDomainType"),bp=i(t=>t.data_type==="USER-DEFINED"?t.udt_name:t.data_type,"getUnderlyingType"),Ap=i(t=>e=>t.character_maximum_length?`${e}(${t.character_maximum_length})`:e,"setLength"),wp=i(t=>e=>e!=="numeric"?e:B.isNumber(t.numeric_precision)&&B.isNumber(t.numeric_scale)?`${e}(${t.numeric_precision},${t.numeric_scale})`:B.isNumber(t.numeric_precision)?`${e}(${t.numeric_precision})`:e,"setPrecisionAndScale"),Cp=i(t=>e=>t.interval_type?`${e} ${t.interval_type}`:e,"setIntervalType"),Op=i(t=>e=>B.isNumber(t.interval_precision)?`${e}(${t.interval_precision})`:e,"setIntervalPrecision"),Np=i(t=>({name:t.constraint_name,expression:t.expression}),"mapDomainConstraint");Di.exports={setDependencies:mp,getUserDefinedTypes:gp,isTypeComposite:Tp}});var ki=h((Hd,Bi)=>{var{clearEmptyPropertiesInObject:Ip,wrapInQuotes:Rp}=Ne(),G=null,xp=i(t=>{G=t.require("lodash")},"setDependencies"),Jr=" (v)",Lp=i(t=>t==="VIEW","isViewByTableType"),Pp=i(t=>G.endsWith(t,Jr),"isViewByName"),qp=i(t=>t.slice(0,-Jr.length),"removeViewNameSuffix"),Mp=i(t=>`${t}${Jr}`,"setViewSuffix"),Dp=i((t,e,r={})=>{let n=G.trim(e.view_definition||r.definition||"");return n?`CREATE VIEW ${Rp(t)} AS ${n}`:""},"generateCreateViewScript"),Fp=i((t,e,r)=>{let n={withCheckOption:t.check_option!=="NONE"||G.isNil(t.check_option),checkTestingScope:Bp(t.check_option),viewOptions:G.fromPairs(G.map(e==null?void 0:e.view_options,Up)),temporary:(e==null?void 0:e.persistence)==="t",recursive:kp(t),description:e==null?void 0:e.description,triggers:r};return Ip(n)},"prepareViewData"),Bp=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),kp=i(t=>G.startsWith(G.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),Up=i(t=>G.split(t,"="),"splitByEqualitySymbol");Bi.exports={setDependencies:xp,isViewByTableType:Lp,isViewByName:Pp,removeViewNameSuffix:qp,generateCreateViewScript:Dp,setViewSuffix:Mp,prepareViewData:Fp}});var Gi=h((Wd,Ui)=>{var Xe=null,Gp=i(t=>{Xe=t.require("lodash")},"setDependencies"),Qp=i((t,e)=>Xe.chain(t).map(r=>({...r,...Xe.find(e,{trigger_name:r.trigger_name})||{}})).map(Hp).value(),"getTriggers"),Hp=i(t=>{var e;return{name:t.trigger_name,triggerDescription:t.description,triggerConstraint:t.constraint,triggerTable:`${t.event_object_schema}.${t.event_object_table}`,triggerReferencedTable:t.referenced_table_name?[t.referenced_table_schema,t.referenced_table_name]:[],triggerType:t.action_timing,triggerEvents:jp(t),triggerUpdateColumns:(e=t.update_attributes)==null?void 0:e.filter(Boolean),triggerDeferrable:t.deferrable,triggerTimeConstraintCheck:t.deferred?"INITIALLY DEFERRED":"INITIALLY IMMEDIATE",triggerReferencing:!!t.action_reference_old_table||!!t.action_reference_new_table,triggerBeforeImageTransitionRelation:t.action_reference_old_table||"",triggerAfterImageTransitionRelation:t.action_reference_new_table||"",triggerEachRowStatement:t.action_orientation==="ROW"?"FOR EACH ROW":"FOR EACH STATEMENT",triggerCondition:t.action_condition,triggerFunction:Wp(t.action_statement)}},"getTrigger"),jp=i(t=>Xe.map(t.trigger_events,e=>({triggerEvent:e})),"getTriggerEvents"),Wp=i(t=>{var e,r,n;return((n=(r=(e=/EXECUTE (?:FUNCTION|PROCEDURE)(?[\s\S]*)/.exec(t))==null?void 0:e.groups)==null?void 0:r.function)==null?void 0:n.trim())||""},"getFunctionFromTrigger");Ui.exports={setDependencies:Gp,getTriggers:Qp}});var ji=h(($d,Hi)=>{var Vp=i((t,e)=>[$p,zp].reduce(({attributes:r,entityLevel:n},s)=>s(r,n),{attributes:t,entityLevel:e}),"reorganizeConstraints"),$p=i((t,e)=>{var a,o,c;if(((c=(o=(a=e.primaryKey)==null?void 0:a[0])==null?void 0:o.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let n=e.primaryKey[0],s=n.compositePrimaryKey[0];return{attributes:Kp(t,s,n),entityLevel:Xp(e)}},"reorganizePrimaryKeys"),zp=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:n},s)=>{if(!(s.compositeUniqueKey.length===1))return{attributes:r,entityLevel:n};let o=s.compositeUniqueKey[0];return{attributes:Yp(r,o,s),entityLevel:eh(n,s)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Kp=i((t,e,r)=>t.map(n=>n.name!==e?n:Jp(n,r)),"setAttributesPrimaryKeyData"),Jp=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:Qi(e)}),"setPrimaryKeyData"),Yp=i((t,e,r)=>t.map(n=>n.name!==e?n:Zp(n,r)),"setAttributesUniqueKeyData"),Zp=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:Qi(e)}),"setUniqueKeyData"),Qi=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexComment:t.indexComment}],"getOptions"),Xp=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),eh=i((t,e)=>{let r=t.uniqueKey.filter(n=>n.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Hi.exports={reorganizeConstraints:Vp}});var Vi=h((Kd,Wi)=>{var Xr=class Xr{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};i(Xr,"Sequence");var Yr=Xr,en=class en{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};i(en,"SequenceDto");var Zr=en;Wi.exports={Sequence:Yr,SequenceDto:Zr}});var zi=h((Xd,$i)=>{var{Sequence:Yd,SequenceDto:Zd}=Vi(),th=i(({sequence:t})=>t.column_name?[{entity:t.table_name,name:t.column_name}]:[],"getOwnedByColumn"),rh=i(({sequence:t})=>({sequenceName:t.sequence_name,increment:Number(t.increment),start:Number(t.start_value),dataType:t.data_type,maxValue:Number(t.maximum_value),minValue:Number(t.minimum_value),cache:Number(t.cache_size),temporary:t.rel_persistance==="t",unlogged:t.rel_persistance==="u",cycle:t.cycle_option==="YES",ownedByColumn:th({sequence:t}),ownedByNone:!t.column_name}),"mapSequenceData");$i.exports={mapSequenceData:rh}});var Zi=h((t_,Yi)=>{var{createClient:nh}=di(),m=Ei(),{getJsonSchema:Ki}=vi(),{setDependencies:sh,mapColumnData:ih,setSubtypeFromSampledJsonValues:ah}=zr(),{setDependencies:oh,clearEmptyPropertiesInObject:Ji}=Ne(),{setDependencies:ch,prepareForeignKeys:uh}=Oi(),{setDependencies:lh,mapFunctionData:ph,mapProcedureData:hh}=Ri(),{setDependencies:fh,prepareTablePartition:dh,checkHaveJsonTypes:_h,prepareTableConstraints:mh,getSampleDocSize:gh,prepareTableLevelData:yh,prepareTableIndexes:Eh,prepareTableInheritance:Sh}=Mi(),{setDependencies:Th,getUserDefinedTypes:vh,isTypeComposite:bh}=Fi(),{setDependencies:Ah,isViewByTableType:wh,isViewByName:Ch,removeViewNameSuffix:Oh,generateCreateViewScript:Nh,setViewSuffix:Ih,prepareViewData:Rh}=ki(),{setDependencies:xh,getTriggers:Lh}=Gi(),g=$r(),{reorganizeConstraints:Ph}=ji(),{mapSequenceData:qh}=zi(),et=null,A=null,M=null,tn=14;Yi.exports={setDependencies(t){A=t.require("lodash"),oh(t),fh(t),sh(t),ch(t),Ah(t),lh(t),Th(t),xh(t)},async connect(t,e){m.isClientInitialized()&&await this.disconnect();let{client:r,sshTunnel:n}=await nh(t,e);m.initializeClient(r,e),et=n,M=e,tn=await this._getServerVersion()},async disconnect(){et&&(et.close(),et=null),await m.releaseClient()},pingDb(){return m.query(g.PING)},applyScript(t){return m.query(t)},async getDatabaseNames(){return A.map(await m.query(g.GET_DATABASES),"database_name")},async logVersion(){let t=await m.queryTolerant(g.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved";M.info(`PostgreSQL version: ${e}`)},async getAllSchemasNames(){return(await m.query(g.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!Mh(e))},async getTablesNames(t){let e=await m.query(g.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:n})=>!A.includes(r,n)).map(({table_name:n,table_type:s})=>wh(s)?Ih(n):n)},async getDbLevelData(){var n,s,a;M.progress("Get database data");let t=(n=await m.queryTolerant(g.GET_DB_NAME,[],!0))==null?void 0:n.current_database,e=(s=await m.queryTolerant(g.GET_DB_ENCODING,[],!0))==null?void 0:s.server_encoding,r=(a=await m.queryTolerant(g.GET_DB_COLLATE_NAME,[],!0))==null?void 0:a.default_collate_name;return Ji({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r,n=!1,s=!1){let a=await this._retrieveUserDefinedTypes(t),o=await m.queryTolerant(g.GET_NAMESPACE_OID,[t],!0),c=o==null?void 0:o.oid,u=n?await m.queryTolerant(g.GET_PARTITIONS,[c]):[],[l,p]=A.partition(e,Ch),f=p.flatMap(C=>[{tableName:C},...A.filter(u,{parent_name:C}).map(({child_name:R,is_parent_partitioned:W})=>({isParentPartitioned:W,tableName:R}))]),_=await ae(A.uniq(f),A.bind(this._retrieveSingleTableData,this,r,c,t,a,s));return{views:await ae(l,A.bind(this._retrieveSingleViewData,this,c,t,s)),tables:_,modelDefinitions:Ki(a)}},async retrieveSchemaLevelData(t,e){var f;if(e)return M.info("Functions and procedures ignored"),{functions:[],procedures:[]};M.progress("Get Functions and Procedures",t);let r=(f=await m.queryTolerant(g.GET_NAMESPACE_OID,[t],!0))==null?void 0:f.oid,n=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES,[t]),s=await m.queryTolerant(Fh(tn),[r]),[a,o]=A.partition(A.filter(n,"routine_type"),{routine_type:"FUNCTION"}),c=await ae(a,async _=>{let S=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[_.specific_name]),C=A.find(s,{function_name:_.name});return ph(_,S,C)}),u=await ae(o,async _=>{let S=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[_.specific_name]),C=A.find(s,{function_name:_.name});return hh(_,S,C)}),p=(await m.queryTolerant(g.GET_SEQUENCES,[t])).map(_=>qh({sequence:_}));return{functions:c,procedures:u,sequences:p}},async _retrieveUserDefinedTypes(t){M.progress("Get User-Defined Types",t);let e=await m.queryTolerant(g.GET_USER_DEFINED_TYPES,[t]),r=await m.queryTolerant(g.GET_DOMAIN_TYPES,[t]),n=await ae(e,async a=>bh(a)?{...a,columns:await m.queryTolerant(g.GET_COMPOSITE_TYPE_COLUMNS,[a.pg_class_oid])}:a),s=await ae(r,async a=>({...a,constraints:await m.queryTolerant(g.GET_DOMAIN_TYPES_CONSTRAINTS,[a.domain_name,t])}));return vh(n,s)},async _retrieveSingleTableData(t,e,r,n,s,{tableName:a,isParentPartitioned:o}){var nn;M.progress("Get table data",r,a);let c=await m.queryTolerant(g.GET_TABLE_LEVEL_DATA,[a,e],!0),u=c==null?void 0:c.oid,l=await m.queryTolerant(g.GET_TABLE_TOAST_OPTIONS,[a,e],!0),p=await m.queryTolerant(g.GET_TABLE_PARTITION_DATA,[u],!0),f=await this._getTableColumns(a,r,u),_=await m.queryTolerant(g.GET_DESCRIPTION_BY_OID,[u],!0),S=await m.queryTolerant(g.GET_INHERITS_PARENT_TABLE_NAME,[u]),C=await m.queryTolerant(g.GET_TABLE_CONSTRAINTS,[u]),R=await m.queryTolerant(Dh(tn),[u]),W=await m.queryTolerant(g.GET_TABLE_FOREIGN_KEYS,[u]),oe=await this._getTriggers(r,a,e,u,s);M.info("Table data retrieved",{schemaName:r,tableName:a,columnTypes:f.map(ia=>ia.data_type)});let rt=dh(p,f),nt=yh(c,l),st=Bh(_),Re=Sh(r,S),xe=mh(C,f,R),k=Eh(R),Xi=uh(W,a,r,f),ea={partitioning:rt,description:st,triggers:oe,Indxs:k,...nt,...xe,...o?{partitionOf:(nn=A.first(Re))==null?void 0:nn.parentTable}:{inherits:Re}},ta=Ji(ea),ce=f.map(ih(n)),ra=_h(ce),it=[];ra&&(it=await this._getDocuments(r,a,ce,t),ce=ah(ce,it));let{attributes:na,entityLevel:sa}=Ph(ce,ta);return{name:a,entityLevel:sa,jsonSchema:Ki(na),documents:it,relationships:Xi}},async _getTriggers(t,e,r,n,s){if(s)return M.info("Triggers ignored"),[];let a=await m.queryTolerant(g.GET_TRIGGERS,[t,e]),o=await m.queryTolerant(g.GET_TRIGGERS_ADDITIONAL_DATA,[r,n]);return Lh(a,o)},async _getTableColumns(t,e,r){M.progress("Get columns",e,t);let n=await m.query(g.GET_TABLE_COLUMNS,[t,e]),s=await m.queryTolerant(g.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return A.map(n,a=>({...a,...A.find(s,{name:a.column_name})||{}}))},async _getDocuments(t,e,r,n){var p;M.progress("Sampling table",t,e);let s=`${t}.${e}`,a=((p=await m.queryTolerant(g.GET_ROWS_COUNT(s),[],!0))==null?void 0:p.quantity)||0,o=gh(a,n),c=r.filter(({type:f})=>A.includes(["json","jsonb"],f)),u=A.map(c,"name").join(", "),l=await m.queryTolerant(g.GET_SAMPLED_DATA_SIZE(s,u),[o],!0);return M.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:l==null?void 0:l._hackolade_tmp_sampling_tbl_size}),await m.queryTolerant(g.GET_SAMPLED_DATA(s,u),[o])},async _retrieveSingleViewData(t,e,r,n){M.progress("Get view data",e,n),n=Oh(n);let s=await m.query(g.GET_VIEW_DATA,[n,e],!0),a=!s.view_definition&&await m.queryTolerant(g.GET_VIEW_SELECT_STMT_FALLBACK,[n,e],!0),o=await m.queryTolerant(g.GET_VIEW_OPTIONS,[n,t],!0),c=await this._getTriggers(e,n,t,o==null?void 0:o.oid,r),u=Nh(n,s,a),l=Rh(s,o,c);return u?{name:n,data:l,ddl:{script:u,type:"postgres"}}:(M.info("View select statement was not retrieved",{schemaName:e,viewName:n}),{name:n,data:l,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await m.queryTolerant(g.GET_VERSION_AS_NUM,[],!0),e=A.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var Mh=i(t=>!!(A.startsWith(t,"pg_")||A.includes(["information_schema"],t)),"isSystemSchema"),Dh=i(t=>t===10?g.GET_TABLE_INDEXES_V_10:t>15?g.GET_TABLE_INDEXES_V_15:g.GET_TABLE_INDEXES,"getGetIndexesQuery"),Fh=i(t=>t===10?g.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:g.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),Bh=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),ae=i((t,e)=>Promise.all(A.map(t,e)),"mapPromises")});var{createLogger:tt}=an(),w=Zi();module.exports={async disconnect(t,e,r,n){await w.disconnect(),r()},async testConnection(t,e,r,n){try{rn("Test connection",t,e);let s=tt({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.pingDb(),await w.logVersion(),r()}catch(s){e.log("error",K(s),"Test connection instance log"),r(K(s))}finally{await w.disconnect()}},async getDatabases(t,e,r,n){try{rn("Get databases",t,e);let s=tt({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.logVersion();let a=await w.getDatabaseNames();return e.log("info",a,"All databases list",t.hiddenKeys),r(null,a)}catch(s){return e.log("error",s),r(K(s))}},getDocumentKinds:i(function(t,e,r){r(null,[])},"getDocumentKinds"),async getDbCollectionsNames(t,e,r,n){try{rn("Get DB table names",t,e);let s=tt({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.logVersion();let o=await(await w.getAllSchemasNames()).reduce(async(c,u)=>{let l=await c;try{let p=await w.getTablesNames(u);return l.concat({dbName:u,dbCollections:p,isEmpty:p.length===0})}catch(p){return s.info(`Error reading database "${u}"`),s.error(p),l.concat({dbName:u,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,o)}catch(s){e.log("error",K(s),"Get DB collections names"),r(K(s)),await w.disconnect()}},async getDbCollectionsData(t,e,r,n){try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let s=tt({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});s.progress("Start reverse engineering...");let a=t.collectionData.collections,o=t.collectionData.dataBaseNames,c=await w.getDbLevelData(),{packages:u,relationships:l}=await Promise.all(o.map(async p=>{let{tables:f,views:_,modelDefinitions:S}=await w.retrieveEntitiesData(p,a[p],t.recordSamplingSettings,t.includePartitions,t.ignoreUdfUdpTriggers),{functions:C,procedures:R,triggers:W,sequences:oe}=await w.retrieveSchemaLevelData(p,t.ignoreUdfUdpTriggers);return s.progress("Schema data fetched successfully",p),{schemaName:p,tables:f,views:_,functions:C,procedures:R,modelDefinitions:S,triggers:W,sequences:oe}})).then(p=>{let f=p.flatMap(({tables:S})=>S.map(C=>C.relationships)).flat();return{packages:p.flatMap(({schemaName:S,tables:C,views:R,functions:W,procedures:oe,triggers:rt,modelDefinitions:nt,sequences:st})=>{let Re={UDFs:W,Procedures:oe,triggers:rt,sequences:st},xe=C.map(k=>({dbName:S,collectionName:k.name,documents:k.documents,views:[],emptyBucket:!1,entityLevel:k.entityLevel,validation:{jsonSchema:k.jsonSchema},bucketInfo:Re,modelDefinitions:nt})).sort(k=>n.require("lodash").isEmpty(k.entityLevel.inherits)?-1:1);if(R!=null&&R.length){let k={dbName:S,views:R,emptyBucket:!1};return[...xe,k]}return xe}),relationships:f}}).then(({packages:p,relationships:f})=>({packages:kh(p),relationships:f}));s.info("The data is processed and sent to the application",{packagesLength:u==null?void 0:u.length,relationshipsLength:l==null?void 0:l.length}),r(null,u,c,l)}catch(s){e.log("error",K(s),"Retrieve tables data"),r(K(s))}finally{await w.disconnect()}}};var K=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),rn=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),kh=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages"); + `},vc=i(t=>(Object.entries(wn).find(([r,s])=>t===s)||[])[0]||"Custom query","getQueryName");Nn.exports={getQueryName:vc,...wn}});var Rn=_((dh,Cn)=>{"use strict";var wc=vr(),j=null,Be=null;Cn.exports={initializeClient(t,e){j=t,Be=e,j.on("error",r=>e.error(r))},isClientInitialized(){return!!j},releaseClient(){return j?new Promise(t=>{j.end(()=>{j=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let s=wc.getQueryName(t);Be.info("Execute query",{queryName:s,params:e});let n=Date.now(),a=await j.query(t,e),o=Date.now()-n;Be.info("Query executed",{queryName:s,params:e,duration:o,rowsCount:a.rowCount});let c=a.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(s){return s.query=t,s.params=e,Be.error(s),null}}}});var xn=_((fh,In)=>{"use strict";var On=i(t=>{let e=t.reduce((s,n)=>n.properties?{...s,[n.name]:{...n,...On(n.properties)}}:{...s,[n.name]:n},{}),r=Object.entries(e).filter(([s,n])=>n.required).map(([s])=>s);return{properties:e,required:r}},"getJsonSchema");In.exports={getJsonSchema:On}});var wr=_((gh,Ln)=>{"use strict";var Q=null,Nc=i(t=>{Q=t.require("lodash")},"setDependencies"),ge={column_default:"default",is_nullable:{keyword:"required",values:{YES:!1,NO:!0}},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:(t,e)=>e!==-1&&Mc(t.data_type)},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:"length",description:"description",domain_name:"domain_name"},Cc=i((t,e,r)=>{var s;return(s=ge[e])!=null&&s.check?ge[e].check(t,r)?r:"":Q.get(ge,`${e}.values.${r}`,r)},"getColumnValue"),Rc=i(t=>e=>Q.chain(e).toPairs().map(([r,s])=>{var n;return[((n=ge[r])==null?void 0:n.keyword)||ge[r],Cc(e,r,s)]}).filter(([r,s])=>r&&!Q.isNil(s)).fromPairs().thru(Oc(t)).value(),"mapColumnData"),Oc=i(t=>e=>({...e,...Ic(t,e)}),"setColumnType"),Ic=i((t,e)=>e.type==="ARRAY"?xc(t,e):e.type==="USER-DEFINED"?ke(t,e.udt_name):e.domain_name?ke(t,e.domain_name):ke(t,e.type),"getType"),xc=i((t,e)=>({...ke(t,e.udt_name.slice(1)),array_type:Q.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),ke=i((t,e)=>{switch(e){case"bigint":case"bigserial":case"smallint":case"integer":case"numeric":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"int8":return{type:"numeric",mode:"bigint"};case"int2":return{type:"numeric",mode:"smallint"};case"int4":return{type:"numeric",mode:"integer"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return Q.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),Lc=i((t,e)=>{let r=Q.first(e)||{};return t.map(s=>{if(s.type!=="json")return s;let n=r[s.name],a=Pc(n),o=qc(a);return{...s,subtype:o}})},"setSubtypeFromSampledJsonValues"),Pc=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),qc=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),Mc=i(t=>Q.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");Ln.exports={setDependencies:Nc,mapColumnData:Rc,setSubtypeFromSampledJsonValues:Lc}});var ye=_((Eh,Pn)=>{"use strict";var Dc=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],te=null,Fc=i(t=>{te=t.require("lodash")},"setDependencies"),Bc=i(t=>te.chain(t).toPairs().reject(([e,r])=>te.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),kc=i(t=>e=>{var r;return(r=te.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),Uc=i(t=>/\s|\W/.test(t)||te.includes(Dc,te.toUpper(t))?`"${t}"`:t,"wrapInQuotes");Pn.exports={clearEmptyPropertiesInObject:Bc,setDependencies:Fc,getColumnNameByPosition:kc,wrapInQuotes:Uc}});var Dn=_((Th,Mn)=>{"use strict";var{getColumnNameByPosition:Gc}=ye(),Nr=null,Qc=i(t=>{Nr=t.require("lodash")},"setDependencies"),qn=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Hc=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";case"p":return"PARTIAL";default:return""}},"prepareMatch"),jc=i((t,e,r,s)=>Nr.map(t,n=>({relationshipName:n.relationship_name,dbName:n.foreign_table_schema,parentCollection:n.foreign_table_name,parentField:n.foreign_columns,childDbName:r,childCollection:e,childField:Nr.map(n.table_columns_positions,Gc(s)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:qn(n.relationship_on_delete),relationshipOnUpdate:qn(n.relationship_on_update),relationshipMatch:Hc(n.relationship_match)}})),"prepareForeignKeys");Mn.exports={setDependencies:Qc,prepareForeignKeys:jc}});var kn=_((Ah,Bn)=>{"use strict";var Ue=null,Wc=i(t=>{Ue=t.require("lodash")},"setDependencies"),Fn=i(t=>Ue.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:Vc(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),Vc=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),zc=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),$c=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),Kc=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Jc=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:Fn(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:Ue.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:zc(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:Kc(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:$c(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),Yc=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:Ue.toLower(t.external_language),inputArgs:Fn(e),body:t.routine_definition}),"mapProcedureData");Bn.exports={setDependencies:Wc,mapFunctionData:Jc,mapProcedureData:Yc}});var jn=_((wh,Hn)=>{"use strict";var{clearEmptyPropertiesInObject:Ee,getColumnNameByPosition:Ge}=ye(),y=null,Zc=i(t=>{y=t.require("lodash")},"setDependencies"),Gn=i((t,e)=>{if(!t&&!e)return null;let r=Un(t),s=Un(e==null?void 0:e.toast_options),n=r.fillfactor,a=r.parallel_workers,o=r.autovacuum_enabled,c=Ee({vacuum_index_cleanup:r.vacuum_index_cleanup,vacuum_truncate:r.vacuum_truncate,autovacuum_vacuum_threshold:r.autovacuum_vacuum_threshold,autovacuum_vacuum_scale_factor:r.autovacuum_vacuum_scale_factor,autovacuum_vacuum_insert_threshold:r.autovacuum_vacuum_insert_threshold,autovacuum_vacuum_insert_scale_factor:r.autovacuum_vacuum_insert_scale_factor,autovacuum_analyze_threshold:r.autovacuum_analyze_threshold,autovacuum_analyze_scale_factor:r.autovacuum_analyze_scale_factor,autovacuum_vacuum_cost_delay:r.autovacuum_vacuum_cost_delay,autovacuum_vacuum_cost_limit:r.autovacuum_vacuum_cost_limit,autovacuum_freeze_min_age:r.autovacuum_freeze_min_age,autovacuum_freeze_max_age:r.autovacuum_freeze_max_age,autovacuum_freeze_table_age:r.autovacuum_freeze_table_age,autovacuum_multixact_freeze_min_age:r.autovacuum_multixact_freeze_min_age,autovacuum_multixact_freeze_max_age:r.autovacuum_multixact_freeze_max_age,autovacuum_multixact_freeze_table_age:r.autovacuum_multixact_freeze_table_age,log_autovacuum_min_duration:r.log_autovacuum_min_duration}),l=r.user_catalog_table,u=s.autovacuum_enabled,p=Ee({toast_tuple_target:r.toast_tuple_target,toast_vacuum_index_cleanup:s.vacuum_index_cleanup,toast_vacuum_truncate:s.vacuum_truncate,toast_autovacuum_vacuum_threshold:s.autovacuum_vacuum_threshold,toast_autovacuum_vacuum_scale_factor:s.autovacuum_vacuum_scale_factor,toast_autovacuum_vacuum_insert_threshold:s.autovacuum_vacuum_insert_threshold,toast_autovacuum_vacuum_insert_scale_factor:s.autovacuum_vacuum_insert_scale_factor,toast_autovacuum_vacuum_cost_delay:s.autovacuum_vacuum_cost_delay,toast_autovacuum_vacuum_cost_limit:s.autovacuum_vacuum_cost_limit,toast_autovacuum_freeze_min_age:s.autovacuum_freeze_min_age,toast_autovacuum_freeze_max_age:s.autovacuum_freeze_max_age,toast_autovacuum_freeze_table_age:s.autovacuum_freeze_table_age,toast_autovacuum_multixact_freeze_min_age:s.autovacuum_multixact_freeze_min_age,toast_autovacuum_multixact_freeze_max_age:s.autovacuum_multixact_freeze_max_age,toast_autovacuum_multixact_freeze_table_age:s.autovacuum_multixact_freeze_table_age,toast_log_autovacuum_min_duration:s.log_autovacuum_min_duration}),h={fillfactor:n,parallel_workers:a,autovacuum_enabled:o,autovacuum:y.isEmpty(c)?null:c,toast_autovacuum_enabled:u,toast:y.isEmpty(p)?null:p,user_catalog_table:l};return Ee(h)},"prepareStorageParameters"),Xc=i((t,e)=>{if(!t)return null;let r=eu(t),s=y.some(t.partition_attributes_positions,o=>o===0),n=s?"partitioning_expression":"compositePartitionKey",a=s?tu(t,e):y.map(t.partition_attributes_positions,Ge(e));return[{partitionMethod:r,partitionBy:s?"expression":"keys",[n]:a}]},"prepareTablePartition"),eu=i(t=>{switch(t.partition_method){case"h":return"HASH";case"l":return"LIST";case"r":return"RANGE";default:return""}},"getPartitionMethod"),tu=i((t,e)=>{let r=0,s=y.split(t.expressions,",");return y.chain(t.partition_attributes_positions).map(n=>{if(n===0){let a=s[r];return r++,a}return Ge(e)(n)}).join(",").value()},"getPartitionExpression"),Qn=i(t=>y.split(t,"="),"splitByEqualitySymbol"),ru=i(t=>y.find(t,{type:"json"}),"checkHaveJsonTypes"),su=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),nu=i((t,e,r)=>y.reduce(t,(s,n)=>{switch(n.constraint_type){case"c":return{...s,chkConstr:[...s.chkConstr,ou(n)]};case"p":return{...s,primaryKey:[...s.primaryKey,iu(n,e)]};case"u":return{...s,uniqueKey:[...s.uniqueKey,au(n,e,r)]};default:return s}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),iu=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:y.map(t.constraint_keys,Ge(e)),indexStorageParameters:y.join(t.storage_parameters,","),indexTablespace:t.tablespace}),"getPrimaryKeyConstraint"),au=i((t,e,r)=>{let s=y.find(r,a=>a.indexname===t.constraint_name),n=s!=null&&s.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"";return{constraintName:t.constraint_name,compositeUniqueKey:y.map(t.constraint_keys,Ge(e)),indexStorageParameters:y.join(t.storage_parameters,","),indexTablespace:t.tablespace,indexComment:t.description,...n&&{nullsDistinct:n}}},"getUniqueKeyConstraint"),ou=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,noInherit:t.no_inherit,constrDescription:t.description}),"getCheckConstraint"),cu=i(t=>y.map(t,e=>{let r=uu(e),s=y.slice(r,0,e.number_of_keys),n=y.chain(r).slice(e.number_of_keys).map(c=>y.pick(c,"name")).value(),a=e.index_indnullsnotdistinct?"NULLS NOT DISTINCT":"",o={indxName:e.indexname,index_method:e.index_method,unique:e.index_unique??!1,index_tablespace_name:e.tablespace_name||"",index_storage_parameter:pu(e.storage_parameters),where:e.where_expression||"",include:n,columns:e.index_method==="btree"?s:y.map(s,c=>y.omit(c,"sortOrder","nullsOrder")),...a&&{nullsDistinct:a}};return Ee(o)}),"prepareTableIndexes"),uu=i(t=>y.chain(t.columns).map((e,r)=>{if(!e)return;let s=y.get(t,`ascendings.${r}`,!1)?"ASC":"DESC",n=lu(y.get(t,`nulls_first.${r}`)),a=y.get(t,`opclasses.${r}`,""),o=y.get(t,`collations.${r}`,"");return{name:e,sortOrder:s,nullsOrder:n,opclass:a,collation:o}}).compact().value(),"mapIndexColumns"),lu=i(t=>y.isNil(t)?"":t?"NULLS FIRST":"NULLS LAST","getNullsOrder"),pu=i(t=>{if(!t)return null;let e=y.fromPairs(y.map(t,s=>Qn(s))),r={index_fillfactor:e.fillfactor,deduplicate_items:e.deduplicate_items,index_buffering:e.index_buffering,fastupdate:e.fastupdate,gin_pending_list_limit:e.gin_pending_list_limit,pages_per_range:e.pages_per_range,autosummarize:e.autosummarize};return Ee(r)},"getIndexStorageParameters"),hu=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",s=(t==null?void 0:t.relpersistence)==="u",n=Gn(t==null?void 0:t.reloptions,e),a=t==null?void 0:t.spcname,o=t.partition_expr;return{temporary:r,unlogged:s,storage_parameter:n,table_tablespace_name:a,partitionBounds:o}},"prepareTableLevelData"),_u=i(t=>{switch(du(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),du=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),Un=i(t=>y.chain(t).map(Qn).map(([e,r])=>[e,_u(r)]).fromPairs().value()||{},"prepareOptions"),fu=i((t,e)=>y.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");Hn.exports={prepareStorageParameters:Gn,prepareTablePartition:Xc,setDependencies:Zc,checkHaveJsonTypes:ru,prepareTableConstraints:nu,prepareTableLevelData:hu,prepareTableIndexes:cu,getSampleDocSize:su,prepareTableInheritance:fu}});var Vn=_((Ch,Wn)=>{"use strict";var{mapColumnData:mu}=wr(),M=null,gu=i(t=>{M=t.require("lodash")},"setDependencies"),yu=i((t,e)=>M.chain(t).map(r=>{switch(r.type){case"e":return Eu(r);case"r":return Su(r);case"c":return Tu(r);default:return null}}).compact().concat(M.map(e,Au)).value(),"getUserDefinedTypes"),Eu=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Su=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Tu=i(t=>{let e=M.map(t.columns,mu([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),bu=i(t=>t.type==="c","isTypeComposite"),Au=i(t=>{var e;return{name:t.domain_name,type:"domain",underlyingType:M.flow(wu(t),Nu(t),Cu(t),Ru(t))(vu(t)),collation:t.collation_name||"",default:t.domain_default||"",required:(e=M.first(t.constraints))==null?void 0:e.not_null,checkConstraints:M.map(t.constraints,Ou)}},"mapDomainType"),vu=i(t=>t.data_type==="USER-DEFINED"?t.udt_name:t.data_type,"getUnderlyingType"),wu=i(t=>e=>t.character_maximum_length?`${e}(${t.character_maximum_length})`:e,"setLength"),Nu=i(t=>e=>e!=="numeric"?e:M.isNumber(t.numeric_precision)&&M.isNumber(t.numeric_scale)?`${e}(${t.numeric_precision},${t.numeric_scale})`:M.isNumber(t.numeric_precision)?`${e}(${t.numeric_precision})`:e,"setPrecisionAndScale"),Cu=i(t=>e=>t.interval_type?`${e} ${t.interval_type}`:e,"setIntervalType"),Ru=i(t=>e=>M.isNumber(t.interval_precision)?`${e}(${t.interval_precision})`:e,"setIntervalPrecision"),Ou=i(t=>({name:t.constraint_name,expression:t.expression}),"mapDomainConstraint");Wn.exports={setDependencies:gu,getUserDefinedTypes:yu,isTypeComposite:bu}});var $n=_((Oh,zn)=>{"use strict";var{clearEmptyPropertiesInObject:Iu,wrapInQuotes:xu}=ye(),k=null,Lu=i(t=>{k=t.require("lodash")},"setDependencies"),Cr=" (v)",Pu=i(t=>t==="VIEW","isViewByTableType"),qu=i(t=>k.endsWith(t,Cr),"isViewByName"),Mu=i(t=>t.slice(0,-Cr.length),"removeViewNameSuffix"),Du=i(t=>`${t}${Cr}`,"setViewSuffix"),Fu=i((t,e,r={})=>{let s=k.trim(e.view_definition||r.definition||"");return s?`CREATE VIEW ${xu(t)} AS ${s}`:""},"generateCreateViewScript"),Bu=i((t,e,r)=>{let s={withCheckOption:t.check_option!=="NONE"||k.isNil(t.check_option),checkTestingScope:ku(t.check_option),viewOptions:k.fromPairs(k.map(e==null?void 0:e.view_options,Gu)),temporary:(e==null?void 0:e.persistence)==="t",recursive:Uu(t),description:e==null?void 0:e.description,triggers:r};return Iu(s)},"prepareViewData"),ku=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),Uu=i(t=>k.startsWith(k.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),Gu=i(t=>k.split(t,"="),"splitByEqualitySymbol");zn.exports={setDependencies:Lu,isViewByTableType:Pu,isViewByName:qu,removeViewNameSuffix:Mu,generateCreateViewScript:Fu,setViewSuffix:Du,prepareViewData:Bu}});var Jn=_((xh,Kn)=>{"use strict";var Qe=null,Qu=i(t=>{Qe=t.require("lodash")},"setDependencies"),Hu=i((t,e)=>Qe.chain(t).map(r=>({...r,...Qe.find(e,{trigger_name:r.trigger_name})||{}})).map(ju).value(),"getTriggers"),ju=i(t=>{var e;return{name:t.trigger_name,triggerDescription:t.description,triggerConstraint:t.constraint,triggerTable:`${t.event_object_schema}.${t.event_object_table}`,triggerReferencedTable:t.referenced_table_name?[t.referenced_table_schema,t.referenced_table_name]:[],triggerType:t.action_timing,triggerEvents:Wu(t),triggerUpdateColumns:(e=t.update_attributes)==null?void 0:e.filter(Boolean),triggerDeferrable:t.deferrable,triggerTimeConstraintCheck:t.deferred?"INITIALLY DEFERRED":"INITIALLY IMMEDIATE",triggerReferencing:!!t.action_reference_old_table||!!t.action_reference_new_table,triggerBeforeImageTransitionRelation:t.action_reference_old_table||"",triggerAfterImageTransitionRelation:t.action_reference_new_table||"",triggerEachRowStatement:t.action_orientation==="ROW"?"FOR EACH ROW":"FOR EACH STATEMENT",triggerCondition:t.action_condition,triggerFunction:Vu(t.action_statement)}},"getTrigger"),Wu=i(t=>Qe.map(t.trigger_events,e=>({triggerEvent:e})),"getTriggerEvents"),Vu=i(t=>{var e,r,s;return((s=(r=(e=/EXECUTE (?:FUNCTION|PROCEDURE)(?[\s\S]*)/.exec(t))==null?void 0:e.groups)==null?void 0:r.function)==null?void 0:s.trim())||""},"getFunctionFromTrigger");Kn.exports={setDependencies:Qu,getTriggers:Hu}});var Xn=_((Ph,Zn)=>{"use strict";var zu=i((t,e)=>[$u,Ku].reduce(({attributes:r,entityLevel:s},n)=>n(r,s),{attributes:t,entityLevel:e}),"reorganizeConstraints"),$u=i((t,e)=>{var a,o,c;if(((c=(o=(a=e.primaryKey)==null?void 0:a[0])==null?void 0:o.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let s=e.primaryKey[0],n=s.compositePrimaryKey[0];return{attributes:Ju(t,n,s),entityLevel:el(e)}},"reorganizePrimaryKeys"),Ku=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:s},n)=>{if(!(n.compositeUniqueKey.length===1))return{attributes:r,entityLevel:s};let o=n.compositeUniqueKey[0];return{attributes:Zu(r,o,n),entityLevel:tl(s,n)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Ju=i((t,e,r)=>t.map(s=>s.name!==e?s:Yu(s,r)),"setAttributesPrimaryKeyData"),Yu=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:Yn(e)}),"setPrimaryKeyData"),Zu=i((t,e,r)=>t.map(s=>s.name!==e?s:Xu(s,r)),"setAttributesUniqueKeyData"),Xu=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:Yn(e)}),"setUniqueKeyData"),Yn=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexTablespace:t.indexTablespace,indexComment:t.indexComment}],"getOptions"),el=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),tl=i((t,e)=>{let r=t.uniqueKey.filter(s=>s.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Zn.exports={reorganizeConstraints:zu}});var ti=_((Mh,ei)=>{"use strict";var Ir=class Ir{cache;cycle;dataType;ifNotExist;increment;maxValue;minValue;ownedByColumn;ownedByNone;sequenceName;start;temporary;unlogged};i(Ir,"Sequence");var Rr=Ir,xr=class xr{sequence_name;increment;start;data_type;maximum_value;minimum_value;cycle_option;cache_size;rel_persistance;column_name;table_name};i(xr,"SequenceDto");var Or=xr;ei.exports={Sequence:Rr,SequenceDto:Or}});var si=_((kh,ri)=>{"use strict";var{Sequence:Fh,SequenceDto:Bh}=ti(),rl=i(({sequence:t})=>t.column_name?[{entity:t.table_name,name:t.column_name}]:[],"getOwnedByColumn"),sl=i(({sequence:t})=>({sequenceName:t.sequence_name,increment:Number(t.increment),start:Number(t.start_value),dataType:t.data_type,maxValue:Number(t.maximum_value),minValue:Number(t.minimum_value),cache:Number(t.cache_size),temporary:t.rel_persistance==="t",unlogged:t.rel_persistance==="u",cycle:t.cycle_option==="YES",ownedByColumn:rl({sequence:t}),ownedByNone:!t.column_name}),"mapSequenceData");ri.exports={mapSequenceData:sl}});var oi=_((Gh,ai)=>{"use strict";var{createClient:nl}=An(),m=Rn(),{getJsonSchema:ni}=xn(),{setDependencies:il,mapColumnData:al,setSubtypeFromSampledJsonValues:ol}=wr(),{setDependencies:cl,clearEmptyPropertiesInObject:ii}=ye(),{setDependencies:ul,prepareForeignKeys:ll}=Dn(),{setDependencies:pl,mapFunctionData:hl,mapProcedureData:_l}=kn(),{setDependencies:dl,prepareTablePartition:fl,checkHaveJsonTypes:ml,prepareTableConstraints:gl,getSampleDocSize:yl,prepareTableLevelData:El,prepareTableIndexes:Sl,prepareTableInheritance:Tl}=jn(),{setDependencies:bl,getUserDefinedTypes:Al,isTypeComposite:vl}=Vn(),{setDependencies:wl,isViewByTableType:Nl,isViewByName:Cl,removeViewNameSuffix:Rl,generateCreateViewScript:Ol,setViewSuffix:Il,prepareViewData:xl}=$n(),{setDependencies:Ll,getTriggers:Pl}=Jn(),g=vr(),{reorganizeConstraints:ql}=Xn(),{mapSequenceData:Ml}=si(),Lr=!1,A=null,L=null,Pr=14;ai.exports={setDependencies(t){A=t.require("lodash"),cl(t),dl(t),il(t),ul(t),wl(t),pl(t),bl(t),Ll(t)},async connect(t,e,r){m.isClientInitialized()&&await this.disconnect(e);let{client:s,isSshTunnel:n}=await nl(t,e,r);m.initializeClient(s,r),Lr=n,L=r,Pr=await this._getServerVersion()},async disconnect(t){Lr&&(Lr=!1,await t.closeConsumer()),await m.releaseClient()},pingDb(){return m.query(g.PING)},applyScript(t){return m.query(t)},async getDatabaseNames(){return A.map(await m.query(g.GET_DATABASES),"database_name")},async logVersion(){let t=await m.queryTolerant(g.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved";L.info(`PostgreSQL version: ${e}`)},async getAllSchemasNames(){return(await m.query(g.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!Dl(e))},async getTablesNames(t){let e=await m.query(g.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:s})=>!A.includes(r,s)).map(({table_name:s,table_type:n})=>Nl(n)?Il(s):s)},async getDbLevelData(){var s,n,a;L.progress("Get database data");let t=(s=await m.queryTolerant(g.GET_DB_NAME,[],!0))==null?void 0:s.current_database,e=(n=await m.queryTolerant(g.GET_DB_ENCODING,[],!0))==null?void 0:n.server_encoding,r=(a=await m.queryTolerant(g.GET_DB_COLLATE_NAME,[],!0))==null?void 0:a.default_collate_name;return ii({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r,s=!1,n=!1){let a=await this._retrieveUserDefinedTypes(t),o=await m.queryTolerant(g.GET_NAMESPACE_OID,[t],!0),c=o==null?void 0:o.oid,l=s?await m.queryTolerant(g.GET_PARTITIONS,[c]):[],[u,p]=A.partition(e,Cl),h=p.flatMap(w=>[{tableName:w},...A.filter(l,{parent_name:w}).map(({child_name:O,is_parent_partitioned:D})=>({isParentPartitioned:D,tableName:O}))]),d=await re(A.uniq(h),A.bind(this._retrieveSingleTableData,this,r,c,t,a,n));return{views:await re(u,A.bind(this._retrieveSingleViewData,this,c,t,n)),tables:d,modelDefinitions:ni(a)}},async retrieveSchemaLevelData(t,e){var h;if(e)return L.info("Functions and procedures ignored"),{functions:[],procedures:[]};L.progress("Get Functions and Procedures",t);let r=(h=await m.queryTolerant(g.GET_NAMESPACE_OID,[t],!0))==null?void 0:h.oid,s=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES,[t]),n=await m.queryTolerant(Bl(Pr),[r]),[a,o]=A.partition(A.filter(s,"routine_type"),{routine_type:"FUNCTION"}),c=await re(a,async d=>{let E=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[d.specific_name]),w=A.find(n,{function_name:d.name});return hl(d,E,w)}),l=await re(o,async d=>{let E=await m.queryTolerant(g.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[d.specific_name]),w=A.find(n,{function_name:d.name});return _l(d,E,w)}),p=(await m.queryTolerant(g.GET_SEQUENCES,[t])).map(d=>Ml({sequence:d}));return{functions:c,procedures:l,sequences:p}},async _retrieveUserDefinedTypes(t){L.progress("Get User-Defined Types",t);let e=await m.queryTolerant(g.GET_USER_DEFINED_TYPES,[t]),r=await m.queryTolerant(g.GET_DOMAIN_TYPES,[t]),s=await re(e,async a=>vl(a)?{...a,columns:await m.queryTolerant(g.GET_COMPOSITE_TYPE_COLUMNS,[a.pg_class_oid])}:a),n=await re(r,async a=>({...a,constraints:await m.queryTolerant(g.GET_DOMAIN_TYPES_CONSTRAINTS,[a.domain_name,t])}));return Al(s,n)},async _retrieveSingleTableData(t,e,r,s,n,{tableName:a,isParentPartitioned:o}){var Mr;L.progress("Get table data",r,a);let c=await m.queryTolerant(g.GET_TABLE_LEVEL_DATA,[a,e],!0),l=c==null?void 0:c.oid,u=await m.queryTolerant(g.GET_TABLE_TOAST_OPTIONS,[a,e],!0),p=await m.queryTolerant(g.GET_TABLE_PARTITION_DATA,[l],!0),h=await this._getTableColumns(a,r,l),d=await m.queryTolerant(g.GET_DESCRIPTION_BY_OID,[l],!0),E=await m.queryTolerant(g.GET_INHERITS_PARENT_TABLE_NAME,[l]),w=await m.queryTolerant(g.GET_TABLE_CONSTRAINTS,[l]),O=await m.queryTolerant(Fl(Pr),[l]),D=await m.queryTolerant(g.GET_TABLE_FOREIGN_KEYS,[l]),se=await this._getTriggers(r,a,e,l,n);L.info("Table data retrieved",{schemaName:r,tableName:a,columnTypes:h.map(_i=>_i.data_type)});let ne=fl(p,h),je=El(c,u),We=kl(d),Se=Tl(r,E),Ve=gl(w,h,O),Te=Sl(O),F=ll(D,a,r,h),ci={partitioning:ne,description:We,triggers:se,Indxs:Te,...je,...Ve,...o?{partitionOf:(Mr=A.first(Se))==null?void 0:Mr.parentTable}:{inherits:Se}},ui=ii(ci),ie=h.map(al(s)),li=ml(ie),ze=[];li&&(ze=await this._getDocuments(r,a,ie,t),ie=ol(ie,ze));let{attributes:pi,entityLevel:hi}=ql(ie,ui);return{name:a,entityLevel:hi,jsonSchema:ni(pi),documents:ze,relationships:F}},async _getTriggers(t,e,r,s,n){if(n)return L.info("Triggers ignored"),[];let a=await m.queryTolerant(g.GET_TRIGGERS,[t,e]),o=await m.queryTolerant(g.GET_TRIGGERS_ADDITIONAL_DATA,[r,s]);return Pl(a,o)},async _getTableColumns(t,e,r){L.progress("Get columns",e,t);let s=await m.query(g.GET_TABLE_COLUMNS,[t,e]),n=await m.queryTolerant(g.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return A.map(s,a=>({...a,...A.find(n,{name:a.column_name})||{}}))},async _getDocuments(t,e,r,s){var p;L.progress("Sampling table",t,e);let n=`${t}.${e}`,a=((p=await m.queryTolerant(g.GET_ROWS_COUNT(n),[],!0))==null?void 0:p.quantity)||0,o=yl(a,s),c=r.filter(({type:h})=>A.includes(["json","jsonb"],h)),l=A.map(c,"name").join(", "),u=await m.queryTolerant(g.GET_SAMPLED_DATA_SIZE(n,l),[o],!0);return L.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:u==null?void 0:u._hackolade_tmp_sampling_tbl_size}),await m.queryTolerant(g.GET_SAMPLED_DATA(n,l),[o])},async _retrieveSingleViewData(t,e,r,s){L.progress("Get view data",e,s),s=Rl(s);let n=await m.query(g.GET_VIEW_DATA,[s,e],!0),a=!n.view_definition&&await m.queryTolerant(g.GET_VIEW_SELECT_STMT_FALLBACK,[s,e],!0),o=await m.queryTolerant(g.GET_VIEW_OPTIONS,[s,t],!0),c=await this._getTriggers(e,s,t,o==null?void 0:o.oid,r),l=Ol(s,n,a),u=xl(n,o,c);return l?{name:s,data:u,ddl:{script:l,type:"postgres"}}:(L.info("View select statement was not retrieved",{schemaName:e,viewName:s}),{name:s,data:u,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await m.queryTolerant(g.GET_VERSION_AS_NUM,[],!0),e=A.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var Dl=i(t=>!!(A.startsWith(t,"pg_")||A.includes(["information_schema"],t)),"isSystemSchema"),Fl=i(t=>t===10?g.GET_TABLE_INDEXES_V_10:t>15?g.GET_TABLE_INDEXES_V_15:g.GET_TABLE_INDEXES,"getGetIndexesQuery"),Bl=i(t=>t===10?g.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:g.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),kl=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),re=i((t,e)=>Promise.all(A.map(t,e)),"mapPromises")});var{createLogger:He}=Fr(),v=oi();module.exports={async disconnect(t,e,r,s){let n=s.require("@hackolade/ssh-service");await v.disconnect(n),r()},async testConnection(t,e,r,s){let n=s.require("@hackolade/ssh-service");try{qr("Test connection",t,e);let a=He({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});v.setDependencies(s),await v.connect(t,n,a),await v.pingDb(),await v.logVersion(),r()}catch(a){e.log("error",W(a),"Test connection instance log"),r(W(a))}finally{await v.disconnect(n)}},async getDatabases(t,e,r,s){let n=s.require("@hackolade/ssh-service");try{qr("Get databases",t,e);let a=He({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});v.setDependencies(s),await v.connect(t,n,a),await v.logVersion();let o=await v.getDatabaseNames();return e.log("info",o,"All databases list",t.hiddenKeys),r(null,o)}catch(a){return e.log("error",a),r(W(a))}},getDocumentKinds:function(t,e,r){r(null,[])},async getDbCollectionsNames(t,e,r,s){let n=s.require("@hackolade/ssh-service");try{qr("Get DB table names",t,e);let a=He({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});v.setDependencies(s),await v.connect(t,n,a),await v.logVersion();let c=await(await v.getAllSchemasNames()).reduce(async(l,u)=>{let p=await l;try{let h=await v.getTablesNames(u);return p.concat({dbName:u,dbCollections:h,isEmpty:h.length===0})}catch(h){return a.info(`Error reading database "${u}"`),a.error(h),p.concat({dbName:u,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,c)}catch(a){e.log("error",W(a),"Get DB collections names"),r(W(a)),await v.disconnect(n)}},async getDbCollectionsData(t,e,r,s){let n=s.require("@hackolade/ssh-service");try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let a=He({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});a.progress("Start reverse engineering...");let o=t.collectionData.collections,c=t.collectionData.dataBaseNames,l=await v.getDbLevelData(),{packages:u,relationships:p}=await Promise.all(c.map(async h=>{let{tables:d,views:E,modelDefinitions:w}=await v.retrieveEntitiesData(h,o[h],t.recordSamplingSettings,t.includePartitions,t.ignoreUdfUdpTriggers),{functions:O,procedures:D,triggers:se,sequences:ne}=await v.retrieveSchemaLevelData(h,t.ignoreUdfUdpTriggers);return a.progress("Schema data fetched successfully",h),{schemaName:h,tables:d,views:E,functions:O,procedures:D,modelDefinitions:w,triggers:se,sequences:ne}})).then(h=>{let d=h.flatMap(({tables:w})=>w.map(O=>O.relationships)).flat();return{packages:h.flatMap(({schemaName:w,tables:O,views:D,functions:se,procedures:ne,triggers:je,modelDefinitions:We,sequences:Se})=>{let Ve={UDFs:se,Procedures:ne,triggers:je,sequences:Se},Te=O.map(F=>({dbName:w,collectionName:F.name,documents:F.documents,views:[],emptyBucket:!1,entityLevel:F.entityLevel,validation:{jsonSchema:F.jsonSchema},bucketInfo:Ve,modelDefinitions:We})).sort(F=>s.require("lodash").isEmpty(F.entityLevel.inherits)?-1:1);if(D!=null&&D.length){let F={dbName:w,views:D,emptyBucket:!1};return[...Te,F]}return Te}),relationships:d}}).then(({packages:h,relationships:d})=>({packages:Ul(h),relationships:d}));a.info("The data is processed and sent to the application",{packagesLength:u==null?void 0:u.length,relationshipsLength:p==null?void 0:p.length}),r(null,u,l,p)}catch(a){e.log("error",W(a),"Retrieve tables data"),r(W(a))}finally{await v.disconnect(n)}}};var W=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),qr=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),Ul=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages"); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c5275b0 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "outDir": "./tscDist", + "allowJs": true, + "checkJs": false, + "target": "ES2016", + "lib": ["ESNext", "DOM"], + "sourceMap": true, + "jsx": "react-jsx", + "moduleResolution": "node", + "experimentalDecorators": true, + "noUnusedParameters": true, + "noUnusedLocals": true, + "noImplicitThis": true, + "noImplicitAny": false, + "alwaysStrict": true, + "skipLibCheck": true, + "module": "ESNext", + "strict": true, + "useUnknownInCatchVariables": true, + "allowSyntheticDefaultImports": true, + "isolatedModules": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "typeRoots": ["./node_modules/@types", "./types"] + }, + "include": ["reverse_engineering", "forward_engineering"], + "exclude": ["**/node_modules/**", "release/**/*"] +} diff --git a/types/geometry.json b/types/geometry.json index 0cb6a78..016c04c 100644 --- a/types/geometry.json +++ b/types/geometry.json @@ -11,8 +11,6 @@ "foreignCollection": "", "foreignField": [], "dependencies": [], - "minProperties": "", - "maxProperties": "", "additionalProperties": false, "enum": [] },