hysteria-orm 10.7.4 → 10.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,19 +1,19 @@
1
- 'use strict';var Se=require('crypto'),We=require('dayjs'),Up=require('dayjs/plugin/customParseFormat.js'),Vp=require('dayjs/plugin/timezone.js'),Jp=require('dayjs/plugin/utc.js'),up=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),It=require('path'),Sf=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Se__default=/*#__PURE__*/_interopDefault(Se);var We__default=/*#__PURE__*/_interopDefault(We);var Up__default=/*#__PURE__*/_interopDefault(Up);var Vp__default=/*#__PURE__*/_interopDefault(Vp);var Jp__default=/*#__PURE__*/_interopDefault(Jp);var up__default=/*#__PURE__*/_interopDefault(up);var It__default=/*#__PURE__*/_interopDefault(It);var Sf__default=/*#__PURE__*/_interopDefault(Sf);var Lp=Object.defineProperty;var rl=i=>{throw TypeError(i)};var ee=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var ol=(i,t,e,r)=>{for(var o=void 0,n=i.length-1,s;n>=0;n--)(s=i[n])&&(o=(s(t,e,o))||o);return o&&Lp(t,e,o),o};var Wr=(i,t,e)=>t.has(i)||rl("Cannot "+e);var Le=(i,t,e)=>(Wr(i,t,"read from private field"),e?e.call(i):t.get(i)),Dt=(i,t,e)=>t.has(i)?rl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Fr=(i,t,e,r)=>(Wr(i,t,"write to private field"),t.set(i,e),e),nl=(i,t,e)=>(Wr(i,t,"access private method"),e);var k=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};k.store=new WeakMap;var jr=Symbol("mongoProperties");function Ur(){return (i,t)=>{let e=k.getMetadata(jr,i)||[];e.push(t),k.defineMetadata(jr,e,i);}}function sl(i){return k.getMetadata(jr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function Fp(i){return typeof i!="string"||!i?i:i.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function jp(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function L(i,t){return t==="preserve"?i:t==="snake"?Fp(i):t==="camel"?jp(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}We__default.default.extend(Jp__default.default);We__default.default.extend(Vp__default.default);We__default.default.extend(Up__default.default);var oe=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=We__default.default(i);if(e==="LOCAL"){let n=r.local();switch(t){case "ISO":return n.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return n.format("YYYY-MM-DD");case "TIME_ONLY":return n.format("HH:mm:ss");default:return n.unix().toString()}}let o=r.utc();switch(t){case "ISO":return o.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return o.format("YYYY-MM-DD");case "TIME_ONLY":return o.format("HH:mm:ss");default:return o.unix().toString()}},ct=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new f("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?We__default.default(i,t):We__default.default(i);if(!r.isValid())throw new f("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new f("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},He=(i=new Date)=>We__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var il=(i,t)=>{try{let e=Se__default.default.createHash("sha256").update(i).digest(),r=Se__default.default.randomBytes(16),o=Se__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},al=(i,t)=>{try{let e=Se__default.default.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=Se__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),d=l.update(a,"hex","utf8");return d+=l.final("utf8"),d}catch(e){throw new f("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},ll=(i,t)=>{try{let e=Se__default.default.randomBytes(32),r=Se__default.default.randomBytes(16),o=Se__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=Se.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},dl=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=Se.privateDecrypt(i,Buffer.from(o,"hex")),a=Se__default.default.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new f("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var Jr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Vr=Jr.length,Gp=10,Zp=16,Xp=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Vr;e=Jr.charAt(o)+e,i=(i-o)/Vr;}return e},ef=i=>{let t=Se.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Jr.charAt(o%Vr);}return e},ul=()=>{let i=Math.floor(Date.now()/1e3),t=Xp(i,Gp),e=ef(Zp);return t+e};function Hr(i){return i.replace(/^[`"]|[`"]$/g,"")}function zr(i,t,e){if(!i.includes(".")){let n=Hr(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=Hr(r),o=Hr(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function S(i){return typeof i=="function"?i():i}var J=(i,t=new WeakMap)=>{if(i===null||typeof i!="object")return i;if(t.has(i))return t.get(i);if(Array.isArray(i)){let r=[];t.set(i,r);for(let o=0;o<i.length;o++)r[o]=J(i[o],t);return r}let e=Object.create(Object.getPrototypeOf(i)||{});t.set(i,e);for(let r of Object.getOwnPropertyNames(i)){let o=i[r];if(typeof o=="function"){e[r]=o;continue}e[r]=J(o,t);}return e};var Oe=class{};Oe.modelCaseConvention="camel",Oe.databaseCaseConvention="snake";var cl;cl=Symbol.toStringTag;var U=class{constructor(t,e,r){this.unWrapFn=t;this.toQueryFn=e;this.executor=r;this[cl]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}unWrap(){return this.unWrapFn()}};var tf=async(i,t,e,r,o=[],n=false)=>{let s=Object.create(t.prototype),a=new Set(e.filter(c=>c.hidden).map(c=>c.columnName)),l=new Map(e.map(c=>[c.databaseName,c])),d=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async c=>{let p=i[c],u=l.get(c)?.columnName??c,m=r.has(u),y=a.has(u),g=n?true:d?d.has(u):true;if(m){if(y||!g)return;if(p===null){s[u]=null;return}let T=r.get(u);if(T&&T.serialize){s[u]=await T.serialize(p);return}s[u]=p;return}(!n||d&&d.has(u))&&(s[u]=p);})),d)for(let c of d)c in s||(s[c]=null);return s},be=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumns(),o=new Map(r.map(l=>[l.columnName,l])),n=e.some(l=>l.includes("*")),s=[];for(let l of e){if(l.toLowerCase().includes(" as ")){let u=l.match(/\s+as\s+(.+)$/i);u&&s.push(u[1].trim());continue}let c=l;if(c.includes(".")&&(c=c.split(".").pop()),c==="*")continue;let p=o.get(c)?.columnName??c;s.push(p);}e=s;let a=await Promise.all(i.map(async l=>await tf(l,t,r,o,e,n)));return a.length===1?a[0]:a};var Q=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Pt={string:"string",varchar:"string",char:"string",text:"textarea",longtext:"textarea",mediumtext:"textarea",tinytext:"textarea",integer:"number",int:"number",smallint:"number",bigint:"number",tinyint:"number",mediumint:"number",float:"float",double:"float",decimal:"float",numeric:"float",real:"float",boolean:"boolean",bool:"boolean",date:"date",datetime:"datetime",timestamp:"datetime",time:"string",year:"number",json:"mixed",jsonb:"mixed",uuid:"string",ulid:"string",binary:"string",blob:"string",enum:"string"};var pl=null;function ml(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let o=e.getColumns();for(let[n,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=o.find(p=>p.columnName===n||p.databaseName===n);if(!l)continue;let d=typeof l.type=="string"?l.type:"string",c=Pt[d]||"string";if(c==="string"||c==="textarea"){i.whereLike(n,`%${a}%`);continue}if(c==="boolean"){i.where(n,a==="true"||a===true);continue}if(c==="date"||c==="datetime"){if(typeof a=="object"&&a!==null){let p=a;p.from&&i.where(n,">=",p.from),p.to&&i.where(n,"<=",p.to);continue}i.where(n,a);continue}i.where(n,a);}}function mt(i,t){let e={},r=t.getColumns();for(let o of r){let n=i[o.columnName];e[o.columnName]=n;}return e}async function rf(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=pl;}static isAdapterFor(n){if(typeof n!="function")return false;let s=n;return s.prototype!==void 0&&typeof s.table=="string"&&typeof s.getColumns=="function"}databaseName(){return this._db.database||"hysteria"}databaseType(){return this._db.getDbType()}id(){return this._model.table}properties(){return this._model.getColumns().map(s=>{let a=typeof s.type=="string"?s.type:"string",l=Pt[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(c=>c.columnName===n||c.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",d=Pt[l]||"string";return new r({path:a.columnName,type:d,isId:a.isPrimary,isSortable:true})}async count(n){let s=this._model.query({connection:this._db});return ml(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return ml(a,n,this._model),s.limit&&a.limit(s.limit),s.offset&&a.offset(s.offset),s.sort?.sortBy&&a.orderBy(s.sort.sortBy,s.sort.direction||"asc"),(await a.many()).map(d=>new e(mt(d,this._model),this))}async findOne(n){if(!this._model.primaryKey)return null;let a=await this._model.findOneByPrimaryKey(n,{connection:this._db});return a?new e(mt(a,this._model),this):null}async findMany(n){let s=this._model.primaryKey;return s?(await this._model.query({connection:this._db}).whereIn(s,n).many()).map(l=>new e(mt(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db,returning:["*"]});return mt(s,this._model)}async update(n,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=await this._model.findOneByPrimaryKey(n,{connection:this._db});if(!l)throw new Error("Record not found");let d=await this._model.updateRecord(l,s,{connection:this._db});return mt(d,this._model)}async delete(n){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=await this._model.findOneByPrimaryKey(n,{connection:this._db});a&&await this._model.deleteRecord(a,{connection:this._db});}}}async function of(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function nf(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),t=await rf(),e=await of();i.default.registerAdapter({Database:e,Resource:t});}async function Yr(i,t){pl=i;let e=await import('adminjs').catch(()=>{throw new Q("adminjs")});await nf();let r=t.resources||Object.values(i.models);if(!r.length)throw new Error("No models provided for AdminJS. Please provide models in the resources option or register them in SqlDataSource.");let o=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),n={rootPath:t.rootPath||"/admin",resources:o};if(t.branding&&(n.branding=t.branding),t.locale?.language&&(n.locale=t.locale),t.assets&&(n.assets=t.assets),t.settings&&(n.settings=t.settings),t.pages){let a={};for(let[l,d]of Object.entries(t.pages))d.component&&(a[l]=d);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function fl(i,t){let{admin:e}=await Yr(i,t),r;try{r=await import('@adminjs/express');}catch{throw new Q("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var ze=new Map,Ae=new Map,$t=class{async get(t){return ze.get(t)}async set(t,e,r){let o=Ae.get(t);if(o&&(clearTimeout(o),Ae.delete(t)),ze.set(t,e),r){let n=setTimeout(()=>{ze.delete(t),Ae.delete(t);},r);Ae.set(t,n);}}async invalidate(t){let e=Ae.get(t);e&&(clearTimeout(e),Ae.delete(t)),ze.delete(t);}async invalidateAll(t){let e=ze.keys();for(let r of e)if(r.startsWith(t)){let o=Ae.get(r);o&&(clearTimeout(o),Ae.delete(r)),ze.delete(r);}}};var E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},af=()=>{try{up__default.default.readFileSync(".env","utf8").split(`
2
- `).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":E.DB_TYPE||(E.DB_TYPE=s);break;case "DB_HOST":E.DB_HOST||(E.DB_HOST=s);break;case "DB_PORT":E.DB_PORT||(E.DB_PORT=s);break;case "DB_USER":E.DB_USER||(E.DB_USER=s);break;case "DB_PASSWORD":E.DB_PASSWORD||(E.DB_PASSWORD=s);break;case "DB_DATABASE":E.DB_DATABASE||(E.DB_DATABASE=s);break;case "MIGRATION_PATH":E.MIGRATION_PATH||(E.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":E.REDIS_HOST||(E.REDIS_HOST=s);break;case "REDIS_PORT":E.REDIS_PORT||(E.REDIS_PORT=s);break;case "REDIS_USERNAME":E.REDIS_USERNAME||(E.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":E.REDIS_PASSWORD||(E.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":E.REDIS_DATABASE||(E.REDIS_DATABASE=s);break;case "MONGO_URL":E.MONGO_URL||(E.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":E.MSSQL_TRUST_SERVER_CERTIFICATE||(E.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return E}},A=af();var yl={info:0,warn:1,error:2};function Et(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function df(i,t="info"){let e=Et(i);if(!e)return false;let r=e.level??"info";return yl[t]>=yl[r]}function uf(i){let t=Et(i);return t?t.logQueries??true:false}var Ye={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function cf(){let i=new Date,t=e=>e.toString().padStart(2,"0");return `${i.getFullYear()}-${t(i.getMonth()+1)}-${t(i.getDate())} ${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}`}function Gr(i,t){let e=cf(),r=i.toUpperCase();return i==="error"?`${Ye.error}[${r}] ${e}
3
- ${t}${Ye.reset}
4
- `:i==="warn"?`${Ye.warn}[${r}] ${e}
5
- ${t}${Ye.reset}
6
- `:i==="info"?`${Ye.info}[${r}] ${e}
7
- ${t}${Ye.reset}
1
+ 'use strict';var qe=require('crypto'),je=require('dayjs'),Gp=require('dayjs/plugin/customParseFormat.js'),Zp=require('dayjs/plugin/timezone.js'),Xp=require('dayjs/plugin/utc.js'),wp=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),Pt=require('path'),Of=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var qe__default=/*#__PURE__*/_interopDefault(qe);var je__default=/*#__PURE__*/_interopDefault(je);var Gp__default=/*#__PURE__*/_interopDefault(Gp);var Zp__default=/*#__PURE__*/_interopDefault(Zp);var Xp__default=/*#__PURE__*/_interopDefault(Xp);var wp__default=/*#__PURE__*/_interopDefault(wp);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var Of__default=/*#__PURE__*/_interopDefault(Of);var Jp=Object.defineProperty;var ml=i=>{throw TypeError(i)};var re=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var pl=(i,t,e,r)=>{for(var o=void 0,n=i.length-1,s;n>=0;n--)(s=i[n])&&(o=(s(t,e,o))||o);return o&&Jp(t,e,o),o};var zr=(i,t,e)=>t.has(i)||ml("Cannot "+e);var Fe=(i,t,e)=>(zr(i,t,"read from private field"),e?e.call(i):t.get(i)),$t=(i,t,e)=>t.has(i)?ml("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Yr=(i,t,e,r)=>(zr(i,t,"write to private field"),t.set(i,e),e),fl=(i,t,e)=>(zr(i,t,"access private method"),e);var k=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};k.store=new WeakMap;var Gr=Symbol("mongoProperties");function Zr(){return (i,t)=>{let e=k.getMetadata(Gr,i)||[];e.push(t),k.defineMetadata(Gr,e,i);}}function yl(i){return k.getMetadata(Gr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function zp(i){return typeof i!="string"||!i?i:i.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Yp(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function L(i,t){return t==="preserve"?i:t==="snake"?zp(i):t==="camel"?Yp(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}je__default.default.extend(Xp__default.default);je__default.default.extend(Zp__default.default);je__default.default.extend(Gp__default.default);var se=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=je__default.default(i);if(e==="LOCAL"){let n=r.local();switch(t){case "ISO":return n.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return n.format("YYYY-MM-DD");case "TIME_ONLY":return n.format("HH:mm:ss");default:return n.unix().toString()}}let o=r.utc();switch(t){case "ISO":return o.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return o.format("YYYY-MM-DD");case "TIME_ONLY":return o.format("HH:mm:ss");default:return o.unix().toString()}},pt=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new f("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?je__default.default(i,t):je__default.default(i);if(!r.isValid())throw new f("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new f("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},Ye=(i=new Date)=>je__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var hl=(i,t)=>{try{let e=qe__default.default.createHash("sha256").update(i).digest(),r=qe__default.default.randomBytes(16),o=qe__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},gl=(i,t)=>{try{let e=qe__default.default.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=qe__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),d=l.update(a,"hex","utf8");return d+=l.final("utf8"),d}catch(e){throw new f("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},bl=(i,t)=>{try{let e=qe__default.default.randomBytes(32),r=qe__default.default.randomBytes(16),o=qe__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=qe.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Tl=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=qe.privateDecrypt(i,Buffer.from(o,"hex")),a=qe__default.default.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new f("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var eo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Xr=eo.length,of=10,nf=16,sf=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Xr;e=eo.charAt(o)+e,i=(i-o)/Xr;}return e},af=i=>{let t=qe.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=eo.charAt(o%Xr);}return e},wl=()=>{let i=Math.floor(Date.now()/1e3),t=sf(i,of),e=af(nf);return t+e};function to(i){return i.replace(/^[`"]|[`"]$/g,"")}function ro(i,t,e){if(!i.includes(".")){let n=to(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=to(r),o=to(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function S(i){return typeof i=="function"?i():i}var z=(i,t=new WeakMap)=>{if(i===null||typeof i!="object")return i;if(t.has(i))return t.get(i);if(Array.isArray(i)){let r=[];t.set(i,r);for(let o=0;o<i.length;o++)r[o]=z(i[o],t);return r}let e=Object.create(Object.getPrototypeOf(i)||{});t.set(i,e);for(let r of Object.getOwnPropertyNames(i)){let o=i[r];if(typeof o=="function"){e[r]=o;continue}e[r]=z(o,t);}return e};var xe=class{};xe.modelCaseConvention="camel",xe.databaseCaseConvention="snake";var Nl;Nl=Symbol.toStringTag;var V=class{constructor(t,e,r){this.unWrapFn=t;this.toQueryFn=e;this.executor=r;this[Nl]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}unWrap(){return this.unWrapFn()}};var lf=async(i,t,e,r,o=[],n=false)=>{let s=Object.create(t.prototype),a=new Set(e.filter(c=>c.hidden).map(c=>c.columnName)),l=new Map(e.map(c=>[c.databaseName,c])),d=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async c=>{let p=i[c],u=l.get(c)?.columnName??c,m=r.has(u),y=a.has(u),g=n?true:d?d.has(u):true;if(m){if(y||!g)return;if(p===null){s[u]=null;return}let T=r.get(u);if(T&&T.serialize){s[u]=await T.serialize(p);return}s[u]=p;return}(!n||d&&d.has(u))&&(s[u]=p);})),d)for(let c of d)c in s||(s[c]=null);return s},we=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumns(),o=new Map(r.map(l=>[l.columnName,l])),n=e.some(l=>l.includes("*")),s=[];for(let l of e){if(l.toLowerCase().includes(" as ")){let u=l.match(/\s+as\s+(.+)$/i);u&&s.push(u[1].trim());continue}let c=l;if(c.includes(".")&&(c=c.split(".").pop()),c==="*")continue;let p=o.get(c)?.columnName??c;s.push(p);}e=s;let a=await Promise.all(i.map(async l=>await lf(l,t,r,o,e,n)));return a.length===1?a[0]:a};var Q=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Et={string:"string",varchar:"string",char:"string",text:"textarea",longtext:"textarea",mediumtext:"textarea",tinytext:"textarea",integer:"number",int:"number",smallint:"number",bigint:"number",tinyint:"number",mediumint:"number",float:"float",double:"float",decimal:"float",numeric:"float",real:"float",boolean:"boolean",bool:"boolean",date:"date",datetime:"datetime",timestamp:"datetime",time:"string",year:"number",json:"mixed",jsonb:"mixed",uuid:"string",ulid:"string",binary:"string",blob:"string",enum:"string"};var Cl=null;function Sl(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let o=e.getColumns();for(let[n,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=o.find(p=>p.columnName===n||p.databaseName===n);if(!l)continue;let d=typeof l.type=="string"?l.type:"string",c=Et[d]||"string";if(c==="string"||c==="textarea"){i.whereLike(n,`%${a}%`);continue}if(c==="boolean"){i.where(n,a==="true"||a===true);continue}if(c==="date"||c==="datetime"){if(typeof a=="object"&&a!==null){let p=a;p.from&&i.where(n,">=",p.from),p.to&&i.where(n,"<=",p.to);continue}i.where(n,a);continue}i.where(n,a);}}function ft(i,t){let e={},r=t.getColumns();for(let o of r){let n=i[o.columnName];e[o.columnName]=n;}return e}async function df(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Cl;}static isAdapterFor(n){if(typeof n!="function")return false;let s=n;return s.prototype!==void 0&&typeof s.table=="string"&&typeof s.getColumns=="function"}databaseName(){return this._db.database||"hysteria"}databaseType(){return this._db.getDbType()}id(){return this._model.table}properties(){return this._model.getColumns().map(s=>{let a=typeof s.type=="string"?s.type:"string",l=Et[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(c=>c.columnName===n||c.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",d=Et[l]||"string";return new r({path:a.columnName,type:d,isId:a.isPrimary,isSortable:true})}async count(n){let s=this._model.query({connection:this._db});return Sl(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return Sl(a,n,this._model),s.limit&&a.limit(s.limit),s.offset&&a.offset(s.offset),s.sort?.sortBy&&a.orderBy(s.sort.sortBy,s.sort.direction||"asc"),(await a.many()).map(d=>new e(ft(d,this._model),this))}async findOne(n){if(!this._model.primaryKey)return null;let a=await this._model.findOneByPrimaryKey(n,{connection:this._db});return a?new e(ft(a,this._model),this):null}async findMany(n){let s=this._model.primaryKey;return s?(await this._model.query({connection:this._db}).whereIn(s,n).many()).map(l=>new e(ft(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db,returning:["*"]});return ft(s,this._model)}async update(n,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=await this._model.findOneByPrimaryKey(n,{connection:this._db});if(!l)throw new Error("Record not found");let d=await this._model.updateRecord(l,s,{connection:this._db});return ft(d,this._model)}async delete(n){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=await this._model.findOneByPrimaryKey(n,{connection:this._db});a&&await this._model.deleteRecord(a,{connection:this._db});}}}async function uf(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function cf(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),t=await df(),e=await uf();i.default.registerAdapter({Database:e,Resource:t});}async function oo(i,t){Cl=i;let e=await import('adminjs').catch(()=>{throw new Q("adminjs")});await cf();let r=t.resources||Object.values(i.models);if(!r.length)throw new Error("No models provided for AdminJS. Please provide models in the resources option or register them in SqlDataSource.");let o=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),n={rootPath:t.rootPath||"/admin",resources:o};if(t.branding&&(n.branding=t.branding),t.locale?.language&&(n.locale=t.locale),t.assets&&(n.assets=t.assets),t.settings&&(n.settings=t.settings),t.pages){let a={};for(let[l,d]of Object.entries(t.pages))d.component&&(a[l]=d);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function ql(i,t){let{admin:e}=await oo(i,t),r;try{r=await import('@adminjs/express');}catch{throw new Q("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var Ge=new Map,De=new Map,Bt=class{async get(t){return Ge.get(t)}async set(t,e,r){let o=De.get(t);if(o&&(clearTimeout(o),De.delete(t)),Ge.set(t,e),r){let n=setTimeout(()=>{Ge.delete(t),De.delete(t);},r);De.set(t,n);}}async invalidate(t){let e=De.get(t);e&&(clearTimeout(e),De.delete(t)),Ge.delete(t);}async invalidateAll(t){let e=Ge.keys();for(let r of e)if(r.startsWith(t)){let o=De.get(r);o&&(clearTimeout(o),De.delete(r)),Ge.delete(r);}}};var E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},pf=()=>{try{wp__default.default.readFileSync(".env","utf8").split(`
2
+ `).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":E.DB_TYPE||(E.DB_TYPE=s);break;case "DB_HOST":E.DB_HOST||(E.DB_HOST=s);break;case "DB_PORT":E.DB_PORT||(E.DB_PORT=s);break;case "DB_USER":E.DB_USER||(E.DB_USER=s);break;case "DB_PASSWORD":E.DB_PASSWORD||(E.DB_PASSWORD=s);break;case "DB_DATABASE":E.DB_DATABASE||(E.DB_DATABASE=s);break;case "MIGRATION_PATH":E.MIGRATION_PATH||(E.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":E.REDIS_HOST||(E.REDIS_HOST=s);break;case "REDIS_PORT":E.REDIS_PORT||(E.REDIS_PORT=s);break;case "REDIS_USERNAME":E.REDIS_USERNAME||(E.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":E.REDIS_PASSWORD||(E.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":E.REDIS_DATABASE||(E.REDIS_DATABASE=s);break;case "MONGO_URL":E.MONGO_URL||(E.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":E.MSSQL_TRUST_SERVER_CERTIFICATE||(E.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return E}},x=pf();var Ml={info:0,warn:1,error:2};function vt(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function yf(i,t="info"){let e=vt(i);if(!e)return false;let r=e.level??"info";return Ml[t]>=Ml[r]}function hf(i){let t=vt(i);return t?t.logQueries??true:false}var Ze={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function gf(){let i=new Date,t=e=>e.toString().padStart(2,"0");return `${i.getFullYear()}-${t(i.getMonth()+1)}-${t(i.getDate())} ${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}`}function no(i,t){let e=gf(),r=i.toUpperCase();return i==="error"?`${Ze.error}[${r}] ${e}
3
+ ${t}${Ze.reset}
4
+ `:i==="warn"?`${Ze.warn}[${r}] ${e}
5
+ ${t}${Ze.reset}
6
+ `:i==="info"?`${Ze.info}[${r}] ${e}
7
+ ${t}${Ze.reset}
8
8
  `:`[${r}] ${e}
9
9
  ${t}
10
- `}var Ge=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){if(t instanceof Error){this.loggerInstance.error(String(t));return}this.loggerInstance.error(t);}static warn(t){this.loggerInstance.warn(t);}};Ge.loggerInstance={info(t){console.log(Gr("info",t));},error(t){console.error(Gr("error",t));},warn(t){console.warn(Gr("warn",t));}};function mf(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function te(i,t,e){if(!uf(t))return;i=sqlHighlight.highlight(i,{colors:{keyword:"\x1B[34m",string:"\x1B[32m",number:"\x1B[33m",bracket:"\x1B[36m",clear:"\x1B[0m",comment:"\x1B[90m",function:"\x1B[35m",identifier:"\x1B[37m",special:"\x1B[31m"}});let r=`${i} [${mf(e||[])}]`;Ge.loggerInstance.info(r);}function hl(i,t,e=false){df(e,t)&&Ge.loggerInstance[t](i);}var q=Ge;var Ze=class{constructor(t){switch(this.type=t?.type||A.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;case "oracledb":this.handleOracleDBSource(t);break;default:throw new f(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
11
- Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=Et(this.logs);e?.customLogger&&q.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||A.DB_HOST,this.port=+t?.port||+A.DB_PORT,this.username=t?.username||A.DB_USER,this.password=t?.password||A.DB_PASSWORD,this.database=t?.database||A.DB_DATABASE,this.logs=t?.logs||A.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||A.DB_HOST,this.port=+t?.port||+A.DB_PORT,this.username=t?.username||A.DB_USER,this.password=t?.password||A.DB_PASSWORD,this.database=t?.database||A.DB_DATABASE,this.logs=t?.logs||A.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||A.DB_HOST,this.port=+t?.port||+A.DB_PORT,this.username=t?.username||A.DB_USER,this.password=t?.password||A.DB_PASSWORD,this.database=t?.database||A.DB_DATABASE,this.logs=t?.logs||A.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||A.DB_DATABASE||":memory:",this.logs=t?.logs||A.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||A.MONGO_URL,this.logs=t?.logs||A.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||A.DB_HOST,this.port=+t?.port||+A.DB_PORT,this.username=t?.username||A.DB_USER,this.password=t?.password||A.DB_PASSWORD,this.database=t?.database||A.DB_DATABASE,this.logs=t?.logs||A.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||A.DB_HOST,this.port=+t?.port||+A.DB_PORT,this.username=t?.username||A.DB_USER,this.password=t?.password||A.DB_PASSWORD,this.database=t?.database||A.DB_DATABASE,this.logs=t?.logs||A.DB_LOGS||false,this.port||(this.port=1521);}};var pf=i=>{let{required:t,...e}=i.openApi||{},r={...e,type:i.openApi?.type||"string",description:i.openApi?.description??`Property: ${i.columnName}`};return i.openApi?.type?{...r,type:i.openApi.type}:Array.isArray(i.type)?{...r,type:"string",enum:i.type}:i.type==="date"||i.type==="datetime"||i.type==="timestamp"||i.type==="time"?{...r,type:"string",format:"date-time"}:i.type==="boolean"?{...r,type:"boolean"}:i.type==="integer"||i.type==="tinyint"||i.type==="smallint"||i.type==="mediumint"||i.type==="increment"?{...r,type:"integer",format:"int32"}:i.type==="biginteger"||i.type==="bigIncrement"?{...r,type:"integer",format:"int64"}:i.type==="float"||i.type==="real"?{...r,type:"number",format:"float"}:i.type==="double"?{...r,type:"number",format:"double"}:i.type==="decimal"||i.type==="numeric"?{...r,type:"number"}:i.type==="json"||i.type==="jsonb"?{...r,type:"object"}:i.type==="uuid"?{...r,type:"string",format:"uuid"}:i.type==="ulid"?{...r,type:"string",format:"ulid"}:i.type==="string"||i.type==="char"||i.type==="varchar"||i.type==="text"||i.type==="longtext"||i.type==="mediumtext"||i.type==="tinytext"?{...r,type:"string"}:i.type==="blob"||i.type==="binary"||i.type==="varbinary"||i.type==="tinyblob"||i.type==="mediumblob"||i.type==="longblob"?{...r,type:"string",format:"binary"}:i.type==="year"?{...r,type:"integer",format:"int32"}:r},ff=i=>i.openApi?.required??false,yf=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=pf(r));return e},hf=i=>{let t=i.getColumns(),e=[];for(let r of t)ff(r)&&e.push(r.columnName);return e||[]},Zr=i=>{let t=yf(i),e=hf(i);return {type:"object",properties:t,required:e.length?e:[]}},dh=i=>i.map(t=>Zr(t)),uh=i=>Zr(i),gl=i=>i.map(t=>({...Zr(t),modelName:t.name,$id:t.name}));var Xr=(i,t)=>{let e=Se__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var eo=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},Bt=i=>{if(i==null)return "NULL";if(i instanceof Date)return `'${i.toISOString()}'`;let t=typeof i;return t==="boolean"?i?"TRUE":"FALSE":t==="number"&&Number.isFinite(i)||t==="bigint"?String(i):t==="string"?`'${i.replace(/'/g,"''")}'`:Array.isArray(i)||t==="object"&&Object.keys(i).length>0?`'${JSON.stringify(i).replace(/'/g,"''")}'`:String(i)},Xe=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,Bt(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,Bt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,Bt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,Bt(t[r]));}return e},et=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,xe=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:eo(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var to=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Tl=new to;var ro=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},wl=new ro;var oo=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},Nl=new oo;var no=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a="";e.options.nullable!==void 0&&(a=e.options.nullable?" null":" not null");let l=`alter column [${e.column}] ${s}${a}`;if(e.options.dropDefault&&(l=`drop constraint DF_${e.column}, ${l}`),e.options.default!==void 0&&!e.options.dropDefault){let d=e.options.default;d===null?d="null":typeof d=="string"&&(d==="NULL"?d="null":d==="TRUE"||d==="FALSE"?d=d==="TRUE"?"1":"0":d=`'${d}'`),l+=`, add constraint DF_${e.column} default ${d} for [${e.column}]`;}return e.options.unique!==void 0&&e.options.unique&&(l+=`, add constraint UQ_${e.column} unique ([${e.column}])`),{sql:l,bindings:[]}}},Sl=new no;var w=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var tt=class extends w{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var bf=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},h=class{constructor(t){this.model=t;let e=vt(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??L(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??L(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a!=="*"&&(o.push(a),n.push(l));}await Promise.all(o.map(async(s,a)=>{let l=o[a],d=n[a],c=this.modelColumnsMap.get(l),p=d;c?r==="insert"&&c.prepare?p=await c.prepare(d):r==="update"&&(p=await c.prepare?.(d)??d):bf(d)&&(p=JSON.stringify(d)),n[a]=p;}));for(let s of this.modelColumnsMap.keys())if(!o.includes(s)){let a=this.modelColumnsMap.get(s);if(!a||r==="insert"&&s===this.model.primaryKey&&!a.prepare)continue;if(r==="insert"||a.autoUpdate){o.push(s);let l=a.prepare?await a.prepare(void 0):void 0;n.push(l??void 0);}}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var so=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};if(e.children.length===1&&e.children[0]instanceof tt){let c=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${c.newName}'`,bindings:[]}}let n=new b(this.model,"mssql"),s=[],a=[];for(let c of e.children){let{sql:p,bindings:u}=n.parse([c]);s.push(p.trim()),a.push(...u);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},ql=new so;var io=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Ml=new io;var ao=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},Cl=new ao;var lo=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},Rl=new lo;var uo=class{toSql(t){let e=t;return q.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},_l=new uo;var co=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Ol=new co;var mo=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Al=new mo;var po=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},xl=new po;var x=class extends w{constructor(e){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e;}};var fo=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue==="NULL"||e.defaultValue===null?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="1"&&e.defaultValue!=="0"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`add constraint DF_${e.column} default ${r} for [${e.column}]`,bindings:[]}}},Il=new fo;var yo=class{toSql(t){let e=t;return q.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},Dl=new yo;var ho=class{toSql(t){return {sql:"",bindings:[]}}},Pl=new ho;var go=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("mssql",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} varchar(max)`,bindings:[]};if(n==="uuid")return {sql:`${o} uniqueidentifier`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigint identity(1,1)`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} tinyint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} int`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} float`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} decimal(${s}, ${a})`,bindings:[]}}if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}if(n==="datetime"||n==="timestamp"){let s=typeof e.precision=="number"?`(${e.precision})`:"",a=`${o} datetime2${s}`;return e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}if(n==="boolean"||n==="bool")return {sql:`${o} bit`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} varbinary(max)`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} nvarchar(max)`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar(255)`,bindings:[]}}return n==="integer"||n==="int"?e.autoIncrement?{sql:`${o} int identity(1,1)`,bindings:[]}:{sql:`${o} int`,bindings:[]}:n==="geometry"?{sql:`${o} geometry`,bindings:[]}:n==="point"?{sql:`${o} geometry`,bindings:[]}:n==="linestring"?{sql:`${o} geometry`,bindings:[]}:n==="polygon"?{sql:`${o} geometry`,bindings:[]}:n==="multipoint"?{sql:`${o} geometry`,bindings:[]}:{sql:`${o} ${n}${e.length?`(${e.length})`:""}`,bindings:[]}}},$l=new go;var bo=class{toSql(t){return {sql:"",bindings:[]}}},El=new bo;var To=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint [${e.constraintName}] `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("mssql",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint [${e.constraintName}] `:"",s=o.map(a=>r.formatStringColumn("mssql",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof x?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("mssql",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mssql",S(d))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint [${e.constraintName}] `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Bl=new To;var wo=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mssql"),s=[],a=[];for(let y of e.children){let{sql:g,bindings:T}=n.parse([y]);if(y.folder==="constraint"){let N=s.pop()??"",M=g;if(/not null/i.test(M)||/null/i.test(M)||/default/i.test(M)){let O=`${N} ${M}`.trim();O=O.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(O),a.push(...T);continue}s.push(N),s.push(M),a.push(...T);continue}s.push(g),a.push(...T);}for(let y of e.namedConstraints){let{sql:g,bindings:T}=n.parse([y]);s.push(g),a.push(...T);}let l=s.join(", "),d=[];e.dataCompression&&d.push(`DATA_COMPRESSION = ${e.dataCompression}`);let c=e.onFilegroup?` ON [${e.onFilegroup}]`:"",p=e.textImageOn?` TEXTIMAGE_ON [${e.textImageOn}]`:"",u=d.length>0?` WITH (${d.join(", ")})`:"";return {sql:`${o} (${l})${u}${c}${p}`,bindings:a}}},vl=new wo;var No=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mssql",e.fromNode),bindings:[]}}},kl=new No;var So=class{toSql(t){return {sql:"",bindings:[]}}},Ql=new So;var qo=class{toSql(t){return q.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},Kl=new qo;var Mo=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Ll=new Mo;var Co=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Wl=new Co;var Ro=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mssql",e.table)} as [${e.alias}]`,bindings:[]}:{sql:a.formatStringTable("mssql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mssql").parse(r),s=e.alias&&e.alias.length?` as [${e.alias}]`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Fl=new Ro;var _o=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},jl=new _o;var Oo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} @${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`@${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Ul=new Oo;var Ao=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table),n=e.columns.map(a=>`[${a}]`).join(", ");return {sql:`${e.unique?"unique ":""}[${e.indexName}] on ${o} (${n})`,bindings:[]}}},Vl=new Ao;var xo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},Jl=new xo;var Io=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n).filter(u=>n[u]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("mssql",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g of m)g instanceof x?y.push(g.rawValue):(l.push(g),y.push(`@${c++}`));d.push(`(${y.join(", ")})`);}let p=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let u=e.returning.map(m=>`inserted.${r.formatStringColumn("mssql",m)}`).join(", ");p=p.replace(") values",`) output ${u} values`);}else {let u=this.getOutputColumns(s,r);p=p.replace(") values",`) output ${u} values`);}return {sql:p,bindings:l}}getOutputColumns(t,e){let r=[...t],o=this.model.primaryKey;return o&&!t.includes(o)&&r.push(o),r.map(n=>`inserted.${e.formatStringColumn("mssql",n)}`).join(", ")}},Hl=new Io;var Do=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mssql",o),a=r.formatStringColumn("mssql",n),d=`${r.formatStringTable("mssql",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"mssql");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},zl=new Do;var Po=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},Yl=new Po;var $o=class{toSql(t){return {sql:"",bindings:[]}}},Gl=new $o;var Eo=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},Zl=new Eo;var Bo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(q.warn("MSSQL does not support ON CONFLICT or ON DUPLICATE KEY. Use MERGE statement for upsert operations. This clause will be ignored. Consider using raw queries for MSSQL upserts."),{sql:"",bindings:[]})}},Xl=new Bo;var vo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("mssql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},ed=new vo;var ko=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},td=new ko;var Qo=class{toSql(t){return {sql:`SELECT
10
+ `}var Xe=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){if(t instanceof Error){this.loggerInstance.error(String(t));return}this.loggerInstance.error(t);}static warn(t){this.loggerInstance.warn(t);}};Xe.loggerInstance={info(t){console.log(no("info",t));},error(t){console.error(no("error",t));},warn(t){console.warn(no("warn",t));}};function bf(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function oe(i,t,e){if(!hf(t))return;i=sqlHighlight.highlight(i,{colors:{keyword:"\x1B[34m",string:"\x1B[32m",number:"\x1B[33m",bracket:"\x1B[36m",clear:"\x1B[0m",comment:"\x1B[90m",function:"\x1B[35m",identifier:"\x1B[37m",special:"\x1B[31m"}});let r=`${i} [${bf(e||[])}]`;Xe.loggerInstance.info(r);}function Rl(i,t,e=false){yf(e,t)&&Xe.loggerInstance[t](i);}var q=Xe;var et=class{constructor(t){switch(this.type=t?.type||x.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;case "oracledb":this.handleOracleDBSource(t);break;default:throw new f(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
11
+ Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=vt(this.logs);e?.customLogger&&q.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||x.DB_HOST,this.port=+t?.port||+x.DB_PORT,this.username=t?.username||x.DB_USER,this.password=t?.password||x.DB_PASSWORD,this.database=t?.database||x.DB_DATABASE,this.logs=t?.logs||x.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||x.DB_HOST,this.port=+t?.port||+x.DB_PORT,this.username=t?.username||x.DB_USER,this.password=t?.password||x.DB_PASSWORD,this.database=t?.database||x.DB_DATABASE,this.logs=t?.logs||x.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||x.DB_HOST,this.port=+t?.port||+x.DB_PORT,this.username=t?.username||x.DB_USER,this.password=t?.password||x.DB_PASSWORD,this.database=t?.database||x.DB_DATABASE,this.logs=t?.logs||x.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||x.DB_DATABASE||":memory:",this.logs=t?.logs||x.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||x.MONGO_URL,this.logs=t?.logs||x.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||x.DB_HOST,this.port=+t?.port||+x.DB_PORT,this.username=t?.username||x.DB_USER,this.password=t?.password||x.DB_PASSWORD,this.database=t?.database||x.DB_DATABASE,this.logs=t?.logs||x.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||x.DB_HOST,this.port=+t?.port||+x.DB_PORT,this.username=t?.username||x.DB_USER,this.password=t?.password||x.DB_PASSWORD,this.database=t?.database||x.DB_DATABASE,this.logs=t?.logs||x.DB_LOGS||false,this.port||(this.port=1521);}};var Tf=i=>{let{required:t,...e}=i.openApi||{},r={...e,type:i.openApi?.type||"string",description:i.openApi?.description??`Property: ${i.columnName}`};return i.openApi?.type?{...r,type:i.openApi.type}:Array.isArray(i.type)?{...r,type:"string",enum:i.type}:i.type==="date"||i.type==="datetime"||i.type==="timestamp"||i.type==="time"?{...r,type:"string",format:"date-time"}:i.type==="boolean"?{...r,type:"boolean"}:i.type==="integer"||i.type==="tinyint"||i.type==="smallint"||i.type==="mediumint"||i.type==="increment"?{...r,type:"integer",format:"int32"}:i.type==="biginteger"||i.type==="bigIncrement"?{...r,type:"integer",format:"int64"}:i.type==="float"||i.type==="real"?{...r,type:"number",format:"float"}:i.type==="double"?{...r,type:"number",format:"double"}:i.type==="decimal"||i.type==="numeric"?{...r,type:"number"}:i.type==="json"||i.type==="jsonb"?{...r,type:"object"}:i.type==="uuid"?{...r,type:"string",format:"uuid"}:i.type==="ulid"?{...r,type:"string",format:"ulid"}:i.type==="string"||i.type==="char"||i.type==="varchar"||i.type==="text"||i.type==="longtext"||i.type==="mediumtext"||i.type==="tinytext"?{...r,type:"string"}:i.type==="blob"||i.type==="binary"||i.type==="varbinary"||i.type==="tinyblob"||i.type==="mediumblob"||i.type==="longblob"?{...r,type:"string",format:"binary"}:i.type==="year"?{...r,type:"integer",format:"int32"}:r},wf=i=>i.openApi?.required??false,Nf=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=Tf(r));return e},Sf=i=>{let t=i.getColumns(),e=[];for(let r of t)wf(r)&&e.push(r.columnName);return e||[]},so=i=>{let t=Nf(i),e=Sf(i);return {type:"object",properties:t,required:e.length?e:[]}},Nh=i=>i.map(t=>so(t)),Sh=i=>so(i),_l=i=>i.map(t=>({...so(t),modelName:t.name,$id:t.name}));var io=(i,t)=>{let e=qe__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var ao=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},kt=i=>{if(i==null)return "NULL";if(i instanceof Date)return `'${i.toISOString()}'`;let t=typeof i;return t==="boolean"?i?"TRUE":"FALSE":t==="number"&&Number.isFinite(i)||t==="bigint"?String(i):t==="string"?`'${i.replace(/'/g,"''")}'`:Array.isArray(i)||t==="object"&&Object.keys(i).length>0?`'${JSON.stringify(i).replace(/'/g,"''")}'`:String(i)},tt=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,kt(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}return e},rt=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,Ie=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:ao(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var lo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Al=new lo;var uo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},xl=new uo;var co=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},Dl=new co;var mo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a="";e.options.nullable!==void 0&&(a=e.options.nullable?" null":" not null");let l=`alter column [${e.column}] ${s}${a}`;if(e.options.dropDefault&&(l=`drop constraint DF_${e.column}, ${l}`),e.options.default!==void 0&&!e.options.dropDefault){let d=e.options.default;d===null?d="null":typeof d=="string"&&(d==="NULL"?d="null":d==="TRUE"||d==="FALSE"?d=d==="TRUE"?"1":"0":d=`'${d}'`),l+=`, add constraint DF_${e.column} default ${d} for [${e.column}]`;}return e.options.unique!==void 0&&e.options.unique&&(l+=`, add constraint UQ_${e.column} unique ([${e.column}])`),{sql:l,bindings:[]}}},Il=new mo;var w=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var ot=class extends w{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var qf=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},h=class{constructor(t){this.model=t;let e=Qt(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??L(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??L(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a!=="*"&&(o.push(a),n.push(l));}await Promise.all(o.map(async(s,a)=>{let l=o[a],d=n[a],c=this.modelColumnsMap.get(l),p=d;c?r==="insert"&&c.prepare?p=await c.prepare(d):r==="update"&&(p=await c.prepare?.(d)??d):qf(d)&&(p=JSON.stringify(d)),n[a]=p;}));for(let s of this.modelColumnsMap.keys())if(!o.includes(s)){let a=this.modelColumnsMap.get(s);if(!a||r==="insert"&&s===this.model.primaryKey&&!a.prepare)continue;if(r==="insert"||a.autoUpdate){o.push(s);let l=a.prepare?await a.prepare(void 0):void 0;n.push(l??void 0);}}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var po=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};if(e.children.length===1&&e.children[0]instanceof ot){let c=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${c.newName}'`,bindings:[]}}let n=new b(this.model,"mssql"),s=[],a=[];for(let c of e.children){let{sql:p,bindings:u}=n.parse([c]);s.push(p.trim()),a.push(...u);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Pl=new po;var fo=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},$l=new fo;var yo=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},El=new yo;var ho=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},Bl=new ho;var go=class{toSql(t){let e=t;return q.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},vl=new go;var bo=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},kl=new bo;var To=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Ql=new To;var wo=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},Kl=new wo;var D=class extends w{constructor(e){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e;}};var No=class{toSql(t){let e=t,r;return e.defaultValue instanceof D?r=e.defaultValue.rawValue:e.defaultValue==="NULL"||e.defaultValue===null?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="1"&&e.defaultValue!=="0"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`add constraint DF_${e.column} default ${r} for [${e.column}]`,bindings:[]}}},Ll=new No;var So=class{toSql(t){let e=t;return q.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},Wl=new So;var Co=class{toSql(t){return {sql:"",bindings:[]}}},Fl=new Co;var qo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("mssql",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} varchar(max)`,bindings:[]};if(n==="uuid")return {sql:`${o} uniqueidentifier`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigint identity(1,1)`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} tinyint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} int`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} float`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} decimal(${s}, ${a})`,bindings:[]}}if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}if(n==="datetime"||n==="timestamp"){let s=typeof e.precision=="number"?`(${e.precision})`:"",a=`${o} datetime2${s}`;return e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}if(n==="boolean"||n==="bool")return {sql:`${o} bit`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} varbinary(max)`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} nvarchar(max)`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar(255)`,bindings:[]}}return n==="integer"||n==="int"?e.autoIncrement?{sql:`${o} int identity(1,1)`,bindings:[]}:{sql:`${o} int`,bindings:[]}:n==="geometry"?{sql:`${o} geometry`,bindings:[]}:n==="point"?{sql:`${o} geometry`,bindings:[]}:n==="linestring"?{sql:`${o} geometry`,bindings:[]}:n==="polygon"?{sql:`${o} geometry`,bindings:[]}:n==="multipoint"?{sql:`${o} geometry`,bindings:[]}:{sql:`${o} ${n}${e.length?`(${e.length})`:""}`,bindings:[]}}},jl=new qo;var Mo=class{toSql(t){return {sql:"",bindings:[]}}},Ul=new Mo;var Ro=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint [${e.constraintName}] `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("mssql",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint [${e.constraintName}] `:"",s=o.map(a=>r.formatStringColumn("mssql",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof D?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("mssql",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mssql",S(d))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint [${e.constraintName}] `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Vl=new Ro;var _o=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mssql"),s=[],a=[];for(let y of e.children){let{sql:g,bindings:T}=n.parse([y]);if(y.folder==="constraint"){let N=s.pop()??"",M=g;if(/not null/i.test(M)||/null/i.test(M)||/default/i.test(M)){let A=`${N} ${M}`.trim();A=A.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(A),a.push(...T);continue}s.push(N),s.push(M),a.push(...T);continue}s.push(g),a.push(...T);}for(let y of e.namedConstraints){let{sql:g,bindings:T}=n.parse([y]);s.push(g),a.push(...T);}let l=s.join(", "),d=[];e.dataCompression&&d.push(`DATA_COMPRESSION = ${e.dataCompression}`);let c=e.onFilegroup?` ON [${e.onFilegroup}]`:"",p=e.textImageOn?` TEXTIMAGE_ON [${e.textImageOn}]`:"",u=d.length>0?` WITH (${d.join(", ")})`:"";return {sql:`${o} (${l})${u}${c}${p}`,bindings:a}}},Jl=new _o;var Oo=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mssql",e.fromNode),bindings:[]}}},Hl=new Oo;var Ao=class{toSql(t){return {sql:"",bindings:[]}}},zl=new Ao;var xo=class{toSql(t){return q.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},Yl=new xo;var Do=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Gl=new Do;var Io=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Zl=new Io;var Po=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mssql",e.table)} as [${e.alias}]`,bindings:[]}:{sql:a.formatStringTable("mssql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mssql").parse(r),s=e.alias&&e.alias.length?` as [${e.alias}]`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Xl=new Po;var $o=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},ed=new $o;var Eo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} @${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`@${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},td=new Eo;var Bo=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mssql",e.table),n=e.columns.map(a=>`[${a}]`).join(", ");return {sql:`${e.unique?"unique ":""}[${e.indexName}] on ${o} (${n})`,bindings:[]}}},rd=new Bo;var vo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},od=new vo;var ko=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n).filter(u=>n[u]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("mssql",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g of m)g instanceof D?y.push(g.rawValue):(l.push(g),y.push(`@${c++}`));d.push(`(${y.join(", ")})`);}let p=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let u=e.returning.map(m=>`inserted.${r.formatStringColumn("mssql",m)}`).join(", ");p=p.replace(") values",`) output ${u} values`);}else {let u=this.getOutputColumns(s,r);p=p.replace(") values",`) output ${u} values`);}return {sql:p,bindings:l}}getOutputColumns(t,e){let r=[...t],o=this.model.primaryKey;return o&&!t.includes(o)&&r.push(o),r.map(n=>`inserted.${e.formatStringColumn("mssql",n)}`).join(", ")}},nd=new ko;var Qo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mssql",o),a=r.formatStringColumn("mssql",n),d=`${r.formatStringTable("mssql",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"mssql");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},sd=new Qo;var Ko=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},id=new Ko;var Lo=class{toSql(t){return {sql:"",bindings:[]}}},ad=new Lo;var Wo=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},ld=new Wo;var Fo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(q.warn("MSSQL does not support ON CONFLICT or ON DUPLICATE KEY. Use MERGE statement for upsert operations. This clause will be ignored. Consider using raw queries for MSSQL upserts."),{sql:"",bindings:[]})}},dd=new Fo;var jo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("mssql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},ud=new jo;var Uo=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},cd=new Uo;var Vo=class{toSql(t){return {sql:`SELECT
12
12
  cc.name AS name,
13
13
  cc.definition AS expression
14
14
  FROM sys.check_constraints cc
15
15
  JOIN sys.tables t ON cc.parent_object_id = t.object_id
16
- WHERE t.name = '${t.table}'`,bindings:[]}}},rd=new Qo;var Ko=class{toSql(t){return {sql:`SELECT
16
+ WHERE t.name = '${t.table}'`,bindings:[]}}},md=new Vo;var Jo=class{toSql(t){return {sql:`SELECT
17
17
  fk.name as name,
18
18
  c.name as column_name,
19
19
  rt.name as referenced_table,
@@ -25,7 +25,7 @@ INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_i
25
25
  INNER JOIN sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
26
26
  INNER JOIN sys.tables rt ON fkc.referenced_object_id = rt.object_id
27
27
  INNER JOIN sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
28
- WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},od=new Ko;var Lo=class{toSql(t){return {sql:`SELECT
28
+ WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},pd=new Jo;var Ho=class{toSql(t){return {sql:`SELECT
29
29
  i.name as index_name,
30
30
  c.name as column_name,
31
31
  i.is_unique as is_unique
@@ -34,7 +34,7 @@ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = i
34
34
  INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
35
35
  WHERE i.object_id = OBJECT_ID('${t.table}')
36
36
  AND i.is_primary_key = 0
37
- AND i.type > 0`,bindings:[]}}},nd=new Lo;var Wo=class{toSql(t){return {sql:`SELECT
37
+ AND i.type > 0`,bindings:[]}}},fd=new Ho;var zo=class{toSql(t){return {sql:`SELECT
38
38
  tc.CONSTRAINT_NAME as name,
39
39
  kcu.COLUMN_NAME as column_name
40
40
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
@@ -42,7 +42,7 @@ JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
42
42
  ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
43
43
  WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
44
44
  AND tc.TABLE_NAME = '${t.table}'
45
- ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},sd=new Wo;var Fo=class{toSql(t){return {sql:`SELECT
45
+ ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},yd=new zo;var Yo=class{toSql(t){return {sql:`SELECT
46
46
  c.COLUMN_NAME as column_name,
47
47
  c.DATA_TYPE as data_type,
48
48
  c.IS_NULLABLE as is_nullable,
@@ -52,7 +52,7 @@ ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},sd=new Wo;var Fo=class{toSql(t){re
52
52
  c.NUMERIC_SCALE as numeric_scale
53
53
  FROM INFORMATION_SCHEMA.COLUMNS c
54
54
  WHERE c.TABLE_NAME = '${t.table}'
55
- ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},id=new Fo;var jo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("mssql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mssql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mssql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("mssql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mssql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as [${t}]`:""}},ad=new jo;var le=class i{constructor(t){this.segments=this.normalize(t);}normalize(t){if(Array.isArray(t))return t;if(typeof t=="string"){if(!t||t==="$")return [];let e=t.trim();return e=e.startsWith("$.")?e.slice(2):e,e=e.startsWith("$")?e.slice(1):e,e=e.startsWith(".")?e.slice(1):e,e?e.split(".").map(r=>{let o=Number(r);return isNaN(o)?r:o}):[]}return []}getSegments(){return [...this.segments]}isEmpty(){return this.segments.length===0}toPostgres(t=false){if(this.isEmpty())return "";let e=[];for(let r=0;r<this.segments.length;r++){let o=this.segments[r],n=r===this.segments.length-1,s=typeof o=="number";n&&t?e.push(s?`->>${o}`:`->>'${o}'`):e.push(s?`->${o}`:`->'${o}'`);}return e.join("")}toStandardJsonPath(){return this.isEmpty()?"$":`$.${this.segments.join(".")}`}toMysql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments){if(typeof e=="number"){t.push(`[${e}]`);continue}t.push(`.${e}`);}return t.join("")}toSqlite(){return this.toStandardJsonPath()}toMssql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments)typeof e=="number"?t.push(`[${e}]`):t.push(`.${e}`);return t.join("")}toOracle(){return this.toStandardJsonPath()}toDbSyntax(t,e=false){switch(t){case "postgres":case "cockroachdb":return this.toPostgres(e);case "mysql":case "mariadb":return this.toMysql();case "sqlite":return this.toSqlite();case "mssql":return this.toMssql();case "oracledb":return this.toOracle();default:return this.toStandardJsonPath()}}static from(t){return new i(t)}static root(){return new i("")}};var Uo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("mssql",e.column),o=le.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMssql();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toMssql();return `(SELECT COUNT(*) FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}buildObjectKeysSql(t,e){let r=e.toMssql();return `(SELECT [key] FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}formatWithAlias(t,e){return e&&e.length>0?`${t} as [${e}]`:t}},ld=new Uo;var Vo=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:`table ${new h(this.model).getFromForWriteOperations("mssql",e.fromNode)}`,bindings:[]}}},dd=new Vo;var Jo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},ud=new Jo;var Ho=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let c=e.currParamIndex+d-n,p=e.values[d];return p instanceof x?(n++,`${r.formatStringColumn("mssql",l)} = ${p.rawValue}`):(s.push(p),`${r.formatStringColumn("mssql",l)} = @${c}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},cd=new Ho;var zo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.value,o=e.currParamIndex;if(this.isRawNode(r)){let a=this.formatRawIdentifierIfPossible(r.rawValue);return {sql:`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} ${a}`.trim(),bindings:[]}}if(Array.isArray(r)){let a=new h(this.model).formatStringColumn("mssql",e.column);if(e.operator.toLowerCase()==="between"){let c=`@${o} AND @${o+1}`,p=`${a} between ${c}`;return e.isNegated&&(p=`not (${p})`),{sql:p.trim(),bindings:r}}let l=r.map((c,p)=>`@${o+p}`).join(", "),d=`${a} ${e.operator} (${l})`;return e.isNegated&&(d=`not (${d})`),{sql:d.trim(),bindings:r}}let n=new h(this.model).formatStringColumn("mssql",e.column);if(e.operator.includes("null")){let a=`${n} ${e.operator}`;return e.isNegated&&(a=`not (${a})`),{sql:a.trim(),bindings:[]}}if(r===void 0)return {sql:"",bindings:[]};let s=`${n} ${e.operator} @${o}`;return e.isNegated&&(s=`not (${s})`),{sql:s.trim(),bindings:[r]}}isRawNode(t){if(!t||!(typeof t=="object"))return false;let r="rawValue"in t,o=t.isRawValue===true;return r&&o}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("mssql",t):t}},md=new zo;var Yo=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"mssql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},pd=new Yo;var Go=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("mssql",e.column);switch(e.jsonOperator){case "=":o=`${s} = @${r}`,n=[JSON.stringify(e.value)];break;case "contains":case "not contains":o=`CHARINDEX(@${r}, ${s}) > 0`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},fd=new Go;var Zo=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},yd=new Zo;var Xo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return e.clause==="materialized"&&q.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},hd=new Xo;var en=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},gd=new en;var tn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},bd=new tn;var rn=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Td=new rn;var on=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(!e.options.dropDefault){if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}}return e.options.collate&&(a+=` COLLATE ${e.options.collate}`),e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},wd=new on;var nn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(u.file==="add_column")s.push(m);else if(u.file==="add_constraint"||u.folder==="constraint"){let g=s[s.length-1]??"",T=/^\s*add\s+column\b/i.test(g),N=/^\s*add\s+constraint\b/i.test(m);if(T&&!N){let M=m.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${g} ${M}`;}else {let M=/^\s*add\b/i.test(m)?m:`add ${m}`;s.push(M);}}else u.file==="set_default"||u.file==="drop_default"||u.file==="set_not_null"||u.file,s.push(m);a.push(...y);}let l=s.join(", "),d=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${d}${o} ${l}`,bindings:a}}},Nd=new nn;var sn=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Sd=new sn;var an=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},qd=new an;var ln=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},Md=new ln;var dn=class{toSql(t){return {sql:"",bindings:[]}}},Cd=new dn;var un=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Rd=new un;var cn=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},_d=new cn;var mn=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},Od=new mn;var pn=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column \`${e.column}\` set default ${r}`,bindings:[]}}},Ad=new pn;var fn=class{toSql(t){return {sql:"",bindings:[]}}},xd=new fn;var yn=class{toSql(t){let e=t,r=[];return e.engine&&r.push(`ENGINE=${e.engine}`),e.charset&&r.push(`CHARSET=${e.charset}`),e.collate&&r.push(`COLLATE=${e.collate}`),{sql:r.join(" "),bindings:[]}}},Id=new yn;var hn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("mysql",S(e.column)),n=e.dataType.toLowerCase(),s;if(n==="char"){let a=e.length??1;s=`${o} char(${a})`;}else if(n==="varchar"){let a=e.length??255;s=`${o} varchar(${a})`;}else if(n==="uuid")s=`${o} varchar(36)`;else if(n==="ulid")s=`${o} varchar(26)`;else if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")s=`${o} ${n}`;else if(n==="integer"||n==="int")s="int",e.autoIncrement&&(s+=" auto_increment"),s=`${o} ${s}`;else if(n==="tinyint")s=`${o} tinyint`;else if(n==="smallint")s=`${o} smallint`;else if(n==="mediumint")s=`${o} mediumint`;else if(n==="bigint")s="bigint",e.autoIncrement&&(s+=" auto_increment"),s=`${o} ${s}`;else if(n==="float")s=`${o} float`;else if(n==="double")s=`${o} double`;else if(n==="real")s=`${o} double`;else if(n==="decimal"){let a=e.precision??10,l=e.scale??0;s=`${o} decimal(${a}, ${l})`;}else if(n==="numeric"){let a=e.precision??10,l=e.scale??0;s=`${o} numeric(${a}, ${l})`;}else if(n==="date")s=`${o} date`;else if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} time${a}`.trimEnd();}else if(n==="datetime"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} datetime${a}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${a}`),e.autoUpdate&&(s+=` on update current_timestamp${a}`);}else if(n==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} timestamp${a}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${a}`),e.autoUpdate&&(s+=` on update current_timestamp${a}`);}else if(n==="year")s=`${o} year`;else if(n==="boolean")s=`${o} boolean`;else if(n==="varbinary"){let a=e.length??255;s=`${o} varbinary(${a})`;}else if(n==="binary"){let a=e.length??255;s=`${o} binary(${a})`;}else if(n==="bytea"||n==="blob")s=`${o} blob`;else if(n==="json"||n==="jsonb")s=`${o} json`;else if(n==="enum")if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");s=`${o} enum(${a})`;}else s=`${o} text`;else n==="geometry"?s=`${o} geometry`:n==="point"?s=`${o} point`:n==="linestring"?s=`${o} linestring`:n==="polygon"?s=`${o} polygon`:n==="multipoint"?s=`${o} multipoint`:s=`${o} ${n} ${e.length?`(${e.length})`:""}`.trim();return e.collate&&(s+=` COLLATE ${e.collate}`),{sql:s,bindings:[]}}},Dd=new hn;var gn=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},Pd=new gn;var bn=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){let o=(e.columns??[]).map(s=>r.formatStringColumn("mysql",S(s))).join(", ");return {sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}primary key (${o})`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns.map(s=>r.formatStringColumn("mysql",S(s))).join(", "),n=e.constraintName?`constraint \`${e.constraintName}\` `:"";return e.constraintName?{sql:`${n}unique (${o})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let o=e.defaultValue;return o instanceof x?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let o=(e.columns??[]).map(d=>r.formatStringColumn("mysql",S(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",S(d))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},$d=new bn;var Tn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:y,bindings:g}=n.parse([m]);if(m.folder==="constraint"){let T=s.pop()??"",N=y;if(/not null/i.test(N)||/null/i.test(N)||/default/i.test(N)){let M=`${T} ${N}`.trim();M=M.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(M),a.push(...g);continue}s.push(T),s.push(N),a.push(...g);continue}s.push(y),a.push(...g);}for(let m of e.namedConstraints){let{sql:y,bindings:g}=n.parse([m]);s.push(y),a.push(...g);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.engine&&c.push(`ENGINE=${e.engine}`),e.charset&&c.push(`CHARSET=${e.charset}`),e.collate&&c.push(`COLLATE=${e.collate}`);let p=c.length>0?` ${c.join(" ")}`:"";return {sql:`${d}${o} (${l})${p}`,bindings:a}}},Ed=new Tn;var wn=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},Bd=new wn;var Nn=class{toSql(t){return {sql:"distinct",bindings:[]}}},vd=new Nn;var Sn=class{toSql(t){return q.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},kd=new Sn;var qn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Qd=new qn;var Mn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Kd=new Mn;var Cn=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mysql",e.table)} as \`${e.alias}\``,bindings:[]}:{sql:a.formatStringTable("mysql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Ld=new Cn;var Rn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},Wd=new Rn;var _n=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Fd=new _n;var On=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table),n=e.columns.map(a=>`\`${a}\``).join(", ");return {sql:`${e.unique?"unique ":""}\`${e.indexName}\` on ${o} (${n})`,bindings:[]}}},jd=new On;var An=class{toSql(t){let e=t;if(!e.table)throw new Error("MySQL DROP INDEX requires table name");return {sql:`\`${e.indexName}\` on \`${e.table}\``,bindings:[]}}},Ud=new An;var xn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("mysql",p)).join(", "),l=[],d=[];for(let p of e.records){let u=s.map(y=>p[y]),m=[];for(let y of u)y instanceof x?m.push(y.rawValue):(l.push(y),m.push("?"));d.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Vd=new xn;var In=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mysql",o),a=r.formatStringColumn("mysql",n),d=`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"mysql");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Jd=new In;var Dn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},Hd=new Dn;var Tf={for_update:"for update",for_share:"lock in share mode"},Pn=class{toSql(t){let e=t,r=Tf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},zd=new Pn;var $n=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Yd=new $n;var En=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model);if(e.mode==="ignore"){let n=e.conflictColumns?.[0]||"id",s=r.formatStringColumn("mysql",`${e.table}.${n}`);return {sql:`AS new ON DUPLICATE KEY UPDATE ${s} = ${s}`,bindings:[]}}return {sql:`AS new ON DUPLICATE KEY UPDATE ${e.columnsToUpdate.map(n=>`${r.formatStringColumn("mysql",n)} = new.${r.formatStringColumn("mysql",n)}`).join(", ")}`,bindings:[]}}},Gd=new En;var Bn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("mysql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Zd=new Bn;var vn=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Xd=new vn;var kn=class{toSql(t){return {sql:`SELECT
55
+ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},hd=new Yo;var Go=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("mssql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mssql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mssql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("mssql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mssql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as [${t}]`:""}},gd=new Go;var ue=class i{constructor(t){this.segments=this.normalize(t);}normalize(t){if(Array.isArray(t))return t;if(typeof t=="string"){if(!t||t==="$")return [];let e=t.trim();return e=e.startsWith("$.")?e.slice(2):e,e=e.startsWith("$")?e.slice(1):e,e=e.startsWith(".")?e.slice(1):e,e?e.split(".").map(r=>{let o=Number(r);return isNaN(o)?r:o}):[]}return []}getSegments(){return [...this.segments]}isEmpty(){return this.segments.length===0}toPostgres(t=false){if(this.isEmpty())return "";let e=[];for(let r=0;r<this.segments.length;r++){let o=this.segments[r],n=r===this.segments.length-1,s=typeof o=="number";n&&t?e.push(s?`->>${o}`:`->>'${o}'`):e.push(s?`->${o}`:`->'${o}'`);}return e.join("")}toStandardJsonPath(){return this.isEmpty()?"$":`$.${this.segments.join(".")}`}toMysql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments){if(typeof e=="number"){t.push(`[${e}]`);continue}t.push(`.${e}`);}return t.join("")}toSqlite(){return this.toStandardJsonPath()}toMssql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments)typeof e=="number"?t.push(`[${e}]`):t.push(`.${e}`);return t.join("")}toOracle(){return this.toStandardJsonPath()}toDbSyntax(t,e=false){switch(t){case "postgres":case "cockroachdb":return this.toPostgres(e);case "mysql":case "mariadb":return this.toMysql();case "sqlite":return this.toSqlite();case "mssql":return this.toMssql();case "oracledb":return this.toOracle();default:return this.toStandardJsonPath()}}static from(t){return new i(t)}static root(){return new i("")}};var Zo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("mssql",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMssql();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toMssql();return `(SELECT COUNT(*) FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}buildObjectKeysSql(t,e){let r=e.toMssql();return `(SELECT [key] FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}formatWithAlias(t,e){return e&&e.length>0?`${t} as [${e}]`:t}},bd=new Zo;var Xo=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:`table ${new h(this.model).getFromForWriteOperations("mssql",e.fromNode)}`,bindings:[]}}},Td=new Xo;var en=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},wd=new en;var tn=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let c=e.currParamIndex+d-n,p=e.values[d];return p instanceof D?(n++,`${r.formatStringColumn("mssql",l)} = ${p.rawValue}`):(s.push(p),`${r.formatStringColumn("mssql",l)} = @${c}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Nd=new tn;var rn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.value,o=e.currParamIndex;if(this.isRawNode(r)){let a=this.formatRawIdentifierIfPossible(r.rawValue);return {sql:`${new h(this.model).formatStringColumn("mssql",e.column)} ${e.operator} ${a}`.trim(),bindings:[]}}if(Array.isArray(r)){let a=new h(this.model).formatStringColumn("mssql",e.column);if(e.operator.toLowerCase()==="between"){let c=`@${o} AND @${o+1}`,p=`${a} between ${c}`;return e.isNegated&&(p=`not (${p})`),{sql:p.trim(),bindings:r}}let l=r.map((c,p)=>`@${o+p}`).join(", "),d=`${a} ${e.operator} (${l})`;return e.isNegated&&(d=`not (${d})`),{sql:d.trim(),bindings:r}}let n=new h(this.model).formatStringColumn("mssql",e.column);if(e.operator.includes("null")){let a=`${n} ${e.operator}`;return e.isNegated&&(a=`not (${a})`),{sql:a.trim(),bindings:[]}}if(r===void 0)return {sql:"",bindings:[]};let s=`${n} ${e.operator} @${o}`;return e.isNegated&&(s=`not (${s})`),{sql:s.trim(),bindings:[r]}}isRawNode(t){if(!t||!(typeof t=="object"))return false;let r="rawValue"in t,o=t.isRawValue===true;return r&&o}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("mssql",t):t}},Sd=new rn;var on=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"mssql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Cd=new on;var nn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("mssql",e.column);switch(e.jsonOperator){case "=":o=`${s} = @${r}`,n=[JSON.stringify(e.value)];break;case "contains":case "not contains":o=`CHARINDEX(@${r}, ${s}) > 0`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},qd=new nn;var sn=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Md=new sn;var an=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return e.clause==="materialized"&&q.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},Rd=new an;var ln=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},_d=new ln;var dn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Od=new dn;var un=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Ad=new un;var cn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(!e.options.dropDefault){if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}}return e.options.collate&&(a+=` COLLATE ${e.options.collate}`),e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},xd=new cn;var mn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(u.file==="add_column")s.push(m);else if(u.file==="add_constraint"||u.folder==="constraint"){let g=s[s.length-1]??"",T=/^\s*add\s+column\b/i.test(g),N=/^\s*add\s+constraint\b/i.test(m);if(T&&!N){let M=m.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${g} ${M}`;}else {let M=/^\s*add\b/i.test(m)?m:`add ${m}`;s.push(M);}}else u.file==="set_default"||u.file==="drop_default"||u.file==="set_not_null"||u.file,s.push(m);a.push(...y);}let l=s.join(", "),d=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${d}${o} ${l}`,bindings:a}}},Dd=new mn;var pn=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Id=new pn;var fn=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},Pd=new fn;var yn=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},$d=new yn;var hn=class{toSql(t){return {sql:"",bindings:[]}}},Ed=new hn;var gn=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Bd=new gn;var bn=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},vd=new bn;var Tn=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},kd=new Tn;var wn=class{toSql(t){let e=t,r;return e.defaultValue instanceof D?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column \`${e.column}\` set default ${r}`,bindings:[]}}},Qd=new wn;var Nn=class{toSql(t){return {sql:"",bindings:[]}}},Kd=new Nn;var Sn=class{toSql(t){let e=t,r=[];return e.engine&&r.push(`ENGINE=${e.engine}`),e.charset&&r.push(`CHARSET=${e.charset}`),e.collate&&r.push(`COLLATE=${e.collate}`),{sql:r.join(" "),bindings:[]}}},Ld=new Sn;var Cn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("mysql",S(e.column)),n=e.dataType.toLowerCase(),s;if(n==="char"){let a=e.length??1;s=`${o} char(${a})`;}else if(n==="varchar"){let a=e.length??255;s=`${o} varchar(${a})`;}else if(n==="uuid")s=`${o} varchar(36)`;else if(n==="ulid")s=`${o} varchar(26)`;else if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")s=`${o} ${n}`;else if(n==="integer"||n==="int")s="int",e.autoIncrement&&(s+=" auto_increment"),s=`${o} ${s}`;else if(n==="tinyint")s=`${o} tinyint`;else if(n==="smallint")s=`${o} smallint`;else if(n==="mediumint")s=`${o} mediumint`;else if(n==="bigint")s="bigint",e.autoIncrement&&(s+=" auto_increment"),s=`${o} ${s}`;else if(n==="float")s=`${o} float`;else if(n==="double")s=`${o} double`;else if(n==="real")s=`${o} double`;else if(n==="decimal"){let a=e.precision??10,l=e.scale??0;s=`${o} decimal(${a}, ${l})`;}else if(n==="numeric"){let a=e.precision??10,l=e.scale??0;s=`${o} numeric(${a}, ${l})`;}else if(n==="date")s=`${o} date`;else if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} time${a}`.trimEnd();}else if(n==="datetime"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} datetime${a}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${a}`),e.autoUpdate&&(s+=` on update current_timestamp${a}`);}else if(n==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} timestamp${a}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${a}`),e.autoUpdate&&(s+=` on update current_timestamp${a}`);}else if(n==="year")s=`${o} year`;else if(n==="boolean")s=`${o} boolean`;else if(n==="varbinary"){let a=e.length??255;s=`${o} varbinary(${a})`;}else if(n==="binary"){let a=e.length??255;s=`${o} binary(${a})`;}else if(n==="bytea"||n==="blob")s=`${o} blob`;else if(n==="json"||n==="jsonb")s=`${o} json`;else if(n==="enum")if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");s=`${o} enum(${a})`;}else s=`${o} text`;else n==="geometry"?s=`${o} geometry`:n==="point"?s=`${o} point`:n==="linestring"?s=`${o} linestring`:n==="polygon"?s=`${o} polygon`:n==="multipoint"?s=`${o} multipoint`:s=`${o} ${n} ${e.length?`(${e.length})`:""}`.trim();return e.collate&&(s+=` COLLATE ${e.collate}`),{sql:s,bindings:[]}}},Wd=new Cn;var qn=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},Fd=new qn;var Mn=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){let o=(e.columns??[]).map(s=>r.formatStringColumn("mysql",S(s))).join(", ");return {sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}primary key (${o})`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns.map(s=>r.formatStringColumn("mysql",S(s))).join(", "),n=e.constraintName?`constraint \`${e.constraintName}\` `:"";return e.constraintName?{sql:`${n}unique (${o})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let o=e.defaultValue;return o instanceof D?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let o=(e.columns??[]).map(d=>r.formatStringColumn("mysql",S(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",S(d))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},jd=new Mn;var Rn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:y,bindings:g}=n.parse([m]);if(m.folder==="constraint"){let T=s.pop()??"",N=y;if(/not null/i.test(N)||/null/i.test(N)||/default/i.test(N)){let M=`${T} ${N}`.trim();M=M.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(M),a.push(...g);continue}s.push(T),s.push(N),a.push(...g);continue}s.push(y),a.push(...g);}for(let m of e.namedConstraints){let{sql:y,bindings:g}=n.parse([m]);s.push(y),a.push(...g);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.engine&&c.push(`ENGINE=${e.engine}`),e.charset&&c.push(`CHARSET=${e.charset}`),e.collate&&c.push(`COLLATE=${e.collate}`);let p=c.length>0?` ${c.join(" ")}`:"";return {sql:`${d}${o} (${l})${p}`,bindings:a}}},Ud=new Rn;var _n=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},Vd=new _n;var On=class{toSql(t){return {sql:"distinct",bindings:[]}}},Jd=new On;var An=class{toSql(t){return q.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},Hd=new An;var xn=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},zd=new xn;var Dn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Yd=new Dn;var In=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mysql",e.table)} as \`${e.alias}\``,bindings:[]}:{sql:a.formatStringTable("mysql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Gd=new In;var Pn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},Zd=new Pn;var $n=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Xd=new $n;var En=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("mysql",e.table),n=e.columns.map(a=>`\`${a}\``).join(", ");return {sql:`${e.unique?"unique ":""}\`${e.indexName}\` on ${o} (${n})`,bindings:[]}}},eu=new En;var Bn=class{toSql(t){let e=t;if(!e.table)throw new Error("MySQL DROP INDEX requires table name");return {sql:`\`${e.indexName}\` on \`${e.table}\``,bindings:[]}}},tu=new Bn;var vn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("mysql",p)).join(", "),l=[],d=[];for(let p of e.records){let u=s.map(y=>p[y]),m=[];for(let y of u)y instanceof D?m.push(y.rawValue):(l.push(y),m.push("?"));d.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},ru=new vn;var kn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mysql",o),a=r.formatStringColumn("mysql",n),d=`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"mysql");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},ou=new kn;var Qn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},nu=new Qn;var Mf={for_update:"for update",for_share:"lock in share mode"},Kn=class{toSql(t){let e=t,r=Mf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},su=new Kn;var Ln=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},iu=new Ln;var Wn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model);if(e.mode==="ignore"){let n=e.conflictColumns?.[0]||"id",s=r.formatStringColumn("mysql",`${e.table}.${n}`);return {sql:`AS new ON DUPLICATE KEY UPDATE ${s} = ${s}`,bindings:[]}}return {sql:`AS new ON DUPLICATE KEY UPDATE ${e.columnsToUpdate.map(n=>`${r.formatStringColumn("mysql",n)} = new.${r.formatStringColumn("mysql",n)}`).join(", ")}`,bindings:[]}}},au=new Wn;var Fn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("mysql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},lu=new Fn;var jn=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},du=new jn;var Un=class{toSql(t){return {sql:`SELECT
56
56
  cc.CONSTRAINT_NAME AS name,
57
57
  cc.CHECK_CLAUSE AS expression
58
58
  FROM information_schema.CHECK_CONSTRAINTS cc
@@ -61,7 +61,7 @@ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},id=new Fo;var jo=class{toSql(t){let
61
61
  AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
62
62
  WHERE tc.TABLE_SCHEMA = DATABASE()
63
63
  AND tc.TABLE_NAME = '${t.table}'
64
- AND tc.CONSTRAINT_TYPE = 'CHECK'`,bindings:[]}}},eu=new kn;var Qn=class{toSql(t){return {sql:`SELECT
64
+ AND tc.CONSTRAINT_TYPE = 'CHECK'`,bindings:[]}}},uu=new Un;var Vn=class{toSql(t){return {sql:`SELECT
65
65
  k.CONSTRAINT_NAME AS name,
66
66
  k.COLUMN_NAME AS column_name,
67
67
  k.REFERENCED_TABLE_NAME AS referenced_table,
@@ -72,18 +72,18 @@ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},id=new Fo;var jo=class{toSql(t){let
72
72
  JOIN information_schema.REFERENTIAL_CONSTRAINTS r
73
73
  ON k.CONSTRAINT_NAME = r.CONSTRAINT_NAME AND k.CONSTRAINT_SCHEMA = r.CONSTRAINT_SCHEMA
74
74
  WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.REFERENCED_TABLE_NAME IS NOT NULL
75
- ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},tu=new Qn;var Kn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},ru=new Kn;var Ln=class{toSql(t){return {sql:`SELECT
75
+ ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},cu=new Vn;var Jn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},mu=new Jn;var Hn=class{toSql(t){return {sql:`SELECT
76
76
  CONSTRAINT_NAME AS name,
77
77
  COLUMN_NAME AS column_name
78
78
  FROM information_schema.KEY_COLUMN_USAGE k
79
79
  WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.CONSTRAINT_NAME = 'PRIMARY'
80
- ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},ou=new Ln;var Wn=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default, CHARACTER_MAXIMUM_LENGTH AS char_length, NUMERIC_PRECISION AS numeric_precision, NUMERIC_SCALE AS numeric_scale FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${t.table}' ORDER BY ORDINAL_POSITION`,bindings:[]}}},nu=new Wn;var Fn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("mysql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},su=new Fn;var jn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("mysql",e.column),o=le.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMysql();return r==="$"?t:`JSON_EXTRACT(${t}, '${r}')`}buildExtractTextSql(t,e){let r=e.toMysql();return r==="$"?`JSON_UNQUOTE(${t})`:`JSON_UNQUOTE(JSON_EXTRACT(${t}, '${r}'))`}buildArrayLengthSql(t,e){let r=e.toMysql();return r==="$"?`JSON_LENGTH(${t})`:`JSON_LENGTH(${t}, '${r}')`}buildObjectKeysSql(t,e){let r=e.toMysql();return r==="$"?`JSON_KEYS(${t})`:`JSON_KEYS(${t}, '${r}')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as \`${e}\``:t}},iu=new jn;var Un=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},au=new Un;var Vn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},lu=new Vn;var Jn=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof x?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},du=new Jn;var Hn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("mysql",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("mysql",t):t}},uu=new Hn;var zn=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},cu=new zn;var Yn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("mysql",e.column);switch(e.jsonOperator){case "=":r=`${n} = CAST(? AS JSON)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},mu=new Yn;var Gn=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},pu=new Gn;var Zn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},fu=new Zn;var Xn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},yu=new Xn;var es=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},hu=new es;var ts=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},gu=new ts;var rs=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify "${e.column}" ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`modify "${e.column}" null`:`modify "${e.column}" not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, modify "${e.column}" default null`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"?l="1":l==="FALSE"?l="0":l=`'${l}'`),a+=`, modify "${e.column}" default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},bu=new rs;var os=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let c of e.children){let{sql:p,bindings:u}=n.parse([c]);s.push(p.trim()),a.push(...u);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Tu=new os;var ns=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},wu=new ns;var ss=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Nu=new ss;var is=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},Su=new is;var as=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},qu=new as;var ls=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Mu=new ls;var ds=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Cu=new ds;var us=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},Ru=new us;var cs=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`modify "${e.column}" default ${r}`,bindings:[]}}},_u=new cs;var ms=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},Ou=new ms;var ps=class{toSql(t){return {sql:"",bindings:[]}}},Au=new ps;var fs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("oracledb",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar2(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} clob`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar2(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar2(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} number(19) generated by default as identity`,bindings:[]}:{sql:`${o} number(19)`,bindings:[]};if(n==="tinyint")return {sql:`${o} number(3)`,bindings:[]};if(n==="smallint")return {sql:`${o} number(5)`,bindings:[]};if(n==="mediumint")return {sql:`${o} number(7)`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} binary_float`,bindings:[]};if(n==="double")return {sql:`${o} binary_double`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} number(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} number(4)`,bindings:[]};if(n==="time")return {sql:`${o} varchar2(8)`,bindings:[]};if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":"",a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} timestamp${a}${s}`.trimEnd();return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} number(1)`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} clob`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar2(255)`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} number(10) generated by default as identity`,bindings:[]}:{sql:`${o} number(10)`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} sdo_geometry`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},xu=new fs;var ys=class{toSql(t){return {sql:"",bindings:[]}}},Iu=new ys;var hs=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("oracledb",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("oracledb",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof x?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("oracledb",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("oracledb",S(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Du=new hs;var gs=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(u.folder==="constraint"){let g=s.pop()??"",T=m;if(/not null/i.test(T)||/null/i.test(T)||/default/i.test(T)){let N=`${g} ${T}`.trim();N=N.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(N),a.push(...y);continue}s.push(g),s.push(T),a.push(...y);continue}s.push(m),a.push(...y);}for(let u of e.namedConstraints){let{sql:m,bindings:y}=n.parse([u]);s.push(m),a.push(...y);}let l=s.join(", "),d=[];if(e.oracleTablespace&&d.push(`TABLESPACE ${e.oracleTablespace}`),e.oracleCompress?d.push("COMPRESS"):e.oracleCompressFor&&d.push(`COMPRESS FOR ${e.oracleCompressFor}`),e.oracleStorage){let u=Object.entries(e.oracleStorage).map(([m,y])=>`${m.toUpperCase()} ${y}`).join(" ");u&&d.push(`STORAGE (${u})`);}e.oracleLogging===false?d.push("NOLOGGING"):e.oracleLogging===true&&d.push("LOGGING"),e.oracleCache===false?d.push("NOCACHE"):e.oracleCache===true&&d.push("CACHE"),e.oracleInMemory&&d.push("INMEMORY");let c=d.length>0?` ${d.join(" ")}`:"";return {sql:`${o} (${l})${c}`,bindings:a}}},Pu=new gs;var bs=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},$u=new bs;var Ts=class{toSql(t){return {sql:"",bindings:[]}}},Eu=new Ts;var ws=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},Bu=new ws;var Ns=class{toSql(t){let e=t;return {sql:`${new h(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},vu=new Ns;var Ss=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},ku=new Ss;var qs=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("oracledb",e.table)} "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("oracledb",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Qu=new qs;var Ms=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},Ku=new Ms;var Cs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Lu=new Cs;var Rs=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Wu=new Rs;var _s=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},Fu=new _s;var Os=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("oracledb",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g of m)g instanceof x?y.push(g.rawValue):(l.push(g),y.push(`:${c++}`));d.push(`(${y.join(", ")})`);}let p;if(e.records.length===1)p=`${o} (${a}) values ${d[0]}`;else {e.keyword="insert",c=e.currParamIndex;let u=[];for(let m of e.records){let y=s.map(T=>m[T]),g=[];for(let T of y)T instanceof x?g.push(T.rawValue):g.push(`:${c++}`);u.push(`into ${o} (${a}) values (${g.join(", ")})`);}p=`all ${u.join(" ")} select * from dual`;}return {sql:p,bindings:l}}},ju=new Os;var As=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("oracledb",o),a=r.formatStringColumn("oracledb",n),d=`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"oracledb");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Uu=new As;var xs=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},Vu=new xs;var wf={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},Is=class{toSql(t){let e=t,r=wf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Ju=new Is;var Ds=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},Hu=new Ds;var Ps=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("oracledb",a)).join(" AND ");if(e.mode==="ignore")return {sql:`on (${o})`,bindings:[]};let n=e.columnsToUpdate.map(a=>`target.${r.formatStringColumn("oracledb",a)} = source.${r.formatStringColumn("oracledb",a)}`).join(", ");return {sql:`on (${o}) when matched then update set ${n}`,bindings:[]}}},zu=new Ps;var $s=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Yu=new $s;var Es=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Gu=new Es;var Bs=class{toSql(t){return {sql:`SELECT
80
+ ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},pu=new Hn;var zn=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default, CHARACTER_MAXIMUM_LENGTH AS char_length, NUMERIC_PRECISION AS numeric_precision, NUMERIC_SCALE AS numeric_scale FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${t.table}' ORDER BY ORDINAL_POSITION`,bindings:[]}}},fu=new zn;var Yn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("mysql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},yu=new Yn;var Gn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("mysql",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMysql();return r==="$"?t:`JSON_EXTRACT(${t}, '${r}')`}buildExtractTextSql(t,e){let r=e.toMysql();return r==="$"?`JSON_UNQUOTE(${t})`:`JSON_UNQUOTE(JSON_EXTRACT(${t}, '${r}'))`}buildArrayLengthSql(t,e){let r=e.toMysql();return r==="$"?`JSON_LENGTH(${t})`:`JSON_LENGTH(${t}, '${r}')`}buildObjectKeysSql(t,e){let r=e.toMysql();return r==="$"?`JSON_KEYS(${t})`:`JSON_KEYS(${t}, '${r}')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as \`${e}\``:t}},hu=new Gn;var Zn=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},gu=new Zn;var Xn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},bu=new Xn;var es=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof D?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},Tu=new es;var ts=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("mysql",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("mysql",t):t}},wu=new ts;var rs=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Nu=new rs;var os=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("mysql",e.column);switch(e.jsonOperator){case "=":r=`${n} = CAST(? AS JSON)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},Su=new os;var ns=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Cu=new ns;var ss=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},qu=new ss;var is=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Mu=new is;var as=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Ru=new as;var ls=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},_u=new ls;var ds=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify "${e.column}" ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`modify "${e.column}" null`:`modify "${e.column}" not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, modify "${e.column}" default null`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"?l="1":l==="FALSE"?l="0":l=`'${l}'`),a+=`, modify "${e.column}" default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},Ou=new ds;var us=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let c of e.children){let{sql:p,bindings:u}=n.parse([c]);s.push(p.trim()),a.push(...u);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Au=new us;var cs=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},xu=new cs;var ms=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Du=new ms;var ps=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},Iu=new ps;var fs=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},Pu=new fs;var ys=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},$u=new ys;var hs=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Eu=new hs;var gs=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},Bu=new gs;var bs=class{toSql(t){let e=t,r;return e.defaultValue instanceof D?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`modify "${e.column}" default ${r}`,bindings:[]}}},vu=new bs;var Ts=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},ku=new Ts;var ws=class{toSql(t){return {sql:"",bindings:[]}}},Qu=new ws;var Ns=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("oracledb",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar2(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} clob`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar2(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar2(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} number(19) generated by default as identity`,bindings:[]}:{sql:`${o} number(19)`,bindings:[]};if(n==="tinyint")return {sql:`${o} number(3)`,bindings:[]};if(n==="smallint")return {sql:`${o} number(5)`,bindings:[]};if(n==="mediumint")return {sql:`${o} number(7)`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} binary_float`,bindings:[]};if(n==="double")return {sql:`${o} binary_double`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} number(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} number(4)`,bindings:[]};if(n==="time")return {sql:`${o} varchar2(8)`,bindings:[]};if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":"",a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} timestamp${a}${s}`.trimEnd();return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} number(1)`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} clob`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar2(255)`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} number(10) generated by default as identity`,bindings:[]}:{sql:`${o} number(10)`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} sdo_geometry`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Ku=new Ns;var Ss=class{toSql(t){return {sql:"",bindings:[]}}},Lu=new Ss;var Cs=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("oracledb",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("oracledb",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof D?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("oracledb",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("oracledb",S(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Wu=new Cs;var qs=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(u.folder==="constraint"){let g=s.pop()??"",T=m;if(/not null/i.test(T)||/null/i.test(T)||/default/i.test(T)){let N=`${g} ${T}`.trim();N=N.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(N),a.push(...y);continue}s.push(g),s.push(T),a.push(...y);continue}s.push(m),a.push(...y);}for(let u of e.namedConstraints){let{sql:m,bindings:y}=n.parse([u]);s.push(m),a.push(...y);}let l=s.join(", "),d=[];if(e.oracleTablespace&&d.push(`TABLESPACE ${e.oracleTablespace}`),e.oracleCompress?d.push("COMPRESS"):e.oracleCompressFor&&d.push(`COMPRESS FOR ${e.oracleCompressFor}`),e.oracleStorage){let u=Object.entries(e.oracleStorage).map(([m,y])=>`${m.toUpperCase()} ${y}`).join(" ");u&&d.push(`STORAGE (${u})`);}e.oracleLogging===false?d.push("NOLOGGING"):e.oracleLogging===true&&d.push("LOGGING"),e.oracleCache===false?d.push("NOCACHE"):e.oracleCache===true&&d.push("CACHE"),e.oracleInMemory&&d.push("INMEMORY");let c=d.length>0?` ${d.join(" ")}`:"";return {sql:`${o} (${l})${c}`,bindings:a}}},Fu=new qs;var Ms=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},ju=new Ms;var Rs=class{toSql(t){return {sql:"",bindings:[]}}},Uu=new Rs;var _s=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},Vu=new _s;var Os=class{toSql(t){let e=t;return {sql:`${new h(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},Ju=new Os;var As=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Hu=new As;var xs=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("oracledb",e.table)} "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("oracledb",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},zu=new xs;var Ds=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},Yu=new Ds;var Is=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Gu=new Is;var Ps=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("oracledb",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Zu=new Ps;var $s=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},Xu=new $s;var Es=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("oracledb",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g of m)g instanceof D?y.push(g.rawValue):(l.push(g),y.push(`:${c++}`));d.push(`(${y.join(", ")})`);}let p;if(e.records.length===1)p=`${o} (${a}) values ${d[0]}`;else {e.keyword="insert",c=e.currParamIndex;let u=[];for(let m of e.records){let y=s.map(T=>m[T]),g=[];for(let T of y)T instanceof D?g.push(T.rawValue):g.push(`:${c++}`);u.push(`into ${o} (${a}) values (${g.join(", ")})`);}p=`all ${u.join(" ")} select * from dual`;}return {sql:p,bindings:l}}},ec=new Es;var Bs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("oracledb",o),a=r.formatStringColumn("oracledb",n),d=`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"oracledb");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},tc=new Bs;var vs=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},rc=new vs;var Rf={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},ks=class{toSql(t){let e=t,r=Rf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},oc=new ks;var Qs=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},nc=new Qs;var Ks=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("oracledb",a)).join(" AND ");if(e.mode==="ignore")return {sql:`on (${o})`,bindings:[]};let n=e.columnsToUpdate.map(a=>`target.${r.formatStringColumn("oracledb",a)} = source.${r.formatStringColumn("oracledb",a)}`).join(", ");return {sql:`on (${o}) when matched then update set ${n}`,bindings:[]}}},sc=new Ks;var Ls=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},ic=new Ls;var Ws=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},ac=new Ws;var Fs=class{toSql(t){return {sql:`SELECT
81
81
  constraint_name AS name,
82
82
  search_condition AS expression
83
83
  FROM user_constraints
84
84
  WHERE table_name = '${t.table.toUpperCase()}'
85
85
  AND constraint_type = 'C'
86
- AND constraint_name NOT LIKE 'SYS_%'`,bindings:[]}}},Zu=new Bs;var vs=class{toSql(t){return {sql:`SELECT
86
+ AND constraint_name NOT LIKE 'SYS_%'`,bindings:[]}}},lc=new Fs;var js=class{toSql(t){return {sql:`SELECT
87
87
  c.constraint_name as name,
88
88
  cc.column_name as column_name,
89
89
  rc.table_name as referenced_table,
@@ -95,7 +95,7 @@ JOIN user_constraints rc ON c.r_constraint_name = rc.constraint_name
95
95
  JOIN user_cons_columns rcc ON rc.constraint_name = rcc.constraint_name AND cc.position = rcc.position
96
96
  WHERE c.constraint_type = 'R'
97
97
  AND c.table_name = '${t.table.toUpperCase()}'
98
- ORDER BY cc.position`,bindings:[]}}},Xu=new vs;var ks=class{toSql(t){return {sql:`SELECT
98
+ ORDER BY cc.position`,bindings:[]}}},dc=new js;var Us=class{toSql(t){return {sql:`SELECT
99
99
  i.index_name as index_name,
100
100
  ic.column_name as column_name,
101
101
  CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END as is_unique
@@ -108,14 +108,14 @@ WHERE i.table_name = '${t.table.toUpperCase()}'
108
108
  WHERE c.constraint_type = 'P'
109
109
  AND c.index_name = i.index_name
110
110
  )
111
- ORDER BY i.index_name, ic.column_position`,bindings:[]}}},ec=new ks;var Qs=class{toSql(t){return {sql:`SELECT
111
+ ORDER BY i.index_name, ic.column_position`,bindings:[]}}},uc=new Us;var Vs=class{toSql(t){return {sql:`SELECT
112
112
  c.constraint_name as name,
113
113
  cc.column_name as column_name
114
114
  FROM user_constraints c
115
115
  JOIN user_cons_columns cc ON c.constraint_name = cc.constraint_name
116
116
  WHERE c.constraint_type = 'P'
117
117
  AND c.table_name = '${t.table.toUpperCase()}'
118
- ORDER BY cc.position`,bindings:[]}}},tc=new Qs;var Ks=class{toSql(t){return {sql:`SELECT
118
+ ORDER BY cc.position`,bindings:[]}}},cc=new Vs;var Js=class{toSql(t){return {sql:`SELECT
119
119
  column_name,
120
120
  data_type,
121
121
  CASE WHEN nullable = 'Y' THEN 'YES' ELSE 'NO' END as is_nullable,
@@ -125,7 +125,7 @@ ORDER BY cc.position`,bindings:[]}}},tc=new Qs;var Ks=class{toSql(t){return {sql
125
125
  data_scale as numeric_scale
126
126
  FROM user_tab_columns
127
127
  WHERE table_name = '${t.table.toUpperCase()}'
128
- ORDER BY column_id`,bindings:[]}}},rc=new Ks;var Ls=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},oc=new Ls;var Ws=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=le.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},nc=new Ws;var Fs=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},sc=new Fs;var js=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},ic=new js;var Us=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,d)=>{let c=e.values[d];return c instanceof x?`${r.formatStringColumn("oracledb",l)} = ${c.rawValue}`:(s.push(c),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},ac=new Us;var Vs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new h(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("oracledb",t):t}},lc=new Vs;var Js=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},dc=new Js;var Hs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},uc=new Hs;var zs=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},cc=new zs;var Ys=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},mc=new Ys;var Gs=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},pc=new Gs;var Zs=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},fc=new Zs;var Xs=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},yc=new Xs;var ei=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},hc=new ei;var ti=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let p of e.children){let{sql:u,bindings:m}=n.parse([p]);s.push(u.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},gc=new ti;var ri=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},bc=new ri;var oi=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Tc=new oi;var ni=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},wc=new ni;var si=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Nc=new si;var ii=class{toSql(t){return {sql:"",bindings:[]}}},Sc=new ii;var ai=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},qc=new ai;var li=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Mc=new li;var di=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Cc=new di;var ui=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Rc=new ui;var ci=class{toSql(t){return {sql:"",bindings:[]}}},_c=new ci;var mi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("postgres",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":" without time zone",a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} timestamp${a}${s}`.trimEnd();return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} text check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Oc=new mi;var pi=class{toSql(t){return {sql:"",bindings:[]}}},Ac=new pi;var fi=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof x?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("postgres",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("postgres",S(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},xc=new fi;var yi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let N of e.children){let{sql:M,bindings:O}=n.parse([N]);if(N.folder==="constraint"){let R=s.pop()??"",D=M;if(/not null/i.test(D)||/null/i.test(D)||/default/i.test(D)){let P=`${R} ${D}`.trim();P=P.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(P),a.push(...O);continue}s.push(R),s.push(D),a.push(...O);continue}s.push(M),a.push(...O);}for(let N of e.namedConstraints){let{sql:M,bindings:O}=n.parse([N]);s.push(M),a.push(...O);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.temporary&&c.push("TEMPORARY"),e.unlogged&&c.push("UNLOGGED");let p=[];if(e.postgresWith){let N=Object.entries(e.postgresWith).map(([M,O])=>`${M}=${O}`).join(", ");N&&p.push(`WITH (${N})`);}let u=e.tablespace?`TABLESPACE ${e.tablespace}`:"",m=c.length>0?`${c.join(" ")} `:"",y=p.length>0?` ${p.join(" ")}`:"",g=u?` ${u}`:"";return {sql:`${d}${m}${o} (${l})${y}${g}`,bindings:a}}},Ic=new yi;var hi=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Dc=new hi;var gi=class{toSql(t){return {sql:"",bindings:[]}}},Pc=new gi;var bi=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},$c=new bi;var Ti=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Ec=new Ti;var wi=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},Bc=new wi;var Ni=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},vc=new Ni;var Si=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},kc=new Si;var qi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Qc=new qi;var Mi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Kc=new Mi;var Ci=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},Lc=new Ci;var Ri=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("postgres",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g=0;g<s.length;g++){let T=m[g];T instanceof x?y.push(T.rawValue):(l.push(T),y.push(`$${c++}${this.formatTypeCast(T)}`));}d.push(`(${y.join(", ")})`);}let p=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let u=e.returning.map(m=>r.formatStringColumn("postgres",m)).join(", ");p+=` returning ${u}`;}else p+=" returning *";return {sql:p,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Wc=new Ri;var _i=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n),d=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"postgres");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Fc=new _i;var Oi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},jc=new Oi;var Nf={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},Ai=class{toSql(t){let e=t,r=Nf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Uc=new Ai;var xi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},Vc=new xi;var Ii=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("postgres",a)).join(", ");if(e.mode==="ignore")return {sql:`on conflict (${o}) do nothing`,bindings:[]};let n=e.columnsToUpdate.map(a=>`${r.formatStringColumn("postgres",a)} = excluded.${r.formatStringColumn("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}else s+=" returning *";return {sql:s,bindings:[]}}},Jc=new Ii;var Di=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Hc=new Di;var Pi=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},zc=new Pi;var $i=class{toSql(t){return {sql:`SELECT
128
+ ORDER BY column_id`,bindings:[]}}},mc=new Js;var Hs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},pc=new Hs;var zs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},fc=new zs;var Ys=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},yc=new Ys;var Gs=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},hc=new Gs;var Zs=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,d)=>{let c=e.values[d];return c instanceof D?`${r.formatStringColumn("oracledb",l)} = ${c.rawValue}`:(s.push(c),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},gc=new Zs;var Xs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new h(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("oracledb",t):t}},bc=new Xs;var ei=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Tc=new ei;var ti=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},wc=new ti;var ri=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Nc=new ri;var oi=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},Sc=new oi;var ni=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Cc=new ni;var si=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},qc=new si;var ii=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Mc=new ii;var ai=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},Rc=new ai;var li=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let p of e.children){let{sql:u,bindings:m}=n.parse([p]);s.push(u.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},_c=new li;var di=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Oc=new di;var ui=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Ac=new ui;var ci=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},xc=new ci;var mi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Dc=new mi;var pi=class{toSql(t){return {sql:"",bindings:[]}}},Ic=new pi;var fi=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Pc=new fi;var yi=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},$c=new yi;var hi=class{toSql(t){let e=t,r;return e.defaultValue instanceof D?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Ec=new hi;var gi=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Bc=new gi;var bi=class{toSql(t){return {sql:"",bindings:[]}}},vc=new bi;var Ti=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("postgres",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":" without time zone",a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} timestamp${a}${s}`.trimEnd();return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} text check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},kc=new Ti;var wi=class{toSql(t){return {sql:"",bindings:[]}}},Qc=new wi;var Ni=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof D?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("postgres",S(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("postgres",S(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Kc=new Ni;var Si=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let N of e.children){let{sql:M,bindings:A}=n.parse([N]);if(N.folder==="constraint"){let _=s.pop()??"",I=M;if(/not null/i.test(I)||/null/i.test(I)||/default/i.test(I)){let P=`${_} ${I}`.trim();P=P.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(P),a.push(...A);continue}s.push(_),s.push(I),a.push(...A);continue}s.push(M),a.push(...A);}for(let N of e.namedConstraints){let{sql:M,bindings:A}=n.parse([N]);s.push(M),a.push(...A);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.temporary&&c.push("TEMPORARY"),e.unlogged&&c.push("UNLOGGED");let p=[];if(e.postgresWith){let N=Object.entries(e.postgresWith).map(([M,A])=>`${M}=${A}`).join(", ");N&&p.push(`WITH (${N})`);}let u=e.tablespace?`TABLESPACE ${e.tablespace}`:"",m=c.length>0?`${c.join(" ")} `:"",y=p.length>0?` ${p.join(" ")}`:"",g=u?` ${u}`:"";return {sql:`${d}${m}${o} (${l})${y}${g}`,bindings:a}}},Lc=new Si;var Ci=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Wc=new Ci;var qi=class{toSql(t){return {sql:"",bindings:[]}}},Fc=new qi;var Mi=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},jc=new Mi;var Ri=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Uc=new Ri;var _i=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},Vc=new _i;var Oi=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Jc=new Oi;var Ai=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Hc=new Ai;var xi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},zc=new xi;var Di=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Yc=new Di;var Ii=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},Gc=new Ii;var Pi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(u=>r.formatStringColumn("postgres",u)).join(", "),l=[],d=[],c=e.currParamIndex;for(let u of e.records){let m=s.map(g=>u[g]),y=[];for(let g=0;g<s.length;g++){let T=m[g];T instanceof D?y.push(T.rawValue):(l.push(T),y.push(`$${c++}${this.formatTypeCast(T)}`));}d.push(`(${y.join(", ")})`);}let p=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let u=e.returning.map(m=>r.formatStringColumn("postgres",m)).join(", ");p+=` returning ${u}`;}else p+=" returning *";return {sql:p,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Zc=new Pi;var $i=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n),d=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"postgres");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Xc=new $i;var Ei=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},em=new Ei;var _f={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},Bi=class{toSql(t){let e=t,r=_f[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},tm=new Bi;var vi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},rm=new vi;var ki=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("postgres",a)).join(", ");if(e.mode==="ignore")return {sql:`on conflict (${o}) do nothing`,bindings:[]};let n=e.columnsToUpdate.map(a=>`${r.formatStringColumn("postgres",a)} = excluded.${r.formatStringColumn("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}else s+=" returning *";return {sql:s,bindings:[]}}},om=new ki;var Qi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},nm=new Qi;var Ki=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},sm=new Ki;var Li=class{toSql(t){return {sql:`SELECT
129
129
  con.conname AS name,
130
130
  pg_get_constraintdef(con.oid) AS expression
131
131
  FROM pg_constraint con
@@ -133,7 +133,7 @@ ORDER BY column_id`,bindings:[]}}},rc=new Ks;var Ls=class{toSql(t){let e=t;if(e.
133
133
  JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
134
134
  WHERE con.contype = 'c'
135
135
  AND rel.relname = '${t.table}'
136
- AND nsp.nspname = current_schema()`,bindings:[]}}},Yc=new $i;var Ei=class{toSql(t){return {sql:`SELECT
136
+ AND nsp.nspname = current_schema()`,bindings:[]}}},im=new Li;var Wi=class{toSql(t){return {sql:`SELECT
137
137
  tc.constraint_name as name,
138
138
  kcu.column_name as column_name,
139
139
  ccu.table_name as referenced_table,
@@ -148,7 +148,7 @@ ORDER BY column_id`,bindings:[]}}},rc=new Ks;var Ls=class{toSql(t){let e=t;if(e.
148
148
  JOIN information_schema.referential_constraints rc
149
149
  ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema
150
150
  WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
151
- ORDER BY kcu.ordinal_position`,bindings:[]}}},Gc=new Ei;var Bi=class{toSql(t){return {sql:`SELECT
151
+ ORDER BY kcu.ordinal_position`,bindings:[]}}},am=new Wi;var Fi=class{toSql(t){return {sql:`SELECT
152
152
  i.relname as index_name,
153
153
  a.attname as column_name,
154
154
  ix.indisunique as is_unique
@@ -167,14 +167,14 @@ ORDER BY column_id`,bindings:[]}}},rc=new Ks;var Ls=class{toSql(t){let e=t;if(e.
167
167
  AND t.relname = '${t.table}'
168
168
  AND t.relnamespace = n.oid
169
169
  AND n.nspname = current_schema()
170
- AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},Zc=new Bi;var vi=class{toSql(t){return {sql:`SELECT
170
+ AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},lm=new Fi;var ji=class{toSql(t){return {sql:`SELECT
171
171
  tc.constraint_name as name,
172
172
  kcu.column_name as column_name
173
173
  FROM information_schema.table_constraints tc
174
174
  JOIN information_schema.key_column_usage kcu
175
175
  ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
176
176
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
177
- ORDER BY kcu.ordinal_position`,bindings:[]}}},Xc=new vi;var ki=class{toSql(t){return {sql:`SELECT column_name,
177
+ ORDER BY kcu.ordinal_position`,bindings:[]}}},dm=new ji;var Ui=class{toSql(t){return {sql:`SELECT column_name,
178
178
  data_type,
179
179
  is_nullable,
180
180
  column_default,
@@ -184,13 +184,13 @@ ORDER BY column_id`,bindings:[]}}},rc=new Ks;var Ls=class{toSql(t){let e=t;if(e.
184
184
  FROM information_schema.columns
185
185
  WHERE table_schema = current_schema()
186
186
  AND table_name = '${t.table}'
187
- ORDER BY ordinal_position`,bindings:[]}}},em=new ki;var Qi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",d=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(d))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),d=0;for(let c of l)c==="("&&d++,c===")"&&d--;if(d>0)return e}return `as "${r}"`})}},tm=new Qi;var Ki=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=le.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},rm=new Ki;var Li=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},om=new Li;var Wi=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},nm=new Wi;var Fi=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let c=e.currParamIndex+d-n,p=e.values[d];return p instanceof x?(n++,`${r.formatStringColumn("postgres",l)} = ${p.rawValue}`):(s.push(p),`${r.formatStringColumn("postgres",l)} = $${c}${this.formatTypeCast(p)}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},sm=new Fi;var ji=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new h(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("postgres",t):t}},im=new ji;var Ui=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},am=new Ui;var Vi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},lm=new Vi;var Ji=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},dm=new Ji;var Hi=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},um=new Hi;var zi=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},cm=new zi;var Yi=class{toSql(t){return {sql:"",bindings:[]}}},mm=new Yi;var Gi=class{toSql(t){return {sql:"",bindings:[]}}},pm=new Gi;var Zi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[],l=false;for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(!(!m||!m.trim())){if(u.file==="add_column")s.push(m),l=true;else if(u.file==="add_constraint"&&l){let g=s.pop()??"",T=m.replace(/^\s*add\s+/i,"").trimStart();s.push(`${g} ${T}`);}else {if(u.file==="set_not_null"||u.file==="drop_not_null")continue;if(u.file==="set_default"||u.file==="drop_default")continue;s.push(m),l=false;}a.push(...y);}}let d=s.join(", "),c=e.ifExists?"if exists ":"";return d.trim()?{sql:`${c}${o} ${d}`,bindings:a}:{sql:"",bindings:[]}}},fm=new Zi;var Xi=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},ym=new Xi;var ea=class{toSql(t){return {sql:"",bindings:[]}}},hm=new ea;var ta=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},gm=new ta;var ra=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},bm=new ra;var oa=class{toSql(t){return {sql:"",bindings:[]}}},Tm=new oa;var na=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},wm=new na;var sa=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Nm=new sa;var ia=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Sm=new ia;var aa=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},qm=new aa;var la=class{toSql(t){return {sql:"",bindings:[]}}},Mm=new la;var da=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("sqlite",S(e.column)),n=e.dataType.toLowerCase();if(n==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let s=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(s+=" default current_timestamp"),{sql:s,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Cm=new da;var ua=class{toSql(t){return {sql:"",bindings:[]}}},Rm=new ua;var ca=class{toSql(t){let e=t,r=new h(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",S(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof x?{sql:`default ${n.rawValue}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(d=>r.formatStringColumn("sqlite",S(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",S(d))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},_m=new ca;var ma=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[];for(let g of e.children){let{sql:T,bindings:N}=n.parse([g]);if(g.folder==="constraint"){let M=s.pop()??"",O=T;if(/not null/i.test(O)||/null/i.test(O)||/default/i.test(O)||/primary key/i.test(O)){let R=`${M} ${O}`.trim();R=R.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(R),a.push(...N);continue}s.push(M),s.push(O),a.push(...N);continue}s.push(T),a.push(...N);}for(let g of e.namedConstraints){let{sql:T,bindings:N}=n.parse([g]);s.push(T),a.push(...N);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.sqliteTemporary&&c.push("TEMPORARY");let p=c.length>0?`${c.join(" ")} `:"",u=e.withoutRowId?" WITHOUT ROWID":"",m=e.strict?" STRICT":"";return {sql:`${d}${p}${o} (${l})${u}${m}`,bindings:a}}},Om=new ma;var pa=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},Am=new pa;var fa=class{toSql(t){return {sql:"distinct",bindings:[]}}},xm=new fa;var ya=class{toSql(t){return q.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Im=new ya;var ha=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Dm=new ha;var ga=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},Pm=new ga;var ba=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},$m=new ba;var Ta=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Em=new Ta;var wa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Bm=new wa;var Na=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},vm=new Na;var Sa=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},km=new Sa;var qa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("sqlite",p)).join(", "),l=[],d=[];for(let p of e.records){let u=s.map(y=>p[y]),m=[];for(let y of u)y instanceof x?m.push(y.rawValue):(l.push(y),m.push("?"));d.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Qm=new qa;var Ma=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n),d=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"sqlite");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Km=new Ma;var Ca=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},Lm=new Ca;var Ra=class{toSql(t){return {sql:"",bindings:[]}}},Wm=new Ra;var _a=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Fm=new _a;var Oa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(s=>r.formatStringColumn("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumn("sqlite",s)} = EXCLUDED.${r.formatStringColumn("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},jm=new Oa;var Aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Um=new Aa;var xa=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Vm=new xa;var Ia=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},Jm=new Ia;var Da=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},Hm=new Da;var Pa=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},zm=new Pa;var $a=class{toSql(t){return {sql:`SELECT
187
+ ORDER BY ordinal_position`,bindings:[]}}},um=new Ui;var Vi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",d=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(d))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),d=0;for(let c of l)c==="("&&d++,c===")"&&d--;if(d>0)return e}return `as "${r}"`})}},cm=new Vi;var Ji=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},mm=new Ji;var Hi=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},pm=new Hi;var zi=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},fm=new zi;var Yi=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let c=e.currParamIndex+d-n,p=e.values[d];return p instanceof D?(n++,`${r.formatStringColumn("postgres",l)} = ${p.rawValue}`):(s.push(p),`${r.formatStringColumn("postgres",l)} = $${c}${this.formatTypeCast(p)}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},ym=new Yi;var Gi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new h(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("postgres",t):t}},hm=new Gi;var Zi=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},gm=new Zi;var Xi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},bm=new Xi;var ea=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Tm=new ea;var ta=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},wm=new ta;var ra=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Nm=new ra;var oa=class{toSql(t){return {sql:"",bindings:[]}}},Sm=new oa;var na=class{toSql(t){return {sql:"",bindings:[]}}},Cm=new na;var sa=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[],l=false;for(let u of e.children){let{sql:m,bindings:y}=n.parse([u]);if(!(!m||!m.trim())){if(u.file==="add_column")s.push(m),l=true;else if(u.file==="add_constraint"&&l){let g=s.pop()??"",T=m.replace(/^\s*add\s+/i,"").trimStart();s.push(`${g} ${T}`);}else {if(u.file==="set_not_null"||u.file==="drop_not_null")continue;if(u.file==="set_default"||u.file==="drop_default")continue;s.push(m),l=false;}a.push(...y);}}let d=s.join(", "),c=e.ifExists?"if exists ":"";return d.trim()?{sql:`${c}${o} ${d}`,bindings:a}:{sql:"",bindings:[]}}},qm=new sa;var ia=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Mm=new ia;var aa=class{toSql(t){return {sql:"",bindings:[]}}},Rm=new aa;var la=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},_m=new la;var da=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Om=new da;var ua=class{toSql(t){return {sql:"",bindings:[]}}},Am=new ua;var ca=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},xm=new ca;var ma=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Dm=new ma;var pa=class{toSql(t){let e=t,r;return e.defaultValue instanceof D?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Im=new pa;var fa=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Pm=new fa;var ya=class{toSql(t){return {sql:"",bindings:[]}}},$m=new ya;var ha=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("sqlite",S(e.column)),n=e.dataType.toLowerCase();if(n==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let s=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(s+=" default current_timestamp"),{sql:s,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Em=new ha;var ga=class{toSql(t){return {sql:"",bindings:[]}}},Bm=new ga;var ba=class{toSql(t){let e=t,r=new h(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",S(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof D?{sql:`default ${n.rawValue}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(d=>r.formatStringColumn("sqlite",S(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",S(d))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},vm=new ba;var Ta=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[];for(let g of e.children){let{sql:T,bindings:N}=n.parse([g]);if(g.folder==="constraint"){let M=s.pop()??"",A=T;if(/not null/i.test(A)||/null/i.test(A)||/default/i.test(A)||/primary key/i.test(A)){let _=`${M} ${A}`.trim();_=_.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(_),a.push(...N);continue}s.push(M),s.push(A),a.push(...N);continue}s.push(T),a.push(...N);}for(let g of e.namedConstraints){let{sql:T,bindings:N}=n.parse([g]);s.push(T),a.push(...N);}let l=s.join(", "),d=e.ifNotExists?"if not exists ":"",c=[];e.sqliteTemporary&&c.push("TEMPORARY");let p=c.length>0?`${c.join(" ")} `:"",u=e.withoutRowId?" WITHOUT ROWID":"",m=e.strict?" STRICT":"";return {sql:`${d}${p}${o} (${l})${u}${m}`,bindings:a}}},km=new Ta;var wa=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},Qm=new wa;var Na=class{toSql(t){return {sql:"distinct",bindings:[]}}},Km=new Na;var Sa=class{toSql(t){return q.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Lm=new Sa;var Ca=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Wm=new Ca;var qa=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},Fm=new qa;var Ma=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},jm=new Ma;var Ra=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Um=new Ra;var _a=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Vm=new _a;var Oa=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Jm=new Oa;var Aa=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},Hm=new Aa;var xa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("sqlite",p)).join(", "),l=[],d=[];for(let p of e.records){let u=s.map(y=>p[y]),m=[];for(let y of u)y instanceof D?m.push(y.rawValue):(l.push(y),m.push("?"));d.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},zm=new xa;var Da=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n),d=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,c=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new b(this.model,"sqlite");for(let u of e.additionalConditions){let m=p.parse([u]);if(m.sql){let y=m.sql.replace(/^where\s+/i,"");d+=` and ${y}`,c.push(...m.bindings);}}}return {sql:d,bindings:c}}},Ym=new Da;var Ia=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},Gm=new Ia;var Pa=class{toSql(t){return {sql:"",bindings:[]}}},Zm=new Pa;var $a=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Xm=new $a;var Ea=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(s=>r.formatStringColumn("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumn("sqlite",s)} = EXCLUDED.${r.formatStringColumn("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},ep=new Ea;var Ba=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},tp=new Ba;var va=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},rp=new va;var ka=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},op=new ka;var Qa=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},np=new Qa;var Ka=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},sp=new Ka;var La=class{toSql(t){return {sql:`SELECT
188
188
  'PRIMARY' as name,
189
189
  name as column_name
190
190
  FROM pragma_table_info('${t.table}')
191
191
  WHERE pk > 0
192
- ORDER BY pk`,bindings:[]}}},Ym=new $a;var Ea=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Gm=new Ea;var Ba=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",d=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(d))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),d=0;for(let c of l)c==="("&&d++,c===")"&&d--;if(d>0)return e}return `as "${r}"`})}},Zm=new Ba;var va=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=le.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Xm=new va;var ka=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new h(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},ep=new ka;var Qa=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},tp=new Qa;var Ka=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof x?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},rp=new Ka;var La=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("sqlite",t):t}},op=new La;var Wa=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},np=new Wa;var Fa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},sp=new Fa;var ja=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},ip=new ja;var Ua=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},ap=new Ua;var lp={mssql:{alter_table:{add_column:Tl,add_constraint:wl,add_primary_key:Nl,alter_column_type:Sl,alter_table:ql,drop_column:Ml,drop_constraint:Cl,drop_default:Rl,drop_not_null:_l,drop_primary_key:Ol,rename_column:Al,rename_table:xl,set_default:Il,set_not_null:Dl,set_table_options:Pl},column:{column_type:$l},constraint:{after:El,constraint:Bl},create_table:{create_table:vl},delete:{delete:kl},distinct:{distinct:Ql,distinct_on:Kl},drop_table:{drop_table:Ll},extension:{create_extension:Wl},from:{from:Fl},group_by:{group_by:jl},having:{having:Ul},index_op:{create_index:Vl,drop_index:Jl},insert:{insert:Hl},join:{join:zl},limit:{limit:Yl},lock:{lock:Gl},offset:{offset:Zl},on_duplicate:{on_duplicate:Xl},order_by:{order_by:ed},raw:{raw:td},schema:{check_constraint_info:rd,foreign_key_info:od,index_info:nd,primary_key_info:sd,table_info:id},select:{select:ad,select_json:ld},truncate:{truncate:dd},union:{union:ud},update:{update:cd},where:{where:md,where_group:pd,where_json:fd,where_subquery:yd},with:{with:hd}},mysql:{alter_table:{add_column:gd,add_constraint:bd,add_primary_key:Td,alter_column_type:wd,alter_table:Nd,drop_column:Sd,drop_constraint:qd,drop_default:Md,drop_not_null:Cd,drop_primary_key:Rd,rename_column:_d,rename_table:Od,set_default:Ad,set_not_null:xd,set_table_options:Id},column:{column_type:Dd},constraint:{after:Pd,constraint:$d},create_table:{create_table:Ed},delete:{delete:Bd},distinct:{distinct:vd,distinct_on:kd},drop_table:{drop_table:Qd},extension:{create_extension:Kd},from:{from:Ld},group_by:{group_by:Wd},having:{having:Fd},index_op:{create_index:jd,drop_index:Ud},insert:{insert:Vd},join:{join:Jd},limit:{limit:Hd},lock:{lock:zd},offset:{offset:Yd},on_duplicate:{on_duplicate:Gd},order_by:{order_by:Zd},raw:{raw:Xd},schema:{check_constraint_info:eu,foreign_key_info:tu,index_info:ru,primary_key_info:ou,table_info:nu},select:{select:su,select_json:iu},truncate:{truncate:au},union:{union:lu},update:{update:du},where:{where:uu,where_group:cu,where_json:mu,where_subquery:pu},with:{with:fu}},oracledb:{alter_table:{add_column:yu,add_constraint:hu,add_primary_key:gu,alter_column_type:bu,alter_table:Tu,drop_column:wu,drop_constraint:Nu,drop_default:Su,drop_not_null:qu,drop_primary_key:Mu,rename_column:Cu,rename_table:Ru,set_default:_u,set_not_null:Ou,set_table_options:Au},column:{column_type:xu},constraint:{after:Iu,constraint:Du},create_table:{create_table:Pu},delete:{delete:$u},distinct:{distinct:Eu,distinct_on:Bu},drop_table:{drop_table:vu},extension:{create_extension:ku},from:{from:Qu},group_by:{group_by:Ku},having:{having:Lu},index_op:{create_index:Wu,drop_index:Fu},insert:{insert:ju},join:{join:Uu},limit:{limit:Vu},lock:{lock:Ju},offset:{offset:Hu},on_duplicate:{on_duplicate:zu},order_by:{order_by:Yu},raw:{raw:Gu},schema:{check_constraint_info:Zu,foreign_key_info:Xu,index_info:ec,primary_key_info:tc,table_info:rc},select:{select:oc,select_json:nc},truncate:{truncate:sc},union:{union:ic},update:{update:ac},where:{where:lc,where_group:dc,where_json:uc,where_subquery:cc},with:{with:mc}},postgres:{alter_table:{add_column:pc,add_constraint:fc,add_primary_key:yc,alter_column_type:hc,alter_table:gc,drop_column:bc,drop_constraint:Tc,drop_default:wc,drop_not_null:Nc,drop_primary_key:Sc,rename_column:qc,rename_table:Mc,set_default:Cc,set_not_null:Rc,set_table_options:_c},column:{column_type:Oc},constraint:{after:Ac,constraint:xc},create_table:{create_table:Ic},delete:{delete:Dc},distinct:{distinct:Pc,distinct_on:$c},drop_table:{drop_table:Ec},extension:{create_extension:Bc},from:{from:vc},group_by:{group_by:kc},having:{having:Qc},index_op:{create_index:Kc,drop_index:Lc},insert:{insert:Wc},join:{join:Fc},limit:{limit:jc},lock:{lock:Uc},offset:{offset:Vc},on_duplicate:{on_duplicate:Jc},order_by:{order_by:Hc},raw:{raw:zc},schema:{check_constraint_info:Yc,foreign_key_info:Gc,index_info:Zc,primary_key_info:Xc,table_info:em},select:{select:tm,select_json:rm},truncate:{truncate:om},union:{union:nm},update:{update:sm},where:{where:im,where_group:am,where_json:lm,where_subquery:dm},with:{with:um}},sqlite:{alter_table:{add_column:cm,add_constraint:mm,alter_column_type:pm,alter_table:fm,drop_column:ym,drop_constraint:hm,drop_default:gm,drop_not_null:bm,drop_primary_key:Tm,rename_column:wm,rename_table:Nm,set_default:Sm,set_not_null:qm,set_table_options:Mm},column:{column_type:Cm},constraint:{after:Rm,constraint:_m},create_table:{create_table:Om},delete:{delete:Am},distinct:{distinct:xm,distinct_on:Im},drop_table:{drop_table:Dm},extension:{create_extension:Pm},from:{from:$m},group_by:{group_by:Em},having:{having:Bm},index_op:{create_index:vm,drop_index:km},insert:{insert:Qm},join:{join:Km},limit:{limit:Lm},lock:{lock:Wm},offset:{offset:Fm},on_duplicate:{on_duplicate:jm},order_by:{order_by:Um},raw:{raw:Vm},schema:{check_constraint_info:Jm,foreign_key_info:Hm,index_info:zm,primary_key_info:Ym,table_info:Gm},select:{select:Zm,select_json:Xm},truncate:{truncate:ep},union:{union:tp},update:{update:rp},where:{where:op,where_group:np,where_json:sp,where_subquery:ip},with:{with:ap}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(R=>!!R&&R.folder==="distinctOn"),n=!o&&t.find(R=>!!R&&R.folder==="distinct"),s=this.dbType==="mssql"?t.find(R=>!!R&&R.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(R=>R!==null&&R.folder!=="distinct"&&R.folder!=="distinctOn"),d=l.some(R=>R.folder==="offset"),c=l.some(R=>R.folder==="order_by"),p=l.find(R=>R.folder==="limit"),u=l.find(R=>R.folder==="offset"),m=this.dbType==="mssql"&&p&&!d&&!c,y=this.dbType==="mssql"&&!m&&(p||u),g=this.dbType==="oracledb"&&(p||u),T=[],N=[],M=null;m&&p&&N.push(p.limit);for(let R=0;R<l.length;R++){let D=l[R];if(m&&D.folder==="limit"||y&&(D.folder==="limit"||D.folder==="offset")||g&&(D.folder==="limit"||D.folder==="offset"))continue;D.currParamIndex=e+N.length;let P=lp[this.mapCommonDbType(this.dbType)][D.folder][D.file];if(!P)throw new Error(`Interpreter not found for ${this.dbType} ${D.keyword}`);P.model=this.model;let _=P.toSql(D);if(!_.sql||!_.sql.trim().length)continue;let K=l[R+1],$=!K||K.keyword!==D.keyword?"":K.chainsWith;if(D.folder==="lock"||D.folder==="on_duplicate"||D.folder==="schema"){T.push(`${_.sql}${$}`),N.push(..._.bindings),M=D.keyword;continue}if(M!==D.keyword||D.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let G=D.keyword;if(D.folder==="with"&&this.dbType!=="mssql"){let X=R,Ne=false;for(;X<l.length&&l[X].keyword===D.keyword;){let _e=l[X];if(_e.folder==="with"&&_e.clause==="recursive"){Ne=true;break}X++;}Ne&&(G=`${G} recursive`);}if(G==="select"){let X=m?`top (@${e}) `:"";if(o){let Ne=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${X}distinct on (${Ne}) ${_.sql}${$}`);}else n?T.push(`select ${X}distinct ${_.sql}${$}`):T.push(`select ${X}${_.sql}${$}`);}else G==="from"&&a?T.push(`${G} ${_.sql}${a}${$}`):T.push(`${G} ${_.sql}${$}`);}M=D.keyword;}else T.push(`${_.sql}${$}`);N.push(..._.bindings);}if(y){c||T.push("order by (select null)");let R=u?.offset??0;N.push(R);let P=`offset @${e+N.length-1} rows`;if(p){N.push(p.limit);let _=e+N.length-1;P+=` fetch next @${_} rows only`;}T.push(P);}if(g){c||T.push("order by null");let R=u?.offset??0;N.push(R);let P=`offset :${e+N.length-1} rows`;if(p){N.push(p.limit);let _=e+N.length-1;P+=` fetch next :${_} rows only`;}T.push(P);}return {sql:T.join(" "),bindings:N}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}getMssqlTableHints(t){let e=[];switch(t.lockType){case "UPDATE":e.push("UPDLOCK");break;case "SHARE":e.push("HOLDLOCK");break;case "NO_KEY_UPDATE":e.push("UPDLOCK");break;case "KEY_SHARE":e.push("HOLDLOCK");break}return t.skipLocked&&e.push("READPAST"),t.noWait&&e.push("NOWAIT"),e.length>0?` with (${e.join(", ")})`:""}};var kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var Qt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Lt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Wt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Ft=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ce=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var rt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var jt=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var me=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var Ut=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var pe=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var pt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Vt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var ot=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Jt=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Ht=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var zt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Fe=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var j=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var Yt=class extends w{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var Gt=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var Zt=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var Xt=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var er=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var nt=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var tr=Symbol("columns"),st=Symbol("primaryKey"),fe=Symbol("relations"),rr=Symbol("indexes"),or=Symbol("uniques"),nr=Symbol("checks"),Ie=i=>`${Sf__default.default.singular(i)}_id`,sr=(i,t)=>`idx_${i}_${t}`,de=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,De=(i,t)=>`pk_${i}_${t}`,dp=(i,t)=>{let e=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_|_$/g,"").toLowerCase();return `chk_${i}_${e}`.substring(0,63)};var B=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false;}};var ft=class extends w{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var je=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var it=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var Pe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var ir=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var ar=class extends Pe{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=De(this.tableName,S(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??Z(this.tableName??"",S(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new j("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new j("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}notNullable(){return this.nodes.push(new j("not_null",{columns:[S(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new j("null",{columns:[S(this.columnNode.column)]})),this}default(t){let e;return t instanceof x?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new j("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new j("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??de(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new j("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||de(this.tableName??"",S(this.columnNode.column))})),this)}check(t,e){let r=S(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new j("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new j("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new ir(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ue=class extends Pe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new ar(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new x(e)}char(e,r=1){let o=new B(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new B(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new B(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new B(e,"uuid");return this.build(r)}ulid(e){let r=new B(e,"ulid");return this.build(r)}integer(e,r=255){let o=new B(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new B(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new B(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new B(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new B(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new B(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new B(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new B(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new B(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new B(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new B(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new B(e,"time",{precision:r});return this.build(o)}year(e){let r=new B(e,"year");return this.build(r)}datetime(e,r){let o=new B(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new B(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new B(e,"boolean");return this.build(r)}binary(e){let r=new B(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new B(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new B(e,"blob");return this.build(r)}tinyblob(e){let r=new B(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new B(e,"mediumblob");return this.build(r)}longblob(e){let r=new B(e,"longblob");return this.build(r)}json(e){let r=new B(e,"json");return this.build(r)}jsonb(e){let r=new B(e,"jsonb");return this.build(r)}enum(e,r){let o=new B(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new B(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new B(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new B(e,"geometry");return this.build(r)}point(e){let r=new B(e,"point");return this.build(r)}linestring(e){let r=new B(e,"linestring");return this.build(r)}polygon(e){let r=new B(e,"polygon");return this.build(r)}multiPoint(e){let r=new B(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var lr=class extends Pe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new x(t)}addColumn(t){let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let u=p;return u.constraintType==="not_null"||u.constraintType==="null"||u.constraintType==="default"}),d=new Ft(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(p=>{let u=p;return u.constraintType==="unique"||u.constraintType==="foreign_key"||u.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new ce(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(m=>m.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=S(s.column),l=o.getNodes().find(m=>m.constraintType==="null"),c=o.getNodes().find(m=>m.constraintType==="not_null")||l,p=o.getNodes().find(m=>m.constraintType==="default"),u={};c&&(u.nullable=c.constraintType==="null"),p&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?u.dropDefault=true:u.default=p.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(u.collate=s.collate),this.nodes.push(new jt(S(a),s,u)),c&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(c.constraintType==="not_null"?this.nodes.push(new zt(S(a))):c.constraintType==="null"&&this.nodes.push(new Vt(S(a)))),p&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?this.nodes.push(new pt(S(a))):this.nodes.push(new Ht(S(a),p.defaultValue))),o.getNodes().forEach(m=>{let y=m;switch(y.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:y.constraintName});break;case "foreign_key":this.foreignKey(S(a),y.references?.table??"",S(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ut(t));}renameColumn(t,e){this.nodes.push(new Jt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new rt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new j(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new j("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??Z(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new j("unique",{columns:[t],constraintName:e?.constraintName??de(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=Z(this.table,t,e);this.nodes.push(new pe(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new f("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??de(this.table,t);this.nodes.push(new pe(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new f("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new ot(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Fe(t)):r?this.nodes.push(new Fe(t)):o?this.nodes.push(new Fe(t)):n&&this.nodes.push(new Fe(t)),this)}};var ne=class{constructor(t){if(this.sqlType=t||A.DB_TYPE,!this.sqlType)throw new f("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new x(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!up__default.default.existsSync(t))throw new f("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=It__default.default.basename(t),r=It__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new f("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=up__default.default.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Ue(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new Yt(t,n,o.getNamedConstraints(),r?.ifNotExists,a),d=s.parse([l]).sql,c=d.startsWith("create table")?d:`create table ${d}`;this.rawQuery(c),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new lr(t,r,this.sqlType);if(e(o),!r.length)return;let n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let d=new me(t,s),c=n.parse([d]).sql;if(!c||!c.trim())return;let p=c.startsWith("alter table")?c:`alter table ${c}`;this.rawQuery(p),s=[];};for(let d of r)d.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(d);a();let l=r.filter(d=>d.file==="add_column").map(d=>d.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new Gt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new me(t,[new tt(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new nt(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let o=r.constraintName||sr(t,e.join("_")),n=new Xt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new er(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new rt(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??de(t,o.join("_")),s=new j("unique",{columns:o,constraintName:n}),a=new me(t,[new ce(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=Z(t,e,r),n=new pe(o),s=new me(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?de(t,e.join("_")):de(t,e),n=r?.constraintName??o,s=new pe(n),a=new me(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new ot,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new j(...e),o=new me(t,[new ce(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new pe(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new j("check",{checkExpression:e,constraintName:o}),s=new me(t,[new ce(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new pe(e),o=new me(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new Zt(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>S(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new b(t,this.sqlType)}};var dr,mp,yt=class{constructor(t,e){Dt(this,dr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new ne(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=nl(this,dr,mp).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
193
- `)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}};dr=new WeakSet,mp=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var ur=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let c of d)c.type==="belongsTo"&&c.model().table===n.table&&a.push(`fk.${l.table}.${c.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(d=>d.table===n.table);if(l){let d=l.getColumns().find(c=>c.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let c=l.getRelations();for(let p of c)p.columnName===d.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let d of l)s(d);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),d=t.relationsToDrop?.find(c=>c.table===a&&c.relation.name===l);d&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:d,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(d)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let d of l)d.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):d.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(d=>d.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var cr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new ur(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let d=r(l);return d?!(s.has(d)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new ne(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(d=>d.table===o.table)?.getColumns().find(d=>d.columnName===o.columns[0])?.primaryKeyConstraintName||De(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,d=>{let c=a||De(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:c});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(c=>c.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new ne(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new ne(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=S(t.relation.constraintName);if(e)return e;let r=t.table;t.relation.type==="belongsTo"?r=t.relation.model().table:t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(r=S(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,Z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=S(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s=e[r.type](...o);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||De(t,r.columnName)}),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new ne(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=S(t.relation.manyToManyOptions.throughModel),r=S(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=S(r);if(t.relation.type==="belongsTo"){let u=t.relation.model(),m=u.primaryKey,g=u.getColumns().find(T=>T.columnName===m);if(g)n=g.databaseName;else {let T=u?.databaseCaseConvention||"preserve";n=L(m,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let u=t.relation.model();if(typeof n=="string"&&n){let m=u.getColumns(),y=m.find(g=>g.columnName===n);if(y)n=y.databaseName;else {let g=u.primaryKey||"id",T=m.find(N=>N.columnName===g);if(T)n=T.databaseName;else {let N=u?.databaseCaseConvention||"preserve";n=L(n||g,N);}}}else {let m=u.primaryKey||"id",g=u.getColumns().find(T=>T.columnName===m);if(g)n=g.databaseName;else {let T=u?.databaseCaseConvention||"preserve";n=L(m,T);}}}let s=this.models.find(u=>u.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(u=>u.columnName===l);if(d)l=d.databaseName;else {let u=s?.databaseCaseConvention||"preserve";l=L(l,u);}if(t.relation.type==="belongsTo"){let u=a.find(m=>m.columnName===t.relation.foreignKey);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=L(t.relation.foreignKey,m);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let u=t.relation.manyToManyOptions.leftForeignKey,m=S(u),y=a.find(g=>g.columnName===m);if(y)l=y.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=L(m,g);}}let c=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,u=>{let m=o||Z(t.table,l,e);u.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:m,onDelete:c,onUpdate:p});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>sqlFormatter.format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};function Cf(i){return i.replace(/\s+/g," ").trim()}function Rf(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function $e(i,t){let e=Cf(t.toLowerCase()),r=Rf(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var mr=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql.models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(u=>u?.type!==void 0&&u?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let y of n.indexes)o.indexes.map(g=>g.name).includes(y.name)||e.data.indexesToAdd.push({table:r.table,index:y.name});let u=r.getUniques?.()||[];for(let y of u)e.data.uniquesToAdd.push({table:r.table,name:y.name||"mandatory",columns:y.columns});let m=r.getChecks?.()||[];for(let y of m)e.data.checksToAdd.push({table:r.table,name:y.name,expression:y.expression});for(let y of n.relations){if(y.type!=="belongsTo")continue;let g=S(y.constraintName);o.foreignKeys.find(N=>N.name===g)||e.data.relationsToAdd.push({table:r.table,relation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}return}for(let u of n.columns)o.columns.some(y=>y.name===u.databaseName||y.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(y=>y.databaseName===u.name||y.columnName===u.name)||e.data.columnsToDrop.push({table:r.table,column:u.name});for(let u of n.indexes)o.indexes.map(m=>m.name).includes(u.name)||e.data.indexesToAdd.push({table:r.table,index:u.name});let s=r.getUniques?.()||[];for(let u of s)o.indexes.some(y=>y.name===u.name&&y.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});let a=o.foreignKeys.map(u=>u.name);for(let u of o.indexes)u.isUnique||a.includes(u.name)||n.indexes.map(y=>y.name).includes(u.name)||e.data.indexesToDrop.push({table:r.table,index:u.name});for(let u of o.indexes){if(!u.isUnique||u.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(y=>y.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}let l=r.getChecks?.()||[];for(let u of l)o.checkConstraints.some(y=>y.name===u.name)||e.data.checksToAdd.push({table:r.table,name:u.name,expression:u.expression});let d=new Set(l.map(u=>u.name));for(let u of o.checkConstraints)d.has(u.name)||e.data.checksToDrop.push({table:r.table,name:u.name});for(let u of n.columns){let m=o.columns.find(T=>T.name===u.databaseName||T.name===u.columnName);if(!m)continue;let y=!e.areColumnsEqual(m,u,o.indexes),g=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:u});(y||g)&&e.data.columnsToModify.push({table:r.table,dbColumns:m,modelColumn:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;if(u.type==="manyToMany"&&u.manyToManyOptions){let g=S(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:g,relation:{type:"belongsTo",model:()=>r,columnName:S(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?S(u.constraintName):Z(g,S(u.manyToManyOptions.leftForeignKey||Ie(r.table)),r.table),onDelete:u.onDelete,onUpdate:u.onUpdate},onDelete:u.onDelete,onUpdate:u.onUpdate});continue}let m=S(u.constraintName);if(m&&o.foreignKeys.some(g=>g.name===m))continue;o.foreignKeys.find(g=>e.relationMatchesDbRelation(r,u,g))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let c=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let m=S(u.foreignKey)||u.columnName,g=r.getColumns().find(T=>T.columnName===m)?.databaseName||m;return S(u.constraintName)||Z(r.table,g,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&c.has(u.name))continue;n.relations.find(y=>y.type!=="belongsTo"&&y.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,y,u))||e.data.relationsToDrop.push({table:r.table,relation:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;let m=o.foreignKeys.find(y=>e.relationMatchesDbRelation(r,u,y));m&&!e.areRelationsEqual(m,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let p=r.primaryKey;if(p&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[p]}),o.primaryKey&&!p&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),p&&o.primaryKey){let u=r.getColumns().find(m=>m.columnName===p);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:p});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getSqlStatementsByPhase(){let t=new cr(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=$e(n,t.dataType),a=typeof e.type=="string"?$e(n,e.type):void 0;a&&o&&(o=s===a),e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;o=o&&d===c;}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),c=d.primaryKey||"id",p=d.getColumns().find(y=>y.columnName===c),u=d.table,m=p?.databaseName||c;o=o&&t.referencedTable===u&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===m;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=S(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===d;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let g=n.model();g&&g.table&&(o=g);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?S(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=S(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),c=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,p=l.find(g=>g.columnName===c);p&&(c=p.databaseName);let u=o.primaryKey||"id",y=o.getColumns().find(g=>g.columnName===u)?.databaseName||u;return r.columns.length===1&&r.columns[0]===c&&r.referencedColumns.length===1&&r.referencedColumns[0]===y}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=$e(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?$e(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",d=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&d?false:"drop";if(s&&a){let c=String(t.dbColumns.defaultValue),p=String(t.modelColumn.constraints?.default),u=this.normalizeDefaultValue(e,r,c),m=this.normalizeDefaultValue(e,o||r,p);return u!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=S(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",c=s.getColumns().find($=>$.columnName===l),p=a.getColumns().find($=>$.columnName===d);if(!c||!p)continue;let u=S(o.manyToManyOptions.leftForeignKey)||l,m=S(o.manyToManyOptions.rightForeignKey)||d,y=await this.sql.getTableSchema(n);if(!y.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(c,u),this.clonePkAsColumn(p,m)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:u,rightFkName:m,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(c,u),T=this.clonePkAsColumn(p,m),N=y.columns.find($=>$.name===u),M=y.columns.find($=>$.name===m),O=N?this.areColumnsEqual(N,g,y.indexes):false,R=M?this.areColumnsEqual(M,T,y.indexes):false;for(let $ of y.foreignKeys){let G=$.referencedTable===s.table,X=$.referencedTable===a.table;if(!G&&!X)continue;let Ne=G?u:m,_e=$.columns[0];_e&&_e!==Ne&&(this.data.relationsToDrop.push({table:n,relation:$}),_e!==u&&_e!==m&&this.data.columnsToDrop.push({table:n,column:_e}));}let D={};O||(D[g.databaseName]=g),R||(D[T.databaseName]=D[T.databaseName]||T);for(let $ of Object.keys(D))this.data.columnsToAdd.push({table:n,column:D[$]});let P=this.buildBelongsToRelation(n,()=>s,u,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,m,d,void 0,o.onDelete,o.onUpdate),K=y.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===u),Ke=y.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===m);if(!K){let $=y.foreignKeys.find(G=>G.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(P);}if(!Ke){let $=y.foreignKeys.find(G=>G.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(_);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,c=o.getColumns().find(u=>u.columnName===l)?.databaseName||l,p=S(a.constraintName)||Z(o.table,c,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(g=>g.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let d=o.table,c=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let T=g.primaryKey||"id";c=g.getColumns().find(M=>M.columnName===T)?.databaseName||T;}let p=new Set([l,o.relation.columnName].filter(Boolean)),u=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let T=p.has(g.columns[0]),N=g.referencedTable===d,M=g.referencedColumns[0]===c;return T&&N&&M}),m=S(o.relation.constraintName)||Z(o.table,l,d),y=e.get(o.table)||new Set;if(u||m&&y.has(m))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=S(o.relation.manyToManyOptions.throughModel),T=S(o.relation.manyToManyOptions.leftForeignKey),N=S(o.relation.manyToManyOptions.rightForeignKey),M=o.table===g&&o.relation.columnName===T&&o.relation.model().table===s?.table,O=o.table===g&&o.relation.columnName===N&&o.relation.model().table!==s?.table,R=await this.sql.getTableSchema(g),D=R.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),P=R.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===N&&_.referencedTable===o.relation.model().table);if(M&&D||O&&P)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(d=>d.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(d=>{if(d.type!=="belongsTo")return false;let p=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,u=d.model(),m=u.primaryKey||"id",g=u.getColumns().find(T=>T.columnName===m)?.databaseName||m;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===u.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?S(n):Z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var at=class extends w{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var F=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var H=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ye=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Me=class extends w{constructor(e,r=[],o=[],n=false){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o;}};var C=class extends w{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var Ee=class extends w{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var se=class extends C{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var Ce=class extends w{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var _f=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Of=/^\d{4}-\d{2}-\d{2}$/,Va=i=>typeof i!="string"?i:_f.test(i)?new Date(i.replace(" ","T")+"Z"):Of.test(i)?new Date(i+"T00:00:00Z"):i,Af=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),fp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Af(r):t[e]=r;}return t};var pr=class extends stream.Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:d=>{s=true,a=d;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(d=>{r=true,this.emit("error",d);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},yp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,c)=>{n.run(i,t,function(p){p&&c(p),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,c)=>{n.all(i,t,(p,u)=>{p&&c(p),(!u||!u.length)&&d([]),d(u);});});let s=r?.typeofModel;if(!s)return new Promise((d,c)=>{n.run(i,t,function(p){p?c(new Error(p.message)):d(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((p,u)=>{n.run(i,t,function(m){if(m)return u(m);let y=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p([y]);return}let g=y?.[a]||this.lastID;if(!g)return u(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[g],(N,M)=>{if(N)return u(N);p([M]);});});});if(!Array.isArray(r.models))throw new f("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((p,u)=>{n.run(i,t,function(m){if(m)return u(m);p(d);});});let c=[];return new Promise(async(p,u)=>{try{let m=d.map(async y=>{let g=new h(s),{columns:T,values:N}=await g.prepareColumns(Object.keys(y),Object.values(y),"insert"),M=Object.fromEntries(T.map((P,_)=>[P,N[_]])),O=new b(s,e.getDbType()),{sql:R,bindings:D}=O.parse([new H(new F(s.table),[M])]);return new Promise((P,_)=>{n.run(R,D,function(K){if(K)return _(K);let Ke=y[a]||this.lastID;if(!Ke)return _(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[Ke],(G,X)=>{if(G)return _(G);P(X);});});})});c=await Promise.all(m),p(c);}catch(m){u(m);}})}return new Promise((d,c)=>{n.run(i,t,function(p){p?c(new Error(p.message)):d(this.changes);});})};var V=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||te(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await ht(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=0,c=i.replace(/\?/g,()=>`$${++d}`),p=await ht(()=>l.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let u=await ht(()=>yp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(u)?u:[u]:u;case "mssql":let m=e.getPool(),y=e.sqlConnection?e.sqlConnection.request():m.request();t.forEach((D,P)=>{y.input(`p${P}`,D);});let g=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${g++}`),N=await ht(()=>y.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?N.rowsAffected[0]:o==="raw"?N:N.recordset;case "oracledb":let M=4002,O=null,R=!!e.sqlConnection;try{O=e.sqlConnection?e.sqlConnection:await e.getConnection();let D=t.map(Va),P=0,_=i.replace(/\?/g,()=>`:${++P}`),K=await ht(()=>O.execute(_,D,{outFormat:M,autoCommit:!R}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?K.rowsAffected:o==="raw"?K:await Promise.all(K.rows?.map(async $=>{let G=await fp($),X={};for(let Ne in G)X[Ne.toLowerCase()]=G[Ne];return X})??[])}finally{O&&!R&&await O.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},yr=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),c=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,u=false,m=false,y=()=>{try{a.release();}catch{}};return c.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,u&&p===0&&!m&&(y(),l.end());}).catch(T=>{m=true,y(),l.destroy(T);});return}l.write(g);}),c.on("end",()=>{u=true,p===0&&!m&&(y(),l.end());}),c.on("error",g=>{m=true,y(),l.destroy(g);}),l.on("close",()=>{y();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new Q("pg-query-stream")}),d=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),c=0,p=i.replace(/\?/g,()=>`$${++c}`),u=new l.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=a.query(u),y=0,g=false,T=false,N=M=>{try{a.release(M);}catch{}};return m.on("data",M=>{if(o.onData){y++,Promise.resolve(o.onData(d,M)).then(()=>{y--,g&&y===0&&!T&&(N(),d.end());}).catch(O=>{T=true,N(O),d.destroy(O);});return}d.write(M);}),m.on("end",()=>{g=true,y===0&&!T&&(N(),d.end());}),m.on("error",M=>{T=true,N(M),d.destroy(M);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new pr(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((y,g)=>{l.input(`p${g}`,y);});let d=0,c=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),p=0,u=false,m=false;return l.on("row",y=>{if(!m){if(o.onData){p++,Promise.resolve(o.onData(a,y)).then(()=>{p--,u&&p===0&&!m&&a.end();}).catch(g=>{m=true,a.destroy(g);});return}a.write(y);}}),l.on("error",y=>{m=true,a.destroy(y);}),l.on("done",()=>{u=true,p===0&&!m&&a.end();}),l.query(c),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,c=0,p=i.replace(/\?/g,()=>`:${++c}`),u=t.map(Va),m=a.queryStream(p,u,{outFormat:d}),y=0,g=false,T=false,N=async()=>{try{await a.close();}catch{}};return m.on("data",M=>{if(T)return;let O={};for(let R in M)O[R.toLowerCase()]=M[R];if(o.onData){y++,Promise.resolve(o.onData(l,O)).then(()=>{y--,g&&y===0&&!T&&(N(),l.end());}).catch(R=>{T=true,N(),l.destroy(R);});return}l.write(O);}),m.on("end",()=>{g=true,y===0&&!T&&(N(),l.end());}),m.on("error",M=>{T=true,N(),l.destroy(M);}),l}default:throw new f("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function ht(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,hl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var W=(i,t="millis",e=3)=>async(...r)=>{let o=performance.now(),n=await i(...r),s=performance.now()-o;return [(t==="millis"?s:s/1e3).toFixed(e),n]};var gt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=hr(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new f("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function gr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function hp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var lt=i=>typeof i=="number"?i:parseFloat(i);var ue=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var Ve=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var br=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Tr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Be=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ie=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var bt=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var wr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Nr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Tt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var Sr=class{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs;let r=this.model?.getColumns;this.modelColumns=typeof r=="function"?r.call(this.model):[],this.modelColumnsMap=new Map(this.modelColumns.map(o=>[o.columnName,o]));}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new bt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new bt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Tt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Tt(t,"asc",true)),this}limit(t){return typeof t!="number"&&q.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new wr(t),this}offset(t){return typeof t!="number"&&q.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Nr(t),this}};var Je=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new C(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new C(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new C(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new C(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new C(t,"and",false,"in",e)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",false,"in",e)),this):(this.whereNodes.push(new C("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"and",true,"in",e)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",true,"in",e)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new C(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new C(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new C(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new C(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Ee(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Ee(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new C(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new C(t,"or",true,"=",e??[],true)),this}};var qr=class extends Sr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ie(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ie(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ie(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ie(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ie(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ie(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new Je(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,d)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new Je(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,d)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new Je(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,d)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new Je(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Mr=class extends qr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new F(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=L(s,this.model.databaseCaseConvention);this.selectNodes.push(new ue(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=L(o,this.model.databaseCaseConvention);this.selectNodes.push(new ue(n));}),this}selectRaw(e){return this.selectNodes.push(new ue(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":L(r,this.model.databaseCaseConvention);return this.selectNodes.push(new ue(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new F(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}from(e){return this.fromNode=new F(e),this}table(e){return this.fromNode=new F(e),this}distinct(){return this.distinctNode=new br,this}distinctOn(...e){return this.distinctOnNode=new Tr(e),this}selectJson(e,r,o){return this.selectNodes.push(new Be(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Be(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Be(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Be(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Be(e,"",r,"raw",true)),this}};var Cr=class extends Mr{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof v&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof v&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new C(e,"and",false,n,new x(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new C(e,"or",false,n,new x(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"and",false,"in",r)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",false,"in",r)),this):(this.whereNodes.push(new C("false","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"in",r)}whereNotIn(e,r){return this.andWhereNotIn(e,r)}andWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"and",true,"in",r)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",true,"in",r)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new C(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new C(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new C(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new C(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ce("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ce("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ce("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ce("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Ve(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Ve(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Ve(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Ve(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof v)return e;let r=new v(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Ce(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Ce(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new v(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new v(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Rr=class extends Cr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"or",false,"raw",e)),this}};var v=class i extends Rr{constructor(e,r=he.instance){super(e,r);this.isNestedCondition=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new b(this.model,this.dbType),this.interpreterUtils=new h(this.model);}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource);return r(n),this.selectNodes.push(new ue(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new ue(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>V(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new f("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await yr(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let s=await this.many(),a=await n.getCount(),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:hp(e,a),data:s},{key:r.discriminator,value:d}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new ft("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new ft("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new je(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new je(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&q.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:gr(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new f("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new F(n,r),this}return this.fromNode=new F(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("normal",e,n)),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new f("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("materialized",e,n)),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,[o],r,n),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((m,y)=>[m,a[y]]));this.insertNode=new H(this.fromNode,[l],r,n);let{sql:d,bindings:c}=this.astParser.parse([this.insertNode]),p=await this.getSqlDataSource("write"),u=await V(d,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(u)&&u.length?u[0]:u})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,o,r,n),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async p=>{let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert");return Object.fromEntries(u.map((y,g)=>[y,m[g]]))}));this.insertNode=new H(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),c=await V(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return c})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new H(new F(this.model.table),[a],void 0,true),this.onDuplicateNode=new ye(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),c=Object.fromEntries(l.map((g,T)=>[g,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([c],s,n,o,[e]);let{sql:p,bindings:u}=this.astParser.parse([new H(new F(this.model.table),[c],void 0,true),new ye(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),m=await this.getSqlDataSource("write"),y=await V(p,u,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(y)?y:[y]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new H(new F(this.model.table),s,void 0,true),this.onDuplicateNode=new ye(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async u=>{let{columns:m,values:y}=await this.interpreterUtils.prepareColumns(Object.keys(u),Object.values(u),"insert"),g=Object.fromEntries(m.map((T,N)=>[T,y[N]]));a.push(g);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:d}=this.astParser.parse([new H(new F(this.model.table),a,void 0,true),new ye(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),c=await this.getSqlDataSource("write"),p=await V(l,d,c,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(p)?p:[p]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),d=K=>this.interpreterUtils.formatStringColumn("mssql",K),c=[],p=e.map(K=>`select ${a.map($=>(c.push(K[$]),`@${c.length}`)).join(", ")}`),u=a.map(d).join(", "),m=p.join(" union all "),y=r.map(K=>`target.${d(K)} = source.${d(K)}`).join(" and "),g=o.filter(K=>!r.includes(K)).map(K=>`target.${d(K)} = source.${d(K)}`).join(", "),T=a.map(d).join(", "),N=a.map(K=>`source.${d(K)}`).join(", "),M=n.returning&&n.returning.length?n.returning.map(K=>`inserted.${d(K)}`).join(", "):a.map(K=>`inserted.${d(K)}`).join(", "),R=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",D=`merge into ${l} as target using (${m}) as source (${u}) on ${y} ${R} when not matched then insert (${T}) values (${N}) output ${M};`,P=await this.getSqlDataSource("write"),_=await V(D,c,P,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(_)?_:[_]}update(e){let r=Object.keys(e),o=Object.values(e);return this.updateNode=new Me(this.fromNode,r,o),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return V(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}truncate(){return this.truncateNode=new nt(this.fromNode),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await V(e,r,o,this.dbType,"rows");})}delete(){return this.deleteNode=new at(this.fromNode),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return V(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=He()}=e||{};return this.updateNode=new Me(this.fromNode,[r],[o]),new U(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return V(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Xe(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new ue("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=J(this.modelSelectedColumns),e.distinctNode=J(this.distinctNode),e.distinctOnNode=J(this.distinctOnNode),e.selectNodes=J(this.selectNodes),e.withQuery=J(this.withQuery),e.joinNodes=J(this.joinNodes),e.whereNodes=J(this.whereNodes),e.groupByNodes=J(this.groupByNodes),e.havingNodes=J(this.havingNodes),e.orderByNodes=J(this.orderByNodes),e.lockQueryNodes=J(this.lockQueryNodes),e.unionNodes=J(this.unionNodes),e.withNodes=J(this.withNodes),e.fromNode=J(this.fromNode),e.limitNode=J(this.limitNode),e.offsetNode=J(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.from(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new ue("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await W(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await W(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await W(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await W(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await W(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await W(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await W(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await W(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await W(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await W(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await W(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await W(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await W(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var dt=class i extends v{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.sqlModelManagerUtils=new gt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=new Map,this.modelColumnsDatabaseNames=new Map,this.model.getColumns().forEach(n=>{this.modelColumnsMap.set(n.databaseName,n),this.modelColumnsDatabaseNames.set(n.databaseName,n.columnName);});}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){return r.connection?new i(e,r.connection):r.trx?new i(e,r.trx.sql):new i(e,e.sqlInstance)}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new f(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a,this.model));if(!o.length)return [];let n=await be(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsRecursively(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await yr(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),c=await be([d],this.model,this.modelSelectedColumns);c&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([c]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([c]),a.write(c));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new f(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(...e){return this.model.insert(...e)}insertMany(...e){return this.model.insertMany(...e)}upsert(...e){return this.model.upsert(...e)}upsertMany(...e){return this.model.upsertMany(...e)}update(e,r={}){let o=super.update(e);return new U(()=>o.unWrap(),()=>o.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),o))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new U(()=>r.unWrap(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=super.delete();return new U(()=>r.unWrap(),()=>r.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),r))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,d]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:gr(e,r,d),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof v)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r){let o=this.sqlModelManagerUtils.getRelationFromModel(e),n=new i(o.model,this.sqlDataSource);return n.relation=o,r?.(n),this.relationQueryBuilders.push(n),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.whereExists(c),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.orWhereExists(c),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.whereNotExists(c),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.orWhereNotExists(c),this}clone(){let e=super.clone();return e.relationQueryBuilders=J(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(u=>{let m=u[e.foreignKey];m&&n.set(String(m),u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=null;return}let y=n.get(String(m));u[e.columnName]=y||null;});break;case "belongsTo":let s=new Map;o.forEach(u=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let m=u[e.model.primaryKey];m&&s.set(String(m),u);}),r.forEach(u=>{let m=u[e.foreignKey];if(!m){u[e.columnName]=null;return}let y=s.get(String(m));u[e.columnName]=y||null;});break;case "hasMany":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(u=>{let m=u[e.foreignKey];if(!m)return;let y=String(m);a.has(y)||a.set(y,[]),a.get(y).push(u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=[];return}let y=a.get(String(m))||[];u[e.columnName]=y;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,c=l.leftForeignKey,p=this.modelColumnsMap.get(c)||this.modelColumnsDatabaseNames.get(c)||L(c,this.model.modelCaseConvention);o.forEach(u=>{let m=u[p];if(m==null)return;let y=String(m);d.has(y)||d.set(y,[]),delete u[p],d.get(y).push(u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=[];return}let y=d.get(String(m))||[];u[e.columnName]=y;});break;default:throw new f(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=Se__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,c=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(d,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${c}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let u=e.modelSelectedColumns.map(_=>zr(_,d,e.model.table));return p.select(...u).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let m=r;if(!o.length)return e;let y=e.limitNode?.limit,g=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!y&&!g)return e.select(...T).select([`${m.throughModel}.${m.leftForeignKey}`,m.leftForeignKey]).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n);let N=Se__default.default.randomBytes(6).toString("hex"),M=`${r.model.table}_cte_${N}`,O=e.orderByNodes.map(_=>{if(_.isRawValue)return _.column;let K=_.column.includes(".")?_.column:`${r.model.table}.${_.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${_.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Se__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,D=e.with(M,_=>_.select(...T).select([`${m.throughModel}.${m.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${m.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,m.leftForeignKey)} ORDER BY ${O}) as rn_${N}`).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n));y&&D.whereRaw(`rn_${N} <= ${y+(g||0)}`),g&&D.whereRaw(`rn_${N} > ${g}`);let P=T.map(_=>zr(_,M,e.model.table));return D.select(...P).select([`${M}.${R}`,m.leftForeignKey]).from(M);default:throw new f(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),c=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(m=>!m.isRawValue&&m.table===d.throughModel&&m.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let p=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new f(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={};return Object.entries(e).forEach(([n,s])=>{if(this.modelColumnsDatabaseNames.get(n)){o[n]=s;return}o[n]=s;}),o}async manyWithPerformance(e={},r="millis"){let[o,n]=await W(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await W(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await W(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await W(this.paginate.bind(this,e,r,{ignoreHooks:s}),n)();return {data:{paginationMetadata:l.paginationMetadata,data:l.data},time:Number(a)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await W(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await W(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await W(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await W(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await W(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await W(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await W(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};function gp(i){let t=i.name.replace(/^_/,""),e=L(t,"snake");return Sf__default.default(e)}function bp(){return {}}var wt=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=bp(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new f(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new f(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(l=>[l,t[l]])),o=!e.returning||e.returning.length===0,n=new H(new F(this.model.table),[r],e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Xe(l,d)};return new U(s,a,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),c={};l.forEach((N,M)=>{let O=d[M];c[N]=O,t[N]??(t[N]=O);});let p=!e.returning||e.returning.length===0,{sql:u,bindings:m}=this.astParser.parse([new H(new F(this.model.table),[c],e.returning,p)]),y=await V(u,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(p)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let g=y[0];return g?(await this.model.afterFetch?.([g]),await be([g],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(l=>Object.fromEntries(Object.keys(l).map(d=>[d,l[d]]))),o=!e.returning||e.returning.length===0,n=new H(new F(this.model.table),r,e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Xe(l,d)};return new U(s,a,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let g=this.model.primaryKey,T=Object.keys(t[0]||{});if(g&&!T.includes(g))return this.handleOracleIdentityInsert(t,e)}let l=[];for(let g of t){let{columns:T,values:N}=await this.interpreterUtils.prepareColumns(Object.keys(g),Object.values(g),"insert"),M={};T.forEach((O,R)=>{let D=N[R];M[O]=D,g[O]??(g[O]=D);}),l.push(M);}let d=!e.returning||e.returning.length===0,{sql:c,bindings:p}=this.astParser.parse([new H(new F(this.model.table),l,e.returning,d)]),u=await V(c,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(u,t,"many",e.returning)||[];let m=u;return m.length?(await this.model.afterFetch?.(m),await be(m,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new H(new F(this.model.table),n,void 0,true),a=new ye(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let c=this.astParser.parse([s,a]);return {sql:xe(this.sqlDataSource,c.sql),bindings:c.bindings}},d=()=>{let{sql:c,bindings:p}=l();return Xe(c,p)};return new U(l,d,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async y=>{let{columns:g,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(y),Object.values(y),"insert"),N=Object.fromEntries(g.map((M,O)=>[M,T[O]]));c.push(N);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let{sql:p,bindings:u}=this.astParser.parse([new H(new F(this.model.table),c,void 0,true),new ye(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await V(p,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=P=>this.interpreterUtils.formatStringColumn("mssql",P),d=[],c=t.map(P=>`select ${s.map(K=>(d.push(P[K]),`@${d.length}`)).join(", ")}`),p=s.map(l).join(", "),u=c.join(" union all "),m=e.map(P=>`target.${l(P)} = source.${l(P)}`).join(" and "),y=r.filter(P=>!e.includes(P)).map(P=>`target.${l(P)} = source.${l(P)}`).join(", "),g=s.map(l).join(", "),T=s.map(P=>`source.${l(P)}`).join(", "),N=o.returning&&o.returning.length?o.returning.map(P=>`inserted.${l(P)}`).join(", "):s.map(P=>`inserted.${l(P)}`).join(", "),O=(o.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",R=`merge into ${a} as target using (${u}) as source (${p}) on ${m} ${O} when not matched then insert (${g}) values (${T}) output ${N};`;return await V(R,d,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}})}async updateRecord(t,e){let r=new Set(this.model.getColumns().map(m=>m.columnName)),o=Object.keys(t).filter(m=>r.has(m)),n=o.map(m=>t[m]),{columns:s,values:a}=await this.interpreterUtils.prepareColumns(o,n,"update"),{primaryKey:l}=this.model;if(!l)throw new f(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=s.indexOf(l);d!==-1&&(s.splice(d,1),a.splice(d,1));let{sql:c,bindings:p}=this.astParser.parse([new Me(new F(this.model.table),s,a),new C(l,"and",false,"=",t[l])]);await V(c,p,this.sqlDataSource,this.sqlType,"affectedRows");let u=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!u)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return u}async deleteRecord(t){if(!this.model.primaryKey)throw new f(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new C(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new at(new F(this.model.table)),e]);await V(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new dt(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await be([a],this.model):null}return await be(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(c=>c[this.model.primaryKey]),l=a.map(c=>`'${c}'`).join(","),d=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((m,y)=>{let g=a[y];l[m]=g,n[m]??(n[m]=g);});let{sql:d,bindings:c}=this.astParser.parse([new H(new F(this.model.table),[l],e.returning)]);await V(d,c,this.sqlDataSource,this.sqlType,"rows");let p=this.query().select(...e.returning||["*"]);for(let[m,y]of Object.entries(l))y!=null&&m!==o&&p.where(m,"=",y);o&&p.orderBy(o,"desc");let u=await p.one({ignoreHooks:["beforeFetch"]});u?(o&&u[o]&&(n[o]=u[o]),r.push(u)):r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let d of n)this.handleWhereCondition(a,d,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,d]=a;o?t.orWhereBetween(e,l,d):t.whereBetween(e,l,d);break}case "$not between":{let[l,d]=a;o?t.orWhereNotBetween(e,l,d):t.whereNotBetween(e,l,d);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Tp=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??He()});var re=class{constructor(t){this.options=t;}static async createDriver(t){throw new f("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var Nt=class Nt extends re{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Nt(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new Q("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new Q("mongodb");return new Nt(this.mongoClient)}};Nt.mongoClient=null;var _r=Nt;var St=class St extends re{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new St(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new Q("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new Q("mssql");return new St(this.mssqlClient)}};St.mssqlClient=null;var Or=St;var qt=class qt extends re{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new qt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new Q("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new Q("mysql2");return new qt(this.mysqlClient)}};qt.mysqlClient=null;var Ar=qt;var Mt=class Mt extends re{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new Mt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new Q("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new Q("oracledb");return new Mt(this.oracledbClient)}};Mt.oracledbClient=null;var xr=Mt;var Ct=class Ct extends re{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Ct(this.pgClient);let e=await import('pg').catch(()=>{throw new Q("pg")});if(this.pgClient=e.default??e,!this.pgClient)throw new Q("pg");return new Ct(this.pgClient)}};Ct.pgClient=null;var Ir=Ct;var Rt=class Rt extends re{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Rt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new Q("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new Q("sqlite3");return new Rt(this.sqlite3Client)}};Rt.sqlite3Client=null;var Dr=Rt;var ae=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Ar.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Ir.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Dr.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await _r.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Or.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await xr.createDriver(),this.oracledbDriver;default:throw new f(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};ae.mysqlDriver=null,ae.pgDriver=null,ae.sqliteDriver=null,ae.mssqlDriver=null,ae.oracledbDriver=null,ae.mongodbDriver=null;var Df=async i=>(await ae.getDriver(i)).client,_t=async(i,t)=>{let e=await Df(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let d=e,c=t,p=c?.database;return new d.Database(p,c?.driverOptions?.mode??void 0,P=>{if(P)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let m=e,y=t,{options:g,...T}=y.driverOptions??{},N=new m.ConnectionPool({server:y.host??"localhost",port:y.port,database:y.database,user:y.username,password:y.password,...T,options:{trustServerCertificate:A.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});return await N.connect(),N;case "oracledb":let M=e,O=t,R=`${O.host}/${O.database}`;return await M.createPool({user:O.username,password:O.password,connectString:R,...O.driverOptions});default:throw new f("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var Ot=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Se__default.default.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),te("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;te("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");q.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":te("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;te("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":te("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw q.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");q.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":te("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;te("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":te("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw q.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new f("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){q.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new f("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new f("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw q.error(e),new Q("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new f("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var ge,Re=class Re extends Ze{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new $t;this.migrationConfig={path:A.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:eo(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Re(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!Le(this,ge))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Le(this,ge)}static async connectToSecondarySource(e,r){let o=new Re(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Re(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.disconnect();}catch(s){throw o.isConnected&&await o.disconnect(),s}}static async disconnect(){if(!Le(this,ge)){q.warn("Connection already closed");return}await Le(this,ge).disconnect(),Fr(this,ge,null);}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!Le(this,ge)?.globalTransaction}async connect(){if(Le(Re,ge))throw new f("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await _t(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await _t(e.sqlType,e.inputDetails),e.ownsPool=true;})),Fr(Re,ge,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new f("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new f("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let c=Xr(JSON.stringify(d)),p=c?`${e}:${c}`:e,u=await this.cacheAdapter.get(p);if(u!==void 0)return u;let m=await n(...d);return await this.cacheAdapter.set(p,m,l),m}async invalidCache(e,...r){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new f("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Xr(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Re(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await _t(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new v(Tp(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new dt(e,this)}schema(){if(!this.isConnected)throw new f("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new yt(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new Ot(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new f("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){q.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new Ot(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new f("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new wt(e,this.globalTransaction.sql):new wt(e,this)}getPool(){if(!this.sqlPool)throw new f("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new f("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new f("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){te("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{q.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){q.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),te("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new f("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){q.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await mr.makeDiff(this)).getSqlStatements();if(!o.length){q.info("No new changes detected between database schema and models metadata");return}if(q.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);q.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),q.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new f("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=xe(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>V(n,r,a,this.getDbType(),"raw")):V(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new x(e)}async getTableSchema(e){let[r,o,n,s,a]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e),this.getCheckConstraintInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s,checkConstraints:a}}getModelOpenApiSchema(){return gl(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Yr(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await fl(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Wt(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(et(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=$e(s,l);return {name:a.name,dataType:d,isNullable:a.notnull===0,defaultValue:a.dflt_value??null,withTimezone:null}}):n.map(a=>{let l=String(a.column_name||a.COLUMN_NAME||a.name||""),d=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),c=$e(s,d),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,u=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,m=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,y=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,T=a.numeric_scale!=null?Number(a.numeric_scale):null,N=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||d||"").toLowerCase());return {name:l,dataType:c,isNullable:u,defaultValue:m,length:y,precision:g,scale:T,withTimezone:N}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Kt(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(et(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let c=d.Key_name,p=d.Non_unique===0,u=l.get(c)||{name:c,columns:[],isUnique:p};u.columns.push(d.Column_name),l.set(c,u);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let c=d.index_name,p=!!d.is_unique,u=l.get(c)||{name:c,columns:[],isUnique:p};u.columns.push(d.column_name),l.set(c,u);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,c=!!l.unique,p=await this.rawQuery(`PRAGMA index_info(${d})`),m=this.extractRowsFromRawResult(p).map(y=>y.name);a.push({name:d,columns:m,isUnique:c});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Qt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(et(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let c=Number(d.id),p=l.get(c)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};p.columns.push(String(d.from)),p.referencedColumns.push(String(d.to)),l.set(c,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),c=d||`${l.referenced_table}_${l.column_name}`,p=a.get(c)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(c,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Lt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(et(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async getCheckConstraintInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new kt(e)]).sql,n=[];try{let s=await this.rawQuery(o);n=this.extractRowsFromRawResult(s);}catch(s){if(et(this.getDbType(),s))return [];throw s}return n.map(s=>({name:String(s.name),expression:String(s.expression)}))}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
192
+ ORDER BY pk`,bindings:[]}}},ip=new La;var Wa=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},ap=new Wa;var Fa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",d=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(d))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),d=0;for(let c of l)c==="("&&d++,c===")"&&d--;if(d>0)return e}return `as "${r}"`})}},lp=new Fa;var ja=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},dp=new ja;var Ua=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new h(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},up=new Ua;var Va=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},cp=new Va;var Ja=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof D?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},mp=new Ja;var Ha=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("sqlite",t):t}},pp=new Ha;var za=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},fp=new za;var Ya=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},yp=new Ya;var Ga=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},hp=new Ga;var Za=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},gp=new Za;var bp={mssql:{alter_table:{add_column:Al,add_constraint:xl,add_primary_key:Dl,alter_column_type:Il,alter_table:Pl,drop_column:$l,drop_constraint:El,drop_default:Bl,drop_not_null:vl,drop_primary_key:kl,rename_column:Ql,rename_table:Kl,set_default:Ll,set_not_null:Wl,set_table_options:Fl},column:{column_type:jl},constraint:{after:Ul,constraint:Vl},create_table:{create_table:Jl},delete:{delete:Hl},distinct:{distinct:zl,distinct_on:Yl},drop_table:{drop_table:Gl},extension:{create_extension:Zl},from:{from:Xl},group_by:{group_by:ed},having:{having:td},index_op:{create_index:rd,drop_index:od},insert:{insert:nd},join:{join:sd},limit:{limit:id},lock:{lock:ad},offset:{offset:ld},on_duplicate:{on_duplicate:dd},order_by:{order_by:ud},raw:{raw:cd},schema:{check_constraint_info:md,foreign_key_info:pd,index_info:fd,primary_key_info:yd,table_info:hd},select:{select:gd,select_json:bd},truncate:{truncate:Td},union:{union:wd},update:{update:Nd},where:{where:Sd,where_group:Cd,where_json:qd,where_subquery:Md},with:{with:Rd}},mysql:{alter_table:{add_column:_d,add_constraint:Od,add_primary_key:Ad,alter_column_type:xd,alter_table:Dd,drop_column:Id,drop_constraint:Pd,drop_default:$d,drop_not_null:Ed,drop_primary_key:Bd,rename_column:vd,rename_table:kd,set_default:Qd,set_not_null:Kd,set_table_options:Ld},column:{column_type:Wd},constraint:{after:Fd,constraint:jd},create_table:{create_table:Ud},delete:{delete:Vd},distinct:{distinct:Jd,distinct_on:Hd},drop_table:{drop_table:zd},extension:{create_extension:Yd},from:{from:Gd},group_by:{group_by:Zd},having:{having:Xd},index_op:{create_index:eu,drop_index:tu},insert:{insert:ru},join:{join:ou},limit:{limit:nu},lock:{lock:su},offset:{offset:iu},on_duplicate:{on_duplicate:au},order_by:{order_by:lu},raw:{raw:du},schema:{check_constraint_info:uu,foreign_key_info:cu,index_info:mu,primary_key_info:pu,table_info:fu},select:{select:yu,select_json:hu},truncate:{truncate:gu},union:{union:bu},update:{update:Tu},where:{where:wu,where_group:Nu,where_json:Su,where_subquery:Cu},with:{with:qu}},oracledb:{alter_table:{add_column:Mu,add_constraint:Ru,add_primary_key:_u,alter_column_type:Ou,alter_table:Au,drop_column:xu,drop_constraint:Du,drop_default:Iu,drop_not_null:Pu,drop_primary_key:$u,rename_column:Eu,rename_table:Bu,set_default:vu,set_not_null:ku,set_table_options:Qu},column:{column_type:Ku},constraint:{after:Lu,constraint:Wu},create_table:{create_table:Fu},delete:{delete:ju},distinct:{distinct:Uu,distinct_on:Vu},drop_table:{drop_table:Ju},extension:{create_extension:Hu},from:{from:zu},group_by:{group_by:Yu},having:{having:Gu},index_op:{create_index:Zu,drop_index:Xu},insert:{insert:ec},join:{join:tc},limit:{limit:rc},lock:{lock:oc},offset:{offset:nc},on_duplicate:{on_duplicate:sc},order_by:{order_by:ic},raw:{raw:ac},schema:{check_constraint_info:lc,foreign_key_info:dc,index_info:uc,primary_key_info:cc,table_info:mc},select:{select:pc,select_json:fc},truncate:{truncate:yc},union:{union:hc},update:{update:gc},where:{where:bc,where_group:Tc,where_json:wc,where_subquery:Nc},with:{with:Sc}},postgres:{alter_table:{add_column:Cc,add_constraint:qc,add_primary_key:Mc,alter_column_type:Rc,alter_table:_c,drop_column:Oc,drop_constraint:Ac,drop_default:xc,drop_not_null:Dc,drop_primary_key:Ic,rename_column:Pc,rename_table:$c,set_default:Ec,set_not_null:Bc,set_table_options:vc},column:{column_type:kc},constraint:{after:Qc,constraint:Kc},create_table:{create_table:Lc},delete:{delete:Wc},distinct:{distinct:Fc,distinct_on:jc},drop_table:{drop_table:Uc},extension:{create_extension:Vc},from:{from:Jc},group_by:{group_by:Hc},having:{having:zc},index_op:{create_index:Yc,drop_index:Gc},insert:{insert:Zc},join:{join:Xc},limit:{limit:em},lock:{lock:tm},offset:{offset:rm},on_duplicate:{on_duplicate:om},order_by:{order_by:nm},raw:{raw:sm},schema:{check_constraint_info:im,foreign_key_info:am,index_info:lm,primary_key_info:dm,table_info:um},select:{select:cm,select_json:mm},truncate:{truncate:pm},union:{union:fm},update:{update:ym},where:{where:hm,where_group:gm,where_json:bm,where_subquery:Tm},with:{with:wm}},sqlite:{alter_table:{add_column:Nm,add_constraint:Sm,alter_column_type:Cm,alter_table:qm,drop_column:Mm,drop_constraint:Rm,drop_default:_m,drop_not_null:Om,drop_primary_key:Am,rename_column:xm,rename_table:Dm,set_default:Im,set_not_null:Pm,set_table_options:$m},column:{column_type:Em},constraint:{after:Bm,constraint:vm},create_table:{create_table:km},delete:{delete:Qm},distinct:{distinct:Km,distinct_on:Lm},drop_table:{drop_table:Wm},extension:{create_extension:Fm},from:{from:jm},group_by:{group_by:Um},having:{having:Vm},index_op:{create_index:Jm,drop_index:Hm},insert:{insert:zm},join:{join:Ym},limit:{limit:Gm},lock:{lock:Zm},offset:{offset:Xm},on_duplicate:{on_duplicate:ep},order_by:{order_by:tp},raw:{raw:rp},schema:{check_constraint_info:op,foreign_key_info:np,index_info:sp,primary_key_info:ip,table_info:ap},select:{select:lp,select_json:dp},truncate:{truncate:up},union:{union:cp},update:{update:mp},where:{where:pp,where_group:fp,where_json:yp,where_subquery:hp},with:{with:gp}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(_=>!!_&&_.folder==="distinctOn"),n=!o&&t.find(_=>!!_&&_.folder==="distinct"),s=this.dbType==="mssql"?t.find(_=>!!_&&_.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(_=>_!==null&&_.folder!=="distinct"&&_.folder!=="distinctOn"),d=l.some(_=>_.folder==="offset"),c=l.some(_=>_.folder==="order_by"),p=l.find(_=>_.folder==="limit"),u=l.find(_=>_.folder==="offset"),m=this.dbType==="mssql"&&p&&!d&&!c,y=this.dbType==="mssql"&&!m&&(p||u),g=this.dbType==="oracledb"&&(p||u),T=[],N=[],M=null;m&&p&&N.push(p.limit);for(let _=0;_<l.length;_++){let I=l[_];if(m&&I.folder==="limit"||y&&(I.folder==="limit"||I.folder==="offset")||g&&(I.folder==="limit"||I.folder==="offset"))continue;I.currParamIndex=e+N.length;let P=bp[this.mapCommonDbType(this.dbType)][I.folder][I.file];if(!P)throw new Error(`Interpreter not found for ${this.dbType} ${I.keyword}`);P.model=this.model;let O=P.toSql(I);if(!O.sql||!O.sql.trim().length)continue;let K=l[_+1],$=!K||K.keyword!==I.keyword?"":K.chainsWith;if(I.folder==="lock"||I.folder==="on_duplicate"||I.folder==="schema"){T.push(`${O.sql}${$}`),N.push(...O.bindings),M=I.keyword;continue}if(M!==I.keyword||I.canKeywordBeSeenMultipleTimes){if(r)T.push(`${O.sql}${$}`);else {let X=I.keyword;if(I.folder==="with"&&this.dbType!=="mssql"){let te=_,Ce=false;for(;te<l.length&&l[te].keyword===I.keyword;){let Ae=l[te];if(Ae.folder==="with"&&Ae.clause==="recursive"){Ce=true;break}te++;}Ce&&(X=`${X} recursive`);}if(X==="select"){let te=m?`top (@${e}) `:"";if(o){let Ce=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${te}distinct on (${Ce}) ${O.sql}${$}`);}else n?T.push(`select ${te}distinct ${O.sql}${$}`):T.push(`select ${te}${O.sql}${$}`);}else X==="from"&&a?T.push(`${X} ${O.sql}${a}${$}`):T.push(`${X} ${O.sql}${$}`);}M=I.keyword;}else T.push(`${O.sql}${$}`);N.push(...O.bindings);}if(y){c||T.push("order by (select null)");let _=u?.offset??0;N.push(_);let P=`offset @${e+N.length-1} rows`;if(p){N.push(p.limit);let O=e+N.length-1;P+=` fetch next @${O} rows only`;}T.push(P);}if(g){c||T.push("order by null");let _=u?.offset??0;N.push(_);let P=`offset :${e+N.length-1} rows`;if(p){N.push(p.limit);let O=e+N.length-1;P+=` fetch next :${O} rows only`;}T.push(P);}return {sql:T.join(" "),bindings:N}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}getMssqlTableHints(t){let e=[];switch(t.lockType){case "UPDATE":e.push("UPDLOCK");break;case "SHARE":e.push("HOLDLOCK");break;case "NO_KEY_UPDATE":e.push("UPDLOCK");break;case "KEY_SHARE":e.push("HOLDLOCK");break}return t.skipLocked&&e.push("READPAST"),t.noWait&&e.push("NOWAIT"),e.length>0?` with (${e.join(", ")})`:""}};var Kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var Lt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Wt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Ft=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var jt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Ut=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var pe=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var nt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Vt=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var fe=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var Jt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var ye=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var yt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Ht=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var st=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var zt=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Yt=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Gt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Ue=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var j=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var Zt=class extends w{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var Xt=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var er=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var tr=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var rr=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var it=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var or=Symbol("columns"),at=Symbol("primaryKey"),he=Symbol("relations"),nr=Symbol("indexes"),sr=Symbol("uniques"),ir=Symbol("checks"),Pe=i=>`${Of__default.default.singular(i)}_id`,ar=(i,t)=>`idx_${i}_${t}`,ce=(i,t)=>`uq_${i}_${t}`,ee=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,$e=(i,t)=>`pk_${i}_${t}`,Tp=(i,t)=>{let e=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_|_$/g,"").toLowerCase();return `chk_${i}_${e}`.substring(0,63)};var B=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false;}};var ht=class extends w{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var Ve=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var lt=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var Ee=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var lr=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var dr=class extends Ee{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=$e(this.tableName,S(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??ee(this.tableName??"",S(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new j("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new j("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}notNullable(){return this.nodes.push(new j("not_null",{columns:[S(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new j("null",{columns:[S(this.columnNode.column)]})),this}default(t){let e;return t instanceof D?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new j("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new j("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??ce(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new j("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||ce(this.tableName??"",S(this.columnNode.column))})),this)}check(t,e){let r=S(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new j("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new j("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new lr(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new j("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Je=class extends Ee{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new dr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new D(e)}char(e,r=1){let o=new B(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new B(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new B(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new B(e,"uuid");return this.build(r)}ulid(e){let r=new B(e,"ulid");return this.build(r)}integer(e,r=255){let o=new B(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new B(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new B(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new B(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new B(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new B(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new B(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new B(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new B(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new B(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new B(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new B(e,"time",{precision:r});return this.build(o)}year(e){let r=new B(e,"year");return this.build(r)}datetime(e,r){let o=new B(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new B(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new B(e,"boolean");return this.build(r)}binary(e){let r=new B(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new B(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new B(e,"blob");return this.build(r)}tinyblob(e){let r=new B(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new B(e,"mediumblob");return this.build(r)}longblob(e){let r=new B(e,"longblob");return this.build(r)}json(e){let r=new B(e,"json");return this.build(r)}jsonb(e){let r=new B(e,"jsonb");return this.build(r)}enum(e,r){let o=new B(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new B(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new B(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new B(e,"geometry");return this.build(r)}point(e){let r=new B(e,"point");return this.build(r)}linestring(e){let r=new B(e,"linestring");return this.build(r)}polygon(e){let r=new B(e,"polygon");return this.build(r)}multiPoint(e){let r=new B(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var ur=class extends Ee{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new D(t)}addColumn(t){let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let u=p;return u.constraintType==="not_null"||u.constraintType==="null"||u.constraintType==="default"}),d=new Ut(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(p=>{let u=p;return u.constraintType==="unique"||u.constraintType==="foreign_key"||u.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new pe(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(m=>m.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=S(s.column),l=o.getNodes().find(m=>m.constraintType==="null"),c=o.getNodes().find(m=>m.constraintType==="not_null")||l,p=o.getNodes().find(m=>m.constraintType==="default"),u={};c&&(u.nullable=c.constraintType==="null"),p&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?u.dropDefault=true:u.default=p.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(u.collate=s.collate),this.nodes.push(new Vt(S(a),s,u)),c&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(c.constraintType==="not_null"?this.nodes.push(new Gt(S(a))):c.constraintType==="null"&&this.nodes.push(new Ht(S(a)))),p&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?this.nodes.push(new yt(S(a))):this.nodes.push(new Yt(S(a),p.defaultValue))),o.getNodes().forEach(m=>{let y=m;switch(y.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:y.constraintName});break;case "foreign_key":this.foreignKey(S(a),y.references?.table??"",S(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new Jt(t));}renameColumn(t,e){this.nodes.push(new zt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new yt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new nt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new j(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new j("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??ee(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new j("unique",{columns:[t],constraintName:e?.constraintName??ce(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=ee(this.table,t,e);this.nodes.push(new ye(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new f("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ce(this.table,t);this.nodes.push(new ye(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ye(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new f("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new st(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Ue(t)):r?this.nodes.push(new Ue(t)):o?this.nodes.push(new Ue(t)):n&&this.nodes.push(new Ue(t)),this)}};var ie=class{constructor(t){if(this.sqlType=t||x.DB_TYPE,!this.sqlType)throw new f("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new D(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!wp__default.default.existsSync(t))throw new f("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=Pt__default.default.basename(t),r=Pt__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new f("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=wp__default.default.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Je(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new Zt(t,n,o.getNamedConstraints(),r?.ifNotExists,a),d=s.parse([l]).sql,c=d.startsWith("create table")?d:`create table ${d}`;this.rawQuery(c),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new ur(t,r,this.sqlType);if(e(o),!r.length)return;let n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let d=new fe(t,s),c=n.parse([d]).sql;if(!c||!c.trim())return;let p=c.startsWith("alter table")?c:`alter table ${c}`;this.rawQuery(p),s=[];};for(let d of r)d.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(d);a();let l=r.filter(d=>d.file==="add_column").map(d=>d.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new Xt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new fe(t,[new ot(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new it(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let o=r.constraintName||ar(t,e.join("_")),n=new tr(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new rr(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new nt(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??ce(t,o.join("_")),s=new j("unique",{columns:o,constraintName:n}),a=new fe(t,[new pe(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=ee(t,e,r),n=new ye(o),s=new fe(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?ce(t,e.join("_")):ce(t,e),n=r?.constraintName??o,s=new ye(n),a=new fe(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new st,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new j(...e),o=new fe(t,[new pe(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new ye(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new j("check",{checkExpression:e,constraintName:o}),s=new fe(t,[new pe(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new ye(e),o=new fe(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new er(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>S(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new b(t,this.sqlType)}};var cr,Sp,gt=class{constructor(t,e){$t(this,cr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new ie(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=fl(this,cr,Sp).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
193
+ `)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}};cr=new WeakSet,Sp=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var mr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let c of d)c.type==="belongsTo"&&c.model().table===n.table&&a.push(`fk.${l.table}.${c.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(d=>d.table===n.table);if(l){let d=l.getColumns().find(c=>c.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let c=l.getRelations();for(let p of c)p.columnName===d.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let d of l)s(d);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),d=t.relationsToDrop?.find(c=>c.table===a&&c.relation.name===l);d&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:d,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(d)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let d of l)d.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):d.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(d=>d.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var pr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new mr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let d=r(l);return d?!(s.has(d)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new ie(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(d=>d.table===o.table)?.getColumns().find(d=>d.columnName===o.columns[0])?.primaryKeyConstraintName||$e(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,d=>{let c=a||$e(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:c});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(c=>c.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new ie(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new ie(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=S(t.relation.constraintName);if(e)return e;let r=t.table;t.relation.type==="belongsTo"?r=t.relation.model().table:t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(r=S(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,ee(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=S(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s=e[r.type](...o);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||$e(t,r.columnName)}),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new ie(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=S(t.relation.manyToManyOptions.throughModel),r=S(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=S(r);if(t.relation.type==="belongsTo"){let u=t.relation.model(),m=u.primaryKey,g=u.getColumns().find(T=>T.columnName===m);if(g)n=g.databaseName;else {let T=u?.databaseCaseConvention||"preserve";n=L(m,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let u=t.relation.model();if(typeof n=="string"&&n){let m=u.getColumns(),y=m.find(g=>g.columnName===n);if(y)n=y.databaseName;else {let g=u.primaryKey||"id",T=m.find(N=>N.columnName===g);if(T)n=T.databaseName;else {let N=u?.databaseCaseConvention||"preserve";n=L(n||g,N);}}}else {let m=u.primaryKey||"id",g=u.getColumns().find(T=>T.columnName===m);if(g)n=g.databaseName;else {let T=u?.databaseCaseConvention||"preserve";n=L(m,T);}}}let s=this.models.find(u=>u.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(u=>u.columnName===l);if(d)l=d.databaseName;else {let u=s?.databaseCaseConvention||"preserve";l=L(l,u);}if(t.relation.type==="belongsTo"){let u=a.find(m=>m.columnName===t.relation.foreignKey);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=L(t.relation.foreignKey,m);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let u=t.relation.manyToManyOptions.leftForeignKey,m=S(u),y=a.find(g=>g.columnName===m);if(y)l=y.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=L(m,g);}}let c=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,u=>{let m=o||ee(t.table,l,e);u.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:m,onDelete:c,onUpdate:p});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>sqlFormatter.format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};function Df(i){return i.replace(/\s+/g," ").trim()}function If(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Be(i,t){let e=Df(t.toLowerCase()),r=If(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var fr=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql.models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(u=>u?.type!==void 0&&u?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let y of n.indexes)o.indexes.map(g=>g.name).includes(y.name)||e.data.indexesToAdd.push({table:r.table,index:y.name});let u=r.getUniques?.()||[];for(let y of u)e.data.uniquesToAdd.push({table:r.table,name:y.name||"mandatory",columns:y.columns});let m=r.getChecks?.()||[];for(let y of m)e.data.checksToAdd.push({table:r.table,name:y.name,expression:y.expression});for(let y of n.relations){if(y.type!=="belongsTo")continue;let g=S(y.constraintName);o.foreignKeys.find(N=>N.name===g)||e.data.relationsToAdd.push({table:r.table,relation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}return}for(let u of n.columns)o.columns.some(y=>y.name===u.databaseName||y.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(y=>y.databaseName===u.name||y.columnName===u.name)||e.data.columnsToDrop.push({table:r.table,column:u.name});for(let u of n.indexes)o.indexes.map(m=>m.name).includes(u.name)||e.data.indexesToAdd.push({table:r.table,index:u.name});let s=r.getUniques?.()||[];for(let u of s)o.indexes.some(y=>y.name===u.name&&y.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});let a=o.foreignKeys.map(u=>u.name);for(let u of o.indexes)u.isUnique||a.includes(u.name)||n.indexes.map(y=>y.name).includes(u.name)||e.data.indexesToDrop.push({table:r.table,index:u.name});for(let u of o.indexes){if(!u.isUnique||u.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(y=>y.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}let l=r.getChecks?.()||[];for(let u of l)o.checkConstraints.some(y=>y.name===u.name)||e.data.checksToAdd.push({table:r.table,name:u.name,expression:u.expression});let d=new Set(l.map(u=>u.name));for(let u of o.checkConstraints)d.has(u.name)||e.data.checksToDrop.push({table:r.table,name:u.name});for(let u of n.columns){let m=o.columns.find(T=>T.name===u.databaseName||T.name===u.columnName);if(!m)continue;let y=!e.areColumnsEqual(m,u,o.indexes),g=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:u});(y||g)&&e.data.columnsToModify.push({table:r.table,dbColumns:m,modelColumn:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;if(u.type==="manyToMany"&&u.manyToManyOptions){let g=S(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:g,relation:{type:"belongsTo",model:()=>r,columnName:S(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?S(u.constraintName):ee(g,S(u.manyToManyOptions.leftForeignKey||Pe(r.table)),r.table),onDelete:u.onDelete,onUpdate:u.onUpdate},onDelete:u.onDelete,onUpdate:u.onUpdate});continue}let m=S(u.constraintName);if(m&&o.foreignKeys.some(g=>g.name===m))continue;o.foreignKeys.find(g=>e.relationMatchesDbRelation(r,u,g))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let c=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let m=S(u.foreignKey)||u.columnName,g=r.getColumns().find(T=>T.columnName===m)?.databaseName||m;return S(u.constraintName)||ee(r.table,g,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&c.has(u.name))continue;n.relations.find(y=>y.type!=="belongsTo"&&y.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,y,u))||e.data.relationsToDrop.push({table:r.table,relation:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;let m=o.foreignKeys.find(y=>e.relationMatchesDbRelation(r,u,y));m&&!e.areRelationsEqual(m,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let p=r.primaryKey;if(p&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[p]}),o.primaryKey&&!p&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),p&&o.primaryKey){let u=r.getColumns().find(m=>m.columnName===p);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:p});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getSqlStatementsByPhase(){let t=new pr(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=Be(n,t.dataType),a=typeof e.type=="string"?Be(n,e.type):void 0;a&&o&&(o=s===a),e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;o=o&&d===c;}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),c=d.primaryKey||"id",p=d.getColumns().find(y=>y.columnName===c),u=d.table,m=p?.databaseName||c;o=o&&t.referencedTable===u&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===m;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=S(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===d;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let g=n.model();g&&g.table&&(o=g);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?S(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=S(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),c=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,p=l.find(g=>g.columnName===c);p&&(c=p.databaseName);let u=o.primaryKey||"id",y=o.getColumns().find(g=>g.columnName===u)?.databaseName||u;return r.columns.length===1&&r.columns[0]===c&&r.referencedColumns.length===1&&r.referencedColumns[0]===y}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Be(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Be(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",d=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&d?false:"drop";if(s&&a){let c=String(t.dbColumns.defaultValue),p=String(t.modelColumn.constraints?.default),u=this.normalizeDefaultValue(e,r,c),m=this.normalizeDefaultValue(e,o||r,p);return u!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=S(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",c=s.getColumns().find($=>$.columnName===l),p=a.getColumns().find($=>$.columnName===d);if(!c||!p)continue;let u=S(o.manyToManyOptions.leftForeignKey)||l,m=S(o.manyToManyOptions.rightForeignKey)||d,y=await this.sql.getTableSchema(n);if(!y.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(c,u),this.clonePkAsColumn(p,m)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:u,rightFkName:m,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(c,u),T=this.clonePkAsColumn(p,m),N=y.columns.find($=>$.name===u),M=y.columns.find($=>$.name===m),A=N?this.areColumnsEqual(N,g,y.indexes):false,_=M?this.areColumnsEqual(M,T,y.indexes):false;for(let $ of y.foreignKeys){let X=$.referencedTable===s.table,te=$.referencedTable===a.table;if(!X&&!te)continue;let Ce=X?u:m,Ae=$.columns[0];Ae&&Ae!==Ce&&(this.data.relationsToDrop.push({table:n,relation:$}),Ae!==u&&Ae!==m&&this.data.columnsToDrop.push({table:n,column:Ae}));}let I={};A||(I[g.databaseName]=g),_||(I[T.databaseName]=I[T.databaseName]||T);for(let $ of Object.keys(I))this.data.columnsToAdd.push({table:n,column:I[$]});let P=this.buildBelongsToRelation(n,()=>s,u,l,void 0,o.onDelete,o.onUpdate),O=this.buildBelongsToRelation(n,o.model,m,d,void 0,o.onDelete,o.onUpdate),K=y.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===u),We=y.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===m);if(!K){let $=y.foreignKeys.find(X=>X.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(P);}if(!We){let $=y.foreignKeys.find(X=>X.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(O);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,c=o.getColumns().find(u=>u.columnName===l)?.databaseName||l,p=S(a.constraintName)||ee(o.table,c,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(g=>g.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let d=o.table,c=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let T=g.primaryKey||"id";c=g.getColumns().find(M=>M.columnName===T)?.databaseName||T;}let p=new Set([l,o.relation.columnName].filter(Boolean)),u=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let T=p.has(g.columns[0]),N=g.referencedTable===d,M=g.referencedColumns[0]===c;return T&&N&&M}),m=S(o.relation.constraintName)||ee(o.table,l,d),y=e.get(o.table)||new Set;if(u||m&&y.has(m))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=S(o.relation.manyToManyOptions.throughModel),T=S(o.relation.manyToManyOptions.leftForeignKey),N=S(o.relation.manyToManyOptions.rightForeignKey),M=o.table===g&&o.relation.columnName===T&&o.relation.model().table===s?.table,A=o.table===g&&o.relation.columnName===N&&o.relation.model().table!==s?.table,_=await this.sql.getTableSchema(g),I=_.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===T&&O.referencedTable===(s?.table||"")),P=_.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===N&&O.referencedTable===o.relation.model().table);if(M&&I||A&&P)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(d=>d.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(d=>{if(d.type!=="belongsTo")return false;let p=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,u=d.model(),m=u.primaryKey||"id",g=u.getColumns().find(T=>T.columnName===m)?.databaseName||m;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===u.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?S(n):ee(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var dt=class extends w{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var F=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var Y=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ge=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Re=class extends w{constructor(e,r=[],o=[],n=false){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o;}};var R=class extends w{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var ve=class extends w{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var ae=class extends R{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var _e=class extends w{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var Pf=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,$f=/^\d{4}-\d{2}-\d{2}$/,Xa=i=>typeof i!="string"?i:Pf.test(i)?new Date(i.replace(" ","T")+"Z"):$f.test(i)?new Date(i+"T00:00:00Z"):i,Ef=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),qp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Ef(r):t[e]=r;}return t};var yr=class extends stream.Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:d=>{s=true,a=d;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(d=>{r=true,this.emit("error",d);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},Mp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,c)=>{n.run(i,t,function(p){p&&c(p),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,c)=>{n.all(i,t,(p,u)=>{p&&c(p),(!u||!u.length)&&d([]),d(u);});});let s=r?.typeofModel;if(!s)return new Promise((d,c)=>{n.run(i,t,function(p){p?c(new Error(p.message)):d(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((p,u)=>{n.run(i,t,function(m){if(m)return u(m);let y=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p([y]);return}let g=y?.[a]||this.lastID;if(!g)return u(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[g],(N,M)=>{if(N)return u(N);p([M]);});});});if(!Array.isArray(r.models))throw new f("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((p,u)=>{n.run(i,t,function(m){if(m)return u(m);p(d);});});let c=[];return new Promise(async(p,u)=>{try{let m=d.map(async y=>{let g=new h(s),{columns:T,values:N}=await g.prepareColumns(Object.keys(y),Object.values(y),"insert"),M=Object.fromEntries(T.map((P,O)=>[P,N[O]])),A=new b(s,e.getDbType()),{sql:_,bindings:I}=A.parse([new Y(new F(s.table),[M])]);return new Promise((P,O)=>{n.run(_,I,function(K){if(K)return O(K);let We=y[a]||this.lastID;if(!We)return O(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[We],(X,te)=>{if(X)return O(X);P(te);});});})});c=await Promise.all(m),p(c);}catch(m){u(m);}})}return new Promise((d,c)=>{n.run(i,t,function(p){p?c(new Error(p.message)):d(this.changes);});})};var J=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||oe(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await bt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=0,c=i.replace(/\?/g,()=>`$${++d}`),p=await bt(()=>l.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let u=await bt(()=>Mp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(u)?u:[u]:u;case "mssql":let m=e.getPool(),y=e.sqlConnection?e.sqlConnection.request():m.request();t.forEach((I,P)=>{y.input(`p${P}`,I);});let g=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${g++}`),N=await bt(()=>y.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?N.rowsAffected[0]:o==="raw"?N:N.recordset;case "oracledb":let M=4002,A=null,_=!!e.sqlConnection;try{A=e.sqlConnection?e.sqlConnection:await e.getConnection();let I=t.map(Xa),P=0,O=i.replace(/\?/g,()=>`:${++P}`),K=await bt(()=>A.execute(O,I,{outFormat:M,autoCommit:!_}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?K.rowsAffected:o==="raw"?K:await Promise.all(K.rows?.map(async $=>{let X=await qp($),te={};for(let Ce in X)te[Ce.toLowerCase()]=X[Ce];return te})??[])}finally{A&&!_&&await A.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},gr=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),c=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,u=false,m=false,y=()=>{try{a.release();}catch{}};return c.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,u&&p===0&&!m&&(y(),l.end());}).catch(T=>{m=true,y(),l.destroy(T);});return}l.write(g);}),c.on("end",()=>{u=true,p===0&&!m&&(y(),l.end());}),c.on("error",g=>{m=true,y(),l.destroy(g);}),l.on("close",()=>{y();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new Q("pg-query-stream")}),d=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),c=0,p=i.replace(/\?/g,()=>`$${++c}`),u=new l.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=a.query(u),y=0,g=false,T=false,N=M=>{try{a.release(M);}catch{}};return m.on("data",M=>{if(o.onData){y++,Promise.resolve(o.onData(d,M)).then(()=>{y--,g&&y===0&&!T&&(N(),d.end());}).catch(A=>{T=true,N(A),d.destroy(A);});return}d.write(M);}),m.on("end",()=>{g=true,y===0&&!T&&(N(),d.end());}),m.on("error",M=>{T=true,N(M),d.destroy(M);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new yr(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((y,g)=>{l.input(`p${g}`,y);});let d=0,c=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),p=0,u=false,m=false;return l.on("row",y=>{if(!m){if(o.onData){p++,Promise.resolve(o.onData(a,y)).then(()=>{p--,u&&p===0&&!m&&a.end();}).catch(g=>{m=true,a.destroy(g);});return}a.write(y);}}),l.on("error",y=>{m=true,a.destroy(y);}),l.on("done",()=>{u=true,p===0&&!m&&a.end();}),l.query(c),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,c=0,p=i.replace(/\?/g,()=>`:${++c}`),u=t.map(Xa),m=a.queryStream(p,u,{outFormat:d}),y=0,g=false,T=false,N=async()=>{try{await a.close();}catch{}};return m.on("data",M=>{if(T)return;let A={};for(let _ in M)A[_.toLowerCase()]=M[_];if(o.onData){y++,Promise.resolve(o.onData(l,A)).then(()=>{y--,g&&y===0&&!T&&(N(),l.end());}).catch(_=>{T=true,N(),l.destroy(_);});return}l.write(A);}),m.on("end",()=>{g=true,y===0&&!T&&(N(),l.end());}),m.on("error",M=>{T=true,N(),l.destroy(M);}),l}default:throw new f("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function bt(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Rl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var W=(i,t="millis",e=3)=>async(...r)=>{let o=performance.now(),n=await i(...r),s=performance.now()-o;return [(t==="millis"?s:s/1e3).toFixed(e),n]};var Tt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=br(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new f("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Tr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function Rp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var ut=i=>typeof i=="number"?i:parseFloat(i);var me=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var He=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var wr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Nr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var ke=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var le=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var wt=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var Sr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Cr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Nt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var qr=class{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs;let r=this.model?.getColumns;this.modelColumns=typeof r=="function"?r.call(this.model):[],this.modelColumnsMap=new Map(this.modelColumns.map(o=>[o.columnName,o]));}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new wt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new wt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Nt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Nt(t,"asc",true)),this}limit(t){return typeof t!="number"&&q.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new Sr(t),this}offset(t){return typeof t!="number"&&q.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Cr(t),this}};var ze=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new R(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new R(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new R(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new R(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new R(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new R(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new R(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new R(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new R(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new R(t,"and",false,"in",e)),this):(this.whereNodes.push(new R("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new R(t,"or",false,"in",e)),this):(this.whereNodes.push(new R("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new R(t,"and",true,"in",e)),this):(this.whereNodes.push(new R("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new R(t,"or",true,"in",e)),this):(this.whereNodes.push(new R("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new R(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new R(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new R(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new R(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new ve(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new ve(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new R(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new R(t,"or",true,"=",e??[],true)),this}};var Mr=class extends qr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new le(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new le(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new le(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new le(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new le(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new le(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new ze(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new le(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,d)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new ze(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new le(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,d)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new ze(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new le(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,d)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let c=new ze(this.sqlDataSource);l(c),d=c.getConditions();}return this.joinNodes.push(new le(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Rr=class extends Mr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new F(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=L(s,this.model.databaseCaseConvention);this.selectNodes.push(new me(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=L(o,this.model.databaseCaseConvention);this.selectNodes.push(new me(n));}),this}selectRaw(e){return this.selectNodes.push(new me(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":L(r,this.model.databaseCaseConvention);return this.selectNodes.push(new me(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new F(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}from(e){return this.fromNode=new F(e),this}table(e){return this.fromNode=new F(e),this}distinct(){return this.distinctNode=new wr,this}distinctOn(...e){return this.distinctOnNode=new Nr(e),this}selectJson(e,r,o){return this.selectNodes.push(new ke(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new ke(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new ke(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new ke(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new ke(e,"",r,"raw",true)),this}};var _r=class extends Rr{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof v&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new R(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof v&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new R(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new R(e,"and",false,n,new D(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new R(e,"or",false,n,new D(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new R(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new R(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof v&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof v||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof v)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new R(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new R(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new R(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new R(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new R(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new R(e,"and",false,"in",r)),this):(this.whereNodes.push(new R("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new R(e,"or",false,"in",r)),this):(this.whereNodes.push(new R("false","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"in",r)}whereNotIn(e,r){return this.andWhereNotIn(e,r)}andWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new R(e,"and",true,"in",r)),this):(this.whereNodes.push(new R("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new R(e,"or",true,"in",r)),this):(this.whereNodes.push(new R("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new R(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new R(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new R(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new R(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new R(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new R(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new R(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new R(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new _e("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new _e("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new _e("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof v?e:new v(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new _e("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new R(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new R(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new He(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new He(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new He(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new He(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof v)return e;let r=new v(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new _e(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new _e(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new v(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new ve(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new v(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new ve(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Or=class extends _r{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ae(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ae(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ae(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ae(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ae(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ae(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ae(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ae(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ae(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ae(t,"or",false,"raw",e)),this}};var v=class i extends Or{constructor(e,r=be.instance){super(e,r);this.isNestedCondition=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new b(this.model,this.dbType),this.interpreterUtils=new h(this.model);}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource);return r(n),this.selectNodes.push(new me(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new me(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>J(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new f("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await gr(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:Rp(e,a),data:s},{key:r.discriminator,value:d}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new ht("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new ht("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Ve(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ve(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ve(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ve(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?ut(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?ut(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?ut(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?ut(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?ut(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&q.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:Tr(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new f("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new F(n,r),this}return this.fromNode=new F(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new lt("normal",e,n)),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new lt("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new f("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new lt("materialized",e,n)),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new Y(this.fromNode,[o],r,n),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((m,y)=>[m,a[y]]));this.insertNode=new Y(this.fromNode,[l],r,n);let{sql:d,bindings:c}=this.astParser.parse([this.insertNode]),p=await this.getSqlDataSource("write"),u=await J(d,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(u)&&u.length?u[0]:u})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new Y(this.fromNode,o,r,n),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async p=>{let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert");return Object.fromEntries(u.map((y,g)=>[y,m[g]]))}));this.insertNode=new Y(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),c=await J(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return c})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new Y(new F(this.model.table),[a],void 0,true),this.onDuplicateNode=new ge(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),c=Object.fromEntries(l.map((g,T)=>[g,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([c],s,n,o,[e]);let{sql:p,bindings:u}=this.astParser.parse([new Y(new F(this.model.table),[c],void 0,true),new ge(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),m=await this.getSqlDataSource("write"),y=await J(p,u,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(y)?y:[y]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new Y(new F(this.model.table),s,void 0,true),this.onDuplicateNode=new ge(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async u=>{let{columns:m,values:y}=await this.interpreterUtils.prepareColumns(Object.keys(u),Object.values(u),"insert"),g=Object.fromEntries(m.map((T,N)=>[T,y[N]]));a.push(g);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:d}=this.astParser.parse([new Y(new F(this.model.table),a,void 0,true),new ge(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),c=await this.getSqlDataSource("write"),p=await J(l,d,c,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(p)?p:[p]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),d=K=>this.interpreterUtils.formatStringColumn("mssql",K),c=[],p=e.map(K=>`select ${a.map($=>(c.push(K[$]),`@${c.length}`)).join(", ")}`),u=a.map(d).join(", "),m=p.join(" union all "),y=r.map(K=>`target.${d(K)} = source.${d(K)}`).join(" and "),g=o.filter(K=>!r.includes(K)).map(K=>`target.${d(K)} = source.${d(K)}`).join(", "),T=a.map(d).join(", "),N=a.map(K=>`source.${d(K)}`).join(", "),M=n.returning&&n.returning.length?n.returning.map(K=>`inserted.${d(K)}`).join(", "):a.map(K=>`inserted.${d(K)}`).join(", "),_=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",I=`merge into ${l} as target using (${m}) as source (${u}) on ${y} ${_} when not matched then insert (${T}) values (${N}) output ${M};`,P=await this.getSqlDataSource("write"),O=await J(I,c,P,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(O)?O:[O]}update(e){let r=Object.keys(e),o=Object.values(e);return this.updateNode=new Re(this.fromNode,r,o),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new Re(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return J(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}truncate(){return this.truncateNode=new it(this.fromNode),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await J(e,r,o,this.dbType,"rows");})}delete(){return this.deleteNode=new dt(this.fromNode),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return J(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=Ye()}=e||{};return this.updateNode=new Re(this.fromNode,[r],[o]),new V(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Re(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return J(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return tt(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new me("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=Ie(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=z(this.modelSelectedColumns),e.distinctNode=z(this.distinctNode),e.distinctOnNode=z(this.distinctOnNode),e.selectNodes=z(this.selectNodes),e.withQuery=z(this.withQuery),e.joinNodes=z(this.joinNodes),e.whereNodes=z(this.whereNodes),e.groupByNodes=z(this.groupByNodes),e.havingNodes=z(this.havingNodes),e.orderByNodes=z(this.orderByNodes),e.lockQueryNodes=z(this.lockQueryNodes),e.unionNodes=z(this.unionNodes),e.withNodes=z(this.withNodes),e.fromNode=z(this.fromNode),e.limitNode=z(this.limitNode),e.offsetNode=z(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.from(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new me("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await W(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await W(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await W(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await W(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await W(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await W(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await W(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await W(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await W(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await W(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await W(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await W(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await W(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var ct=class i extends v{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.sqlModelManagerUtils=new Tt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=new Map,this.modelColumnsDatabaseNames=new Map,this.model.getColumns().forEach(n=>{this.modelColumnsMap.set(n.databaseName,n),this.modelColumnsDatabaseNames.set(n.databaseName,n.columnName);});}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){return r.connection?new i(e,r.connection):r.trx?new i(e,r.trx.sql):new i(e,e.sqlInstance)}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new f(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a,this.model));if(!o.length)return [];let n=await we(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsRecursively(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await gr(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),c=await we([d],this.model,this.modelSelectedColumns);c&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([c]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([c]),a.write(c));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new f(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(...e){return this.model.insert(...e)}insertMany(...e){return this.model.insertMany(...e)}upsert(...e){return this.model.upsert(...e)}upsertMany(...e){return this.model.upsertMany(...e)}update(e,r={}){let o=super.update(e);return new V(()=>o.unWrap(),()=>o.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),o))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new V(()=>r.unWrap(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=super.delete();return new V(()=>r.unWrap(),()=>r.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),r))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,d]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Tr(e,r,d),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof v)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r){let o=this.sqlModelManagerUtils.getRelationFromModel(e),n=new i(o.model,this.sqlDataSource);return n.relation=o,r?.(n),this.relationQueryBuilders.push(n),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.whereExists(c),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.orWhereExists(c),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.whereNotExists(c),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let c=this.getRelatedModelsQueryForRelation(d,l,[]);return c.clearWhere(),c.clearSelect(),c.selectRaw("1"),a?.(c),this.applyHavingRelatedFilter(c,l,s,n),this.orWhereNotExists(c),this}clone(){let e=super.clone();return e.relationQueryBuilders=z(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(u=>{let m=u[e.foreignKey];m&&n.set(String(m),u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=null;return}let y=n.get(String(m));u[e.columnName]=y||null;});break;case "belongsTo":let s=new Map;o.forEach(u=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let m=u[e.model.primaryKey];m&&s.set(String(m),u);}),r.forEach(u=>{let m=u[e.foreignKey];if(!m){u[e.columnName]=null;return}let y=s.get(String(m));u[e.columnName]=y||null;});break;case "hasMany":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(u=>{let m=u[e.foreignKey];if(!m)return;let y=String(m);a.has(y)||a.set(y,[]),a.get(y).push(u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=[];return}let y=a.get(String(m))||[];u[e.columnName]=y;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,c=l.leftForeignKey,p=this.modelColumnsMap.get(c)||this.modelColumnsDatabaseNames.get(c)||L(c,this.model.modelCaseConvention);o.forEach(u=>{let m=u[p];if(m==null)return;let y=String(m);d.has(y)||d.set(y,[]),delete u[p],d.get(y).push(u);}),r.forEach(u=>{let m=u[this.model.primaryKey];if(!m){u[e.columnName]=[];return}let y=d.get(String(m))||[];u[e.columnName]=y;});break;default:throw new f(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=qe__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,c=e.orderByNodes.map(O=>O.isRawValue?O.column:`${this.interpreterUtils.formatStringColumn(this.dbType,O.column)} ${O.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(d,O=>O.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${c}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let u=e.modelSelectedColumns.map(O=>ro(O,d,e.model.table));return p.select(...u).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let m=r;if(!o.length)return e;let y=e.limitNode?.limit,g=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(O=>O.includes(".")?O:`${r.model.table}.${O}`):[`${r.model.table}.*`];if(!y&&!g)return e.select(...T).select([`${m.throughModel}.${m.leftForeignKey}`,m.leftForeignKey]).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n);let N=qe__default.default.randomBytes(6).toString("hex"),M=`${r.model.table}_cte_${N}`,A=e.orderByNodes.map(O=>{if(O.isRawValue)return O.column;let K=O.column.includes(".")?O.column:`${r.model.table}.${O.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${O.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let _=`${qe__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,I=e.with(M,O=>O.select(...T).select([`${m.throughModel}.${m.leftForeignKey}`,_]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${m.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,m.leftForeignKey)} ORDER BY ${A}) as rn_${N}`).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n));y&&I.whereRaw(`rn_${N} <= ${y+(g||0)}`),g&&I.whereRaw(`rn_${N} > ${g}`);let P=T.map(O=>ro(O,M,e.model.table));return I.select(...P).select([`${M}.${_}`,m.leftForeignKey]).from(M);default:throw new f(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),c=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(m=>!m.isRawValue&&m.table===d.throughModel&&m.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let p=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new f(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={};return Object.entries(e).forEach(([n,s])=>{if(this.modelColumnsDatabaseNames.get(n)){o[n]=s;return}o[n]=s;}),o}async manyWithPerformance(e={},r="millis"){let[o,n]=await W(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await W(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await W(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await W(this.paginate.bind(this,e,r,{ignoreHooks:s}),n)();return {data:{paginationMetadata:l.paginationMetadata,data:l.data},time:Number(a)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await W(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await W(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await W(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await W(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await W(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await W(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await W(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};function _p(i){let t=i.name.replace(/^_/,""),e=L(t,"snake");return Of__default.default(e)}function Op(){return {}}var St=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Op(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new f(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new f(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(l=>[l,t[l]])),o=!e.returning||e.returning.length===0,n=new Y(new F(this.model.table),[r],e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:Ie(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return tt(l,d)};return new V(s,a,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),c={};l.forEach((N,M)=>{let A=d[M];c[N]=A,t[N]??(t[N]=A);});let p=!e.returning||e.returning.length===0,{sql:u,bindings:m}=this.astParser.parse([new Y(new F(this.model.table),[c],e.returning,p)]),y=await J(u,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(p)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let g=y[0];return g?(await this.model.afterFetch?.([g]),await we([g],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(l=>Object.fromEntries(Object.keys(l).map(d=>[d,l[d]]))),o=!e.returning||e.returning.length===0,n=new Y(new F(this.model.table),r,e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:Ie(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return tt(l,d)};return new V(s,a,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let g=this.model.primaryKey,T=Object.keys(t[0]||{});if(g&&!T.includes(g))return this.handleOracleIdentityInsert(t,e)}let l=[];for(let g of t){let{columns:T,values:N}=await this.interpreterUtils.prepareColumns(Object.keys(g),Object.values(g),"insert"),M={};T.forEach((A,_)=>{let I=N[_];M[A]=I,g[A]??(g[A]=I);}),l.push(M);}let d=!e.returning||e.returning.length===0,{sql:c,bindings:p}=this.astParser.parse([new Y(new F(this.model.table),l,e.returning,d)]),u=await J(c,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(u,t,"many",e.returning)||[];let m=u;return m.length?(await this.model.afterFetch?.(m),await we(m,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new Y(new F(this.model.table),n,void 0,true),a=new ge(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let c=this.astParser.parse([s,a]);return {sql:Ie(this.sqlDataSource,c.sql),bindings:c.bindings}},d=()=>{let{sql:c,bindings:p}=l();return tt(c,p)};return new V(l,d,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async y=>{let{columns:g,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(y),Object.values(y),"insert"),N=Object.fromEntries(g.map((M,A)=>[M,T[A]]));c.push(N);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let{sql:p,bindings:u}=this.astParser.parse([new Y(new F(this.model.table),c,void 0,true),new ge(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await J(p,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=P=>this.interpreterUtils.formatStringColumn("mssql",P),d=[],c=t.map(P=>`select ${s.map(K=>(d.push(P[K]),`@${d.length}`)).join(", ")}`),p=s.map(l).join(", "),u=c.join(" union all "),m=e.map(P=>`target.${l(P)} = source.${l(P)}`).join(" and "),y=r.filter(P=>!e.includes(P)).map(P=>`target.${l(P)} = source.${l(P)}`).join(", "),g=s.map(l).join(", "),T=s.map(P=>`source.${l(P)}`).join(", "),N=o.returning&&o.returning.length?o.returning.map(P=>`inserted.${l(P)}`).join(", "):s.map(P=>`inserted.${l(P)}`).join(", "),A=(o.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",_=`merge into ${a} as target using (${u}) as source (${p}) on ${m} ${A} when not matched then insert (${g}) values (${T}) output ${N};`;return await J(_,d,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}})}async updateRecord(t,e){let r=new Set(this.model.getColumns().map(m=>m.columnName)),o=Object.keys(t).filter(m=>r.has(m)),n=o.map(m=>t[m]),{columns:s,values:a}=await this.interpreterUtils.prepareColumns(o,n,"update"),{primaryKey:l}=this.model;if(!l)throw new f(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=s.indexOf(l);d!==-1&&(s.splice(d,1),a.splice(d,1));let{sql:c,bindings:p}=this.astParser.parse([new Re(new F(this.model.table),s,a),new R(l,"and",false,"=",t[l])]);await J(c,p,this.sqlDataSource,this.sqlType,"affectedRows");let u=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!u)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return u}async deleteRecord(t){if(!this.model.primaryKey)throw new f(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new R(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new dt(new F(this.model.table)),e]);await J(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ct(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await we([a],this.model):null}return await we(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(c=>c[this.model.primaryKey]),l=a.map(c=>`'${c}'`).join(","),d=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((m,y)=>{let g=a[y];l[m]=g,n[m]??(n[m]=g);});let{sql:d,bindings:c}=this.astParser.parse([new Y(new F(this.model.table),[l],e.returning)]);await J(d,c,this.sqlDataSource,this.sqlType,"rows");let p=this.query().select(...e.returning||["*"]);for(let[m,y]of Object.entries(l))y!=null&&m!==o&&p.where(m,"=",y);o&&p.orderBy(o,"desc");let u=await p.one({ignoreHooks:["beforeFetch"]});u?(o&&u[o]&&(n[o]=u[o]),r.push(u)):r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let d of n)this.handleWhereCondition(a,d,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,d]=a;o?t.orWhereBetween(e,l,d):t.whereBetween(e,l,d);break}case "$not between":{let[l,d]=a;o?t.orWhereNotBetween(e,l,d):t.whereNotBetween(e,l,d);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Ap=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??Ye()});var ne=class{constructor(t){this.options=t;}static async createDriver(t){throw new f("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var Ct=class Ct extends ne{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Ct(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new Q("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new Q("mongodb");return new Ct(this.mongoClient)}};Ct.mongoClient=null;var Ar=Ct;var qt=class qt extends ne{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new qt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new Q("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new Q("mssql");return new qt(this.mssqlClient)}};qt.mssqlClient=null;var xr=qt;var Mt=class Mt extends ne{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Mt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new Q("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new Q("mysql2");return new Mt(this.mysqlClient)}};Mt.mysqlClient=null;var Dr=Mt;var Rt=class Rt extends ne{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new Rt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new Q("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new Q("oracledb");return new Rt(this.oracledbClient)}};Rt.oracledbClient=null;var Ir=Rt;var _t=class _t extends ne{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new _t(this.pgClient);let e=await import('pg').catch(()=>{throw new Q("pg")});if(this.pgClient=e.default??e,!this.pgClient)throw new Q("pg");return new _t(this.pgClient)}};_t.pgClient=null;var Pr=_t;var Ot=class Ot extends ne{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Ot(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new Q("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new Q("sqlite3");return new Ot(this.sqlite3Client)}};Ot.sqlite3Client=null;var $r=Ot;var de=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Dr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Pr.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await $r.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await Ar.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await xr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await Ir.createDriver(),this.oracledbDriver;default:throw new f(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};de.mysqlDriver=null,de.pgDriver=null,de.sqliteDriver=null,de.mssqlDriver=null,de.oracledbDriver=null,de.mongodbDriver=null;var kf=async i=>(await de.getDriver(i)).client,At=async(i,t)=>{let e=await kf(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let d=e,c=t,p=c?.database;return new d.Database(p,c?.driverOptions?.mode??void 0,P=>{if(P)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let m=e,y=t,{options:g,...T}=y.driverOptions??{},N=new m.ConnectionPool({server:y.host??"localhost",port:y.port,database:y.database,user:y.username,password:y.password,...T,options:{trustServerCertificate:x.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});return await N.connect(),N;case "oracledb":let M=e,A=t,_=`${A.host}/${A.database}`;return await M.createPool({user:A.username,password:A.password,connectString:_,...A.driverOptions});default:throw new f("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var xt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=qe__default.default.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),oe("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;oe("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");q.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw q.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");q.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw q.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new f("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){q.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new f("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new f("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw q.error(e),new Q("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new f("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var Te,Oe=class Oe extends et{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new Bt;this.migrationConfig={path:x.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:ao(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Oe(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!Fe(this,Te))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Fe(this,Te)}static async connectToSecondarySource(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.disconnect();}catch(s){throw o.isConnected&&await o.disconnect(),s}}static async disconnect(){if(!Fe(this,Te)){q.warn("Connection already closed");return}await Fe(this,Te).disconnect(),Yr(this,Te,null);}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!Fe(this,Te)?.globalTransaction}async connect(){if(Fe(Oe,Te))throw new f("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await At(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await At(e.sqlType,e.inputDetails),e.ownsPool=true;})),Yr(Oe,Te,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new f("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new f("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let c=io(JSON.stringify(d)),p=c?`${e}:${c}`:e,u=await this.cacheAdapter.get(p);if(u!==void 0)return u;let m=await n(...d);return await this.cacheAdapter.set(p,m,l),m}async invalidCache(e,...r){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new f("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=io(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Oe(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await At(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new v(Ap(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new ct(e,this)}schema(){if(!this.isConnected)throw new f("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new gt(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new xt(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new f("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){q.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new xt(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new f("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new St(e,this.globalTransaction.sql):new St(e,this)}getPool(){if(!this.sqlPool)throw new f("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new f("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new f("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){oe("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{q.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){q.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),oe("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new f("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){q.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await fr.makeDiff(this)).getSqlStatements();if(!o.length){q.info("No new changes detected between database schema and models metadata");return}if(q.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);q.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),q.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new f("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=Ie(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>J(n,r,a,this.getDbType(),"raw")):J(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new D(e)}async getTableSchema(e){let[r,o,n,s,a]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e),this.getCheckConstraintInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s,checkConstraints:a}}getModelOpenApiSchema(){return _l(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await oo(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await ql(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new jt(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(rt(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=Be(s,l);return {name:a.name,dataType:d,isNullable:a.notnull===0,defaultValue:a.dflt_value??null,withTimezone:null}}):n.map(a=>{let l=String(a.column_name||a.COLUMN_NAME||a.name||""),d=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),c=Be(s,d),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,u=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,m=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,y=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,T=a.numeric_scale!=null?Number(a.numeric_scale):null,N=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||d||"").toLowerCase());return {name:l,dataType:c,isNullable:u,defaultValue:m,length:y,precision:g,scale:T,withTimezone:N}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Wt(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(rt(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let c=d.Key_name,p=d.Non_unique===0,u=l.get(c)||{name:c,columns:[],isUnique:p};u.columns.push(d.Column_name),l.set(c,u);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let c=d.index_name,p=!!d.is_unique,u=l.get(c)||{name:c,columns:[],isUnique:p};u.columns.push(d.column_name),l.set(c,u);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,c=!!l.unique,p=await this.rawQuery(`PRAGMA index_info(${d})`),m=this.extractRowsFromRawResult(p).map(y=>y.name);a.push({name:d,columns:m,isUnique:c});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Lt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(rt(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let c=Number(d.id),p=l.get(c)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};p.columns.push(String(d.from)),p.referencedColumns.push(String(d.to)),l.set(c,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),c=d||`${l.referenced_table}_${l.column_name}`,p=a.get(c)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(c,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Ft(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(rt(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async getCheckConstraintInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Kt(e)]).sql,n=[];try{let s=await this.rawQuery(o);n=this.extractRowsFromRawResult(s);}catch(s){if(rt(this.getDbType(),s))return [];throw s}return n.map(s=>({name:String(s.name),expression:String(s.expression)}))}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
194
194
  v_result NUMBER;
195
195
  BEGIN
196
196
  v_result := DBMS_LOCK.REQUEST(
@@ -213,7 +213,7 @@ ORDER BY ordinal_position`,bindings:[]}}},em=new ki;var Qi=class{toSql(t){let e=
213
213
  ELSE
214
214
  :result := 0;
215
215
  END IF;
216
- END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return q.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return q.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return q.error(`Failed to release lock: ${n.message||JSON.stringify(o)} (dbType: ${r}, lockKey: ${e}). Full error: ${JSON.stringify(o)}`),false}}hashStringToLockId(e){let r=0;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);r=(r<<5)-r+n,r=r&r;}return Math.abs(r)}async executeOnSlave(e){let r=this.getSlave();if(!r)return e(this);try{return await e(r)}catch(o){let n=o instanceof Error?o:new Error(String(o));if(this.onSlaveServerFailure)return await this.onSlaveServerFailure(n,{host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,type:r.sqlType}),e(this);throw n}}async connectWithoutSettingPrimary(){this.sqlPool=await _t(this.sqlType,this.inputDetails),this.ownsPool=true;}};ge=new WeakMap,Dt(Re,ge,null);var he=Re;var wp=["postgres","cockroachdb"];var At=class At extends Oe{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:gp(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Rp(this)}constructor(t){super(),t&&this.constructor.combineProps(this,t);}static from(t){let e=new this;return this.combineProps(e,t),e}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static async first(t){return this.dispatchModelManager(t).query().one({ignoreHooks:t?.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async find(t,e){return await this.dispatchModelManager(e).find(t)}static async findOneOrFail(t,e){return await this.dispatchModelManager(e).findOneOrFail(t)}static async findOne(t,e){return await this.dispatchModelManager(e).findOne(t)}static async findBy(t,e,r={}){return await this.dispatchModelManager(r).find({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneBy(t,e,r={}){return await this.dispatchModelManager(r).findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneByPrimaryKey(t,e={}){return await this.dispatchModelManager(e).findOneByPrimaryKey(t)}static async refresh(t,e={}){let r=this,o=r.dispatchModelManager(e),n=r.primaryKey,s=t[n],a=await o.findOneByPrimaryKey(s);a&&Object.assign(t,a);}static insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static insertMany(t,e={}){let o=this.dispatchModelManager(e);if(!t.length){let n=!e.returning||e.returning.length===0;return new U(()=>({sql:"",bindings:[]}),()=>"",async()=>n?void 0:[])}return o.insertMany(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async sync(t,e,r,o,n={}){if(Array.isArray(r)||(r=[r]),!r.length)return;let s=this,l=hr(s).find(y=>y.columnName===t);if(!l)throw new f(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new f(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=L(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),c=L(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),p=r.map((y,g)=>({[d]:e[s.primaryKey],[c]:y[l.model.primaryKey],...o?o(y,g):{}}));class u extends At{static get table(){return l.throughModel}}u.databaseCaseConvention="preserve",u.modelCaseConvention="preserve",await u.dispatchModelManager(n).insertMany(p);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof f&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new f(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e,{returning:["*"]});return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),s=Object.keys(t).length>0,a=!r.returning||r.returning.length===0,l=s?await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t}):null;if(l){if(e[o.primaryKey]=l[o.primaryKey],r.updateOnConflict??true){if(a){await n.updateRecord(e);return}return await n.updateRecord(e,{returning:r.returning})}return a?void 0:l}return await n.insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}static async upsertMany(t,e,r={updateOnConflict:true}){if(!e.length)return [];let o=this,n=o.dispatchModelManager(r),s=!r.returning||r.returning.length===0;if(!e.every(u=>{let m=new Set(Object.keys(u));return t.every(y=>m.has(y))}))throw new f("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let a=Object.keys(e[0]),l=await n.upsertMany(t,a,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true});if(s)return;let d=o.sqlInstance.getDbType();if(wp.includes(d))return await be(l,o,r.returning);let c=n.query();r.returning?.length&&c.select(...r.returning);let p=new Map;return t.forEach(u=>{e.forEach(m=>{p.set(u,[...p.get(u)||[],m[u]]);});}),c.where(u=>{t.forEach(m=>{u.orWhereIn(m,p.get(m)||[]);});}),c.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(t)}static async save(t,e={}){let r=this,o=r.primaryKey;if(!o)throw new f(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=t[o],s=n?{[o]:n}:{},a=t,l=await r.upsert.call(this,s,a,{updateOnConflict:true,returning:["*"],...e});return r.combineProps(t,l),t}static async softDelete(t,e,r){let o=this,{column:n=o.softDeleteColumn,value:s=o.softDeleteValue}=e||{};return t[n]=s,await o.dispatchModelManager({trx:r?.trx,connection:r?.connection}).updateRecord(t),typeof s=="string"?(t[n]=new Date(s),t):(t[n]=s,t)}static async truncate(t={}){return this.dispatchModelManager(t).query().truncate()}static async getTableInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getTableInfo(t.table)}static async getIndexInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getIndexInfo(t.table)}static async getTableSchema(){let t=this;return t.establishConnection(),t.sqlInstance.getTableSchema(t.table)}static combineProps(t,e){for(let r in e)Object.assign(t,{[r]:e[r]});}static getColumns(){return vt(this)}static getRelations(){return Cp(this)}static getIndexes(){return _p(this)}static getUniques(){return Op(this)}static getChecks(){return Ap(this)}static column(t,...e){I(...e)(this.prototype,t);}static dateColumn(t,...e){I.date(...e)(this.prototype,t);}static datetimeColumn(t,...e){I.datetime(...e)(this.prototype,t);}static timestampColumn(t,...e){I.timestamp(...e)(this.prototype,t);}static timeColumn(t,...e){I.time(...e)(this.prototype,t);}static booleanColumn(t,...e){I.boolean(...e)(this.prototype,t);}static jsonColumn(t,...e){I.json(...e)(this.prototype,t);}static uuidColumn(t,...e){I.uuid(...e)(this.prototype,t);}static ulidColumn(t,...e){I.ulid(...e)(this.prototype,t);}static integerColumn(t,...e){I.integer(...e)(this.prototype,t);}static floatColumn(t,...e){I.float(...e)(this.prototype,t);}static incrementColumn(t,...e){I.increment(...e)(this.prototype,t);}static bigIncrementColumn(t,...e){I.bigIncrement(...e)(this.prototype,t);}static encryptionSymmetricColumn(t,...e){I.encryption.symmetric(...e)(this.prototype,t);}static encryptionAsymmetricColumn(t,...e){I.encryption.asymmetric(...e)(this.prototype,t);}static hasOne(t,...e){Sp(...e)(this.prototype,t);}static hasMany(t,...e){qp(...e)(this.prototype,t);}static belongsTo(t,...e){Np(...e)(this.prototype,t);}static manyToMany(t,...e){Mp(...e)(this.prototype,t);}static establishConnection(){let t=he.instance;if(!t)throw new f("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){let e;if(t?.connection)e=t.connection.getModelManager(this);else if(t?.trx)e=t.trx.sql.getModelManager(this);else {let r=this;r.establishConnection(),e=r.sqlInstance.getModelManager(r);}return t?.replicationMode&&e.setReplicationMode(t.replicationMode),e}};At.softDeleteColumn="deletedAt",At.softDeleteValue=He();var z=At;var Te=class{constructor(t,e){this.model=z;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Pr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var $r=class extends Te{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Er=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Br=class extends Te{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function Qk(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(rr,e.prototype)||[];o.push({columns:r,name:t??sr(e.table,r.join("_"))}),k.defineMetadata(rr,o,e.prototype);}}function Kk(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(or,e.prototype)||[];o.push({columns:r,name:t??de(e.table,r.join("_"))}),k.defineMetadata(or,o,e.prototype);}}function Lk(i,t){return e=>{let r=k.getMetadata(nr,e.prototype)||[];r.push({expression:i,name:t??dp(e.table,i)}),k.defineMetadata(nr,r,e.prototype);}}function Wk(i){return t=>{let e=t,r=e.query;e.query=function(...o){let n=r.bind(this).call(this,...o);return i(n),n};}}function I(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(k.getMetadata(st,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");k.defineMetadata(st,r,e),k.defineMetadata(st,r,e.constructor);}let n=i.databaseName??L(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??De(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=k.getMetadata(tr,e)||[];a.push(s),k.defineMetadata(tr,a,e);}}I.primary=Ef;I.date=Gf;I.datetime=Zf;I.timestamp=Xf;I.time=ey;I.boolean=Yf;I.json=ty;I.uuid=Kf;I.ulid=Lf;I.integer=vf;I.bigInteger=jf;I.float=Bf;I.decimal=Uf;I.increment=kf;I.bigIncrement=Qf;I.string=Wf;I.text=Ff;I.binary=Vf;I.enum=Jf;I.encryption={symmetric:Hf,asymmetric:zf};function Ef(i={}){return I({...i,primaryKey:true})}function Bf(i={}){return I({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function vf(i={}){return I({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function kf(i={}){return I({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function Qf(i={}){return I({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function Kf(i={}){return I({type:"uuid",...i,prepare:t=>t||Se__default.default.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Lf(i={}){return I({type:"ulid",...i,prepare:t=>t||ul(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Wf(i={}){return I({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Ff(i={}){return I({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function jf(i={}){return I({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function Uf(i={}){return I({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Vf(i={}){return I({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Jf(i,t={}){return I({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Hf(i){return I({...i,prepare:t=>t&&il(i.key,t),serialize:t=>t&&al(i.key,t)})}function zf(i){return I({...i,prepare:t=>t&&ll(i.publicKey,t),serialize:t=>t&&dl(i.privateKey,t)})}function Yf(i={}){return I({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t,openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function Gf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"DATE_ONLY",t):typeof d=="string"?d:oe(d,"DATE_ONLY",t):r?oe(new Date,"DATE_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:ct(d,void 0,t)};return I({type:"date",...s,autoUpdate:e,prepare:d=>{let c=a(d);return o?o(c):c},serialize:d=>{let c=l(d);return n?n(c):c},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function Zf(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",d=e??t!==void 0,c=u=>u?r?oe(new Date,"ISO",l):typeof u=="string"?u:oe(u,"ISO",l):o?oe(new Date,"ISO",l):null,p=u=>{if(u!==void 0)return u===null?null:ct(u,void 0,l)};return I({type:"datetime",...a,withTimezone:d,autoUpdate:r,prepare:u=>{let m=c(u);return n?n(m):m},serialize:u=>{let m=p(u);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...a.openApi||{}}})}function Xf(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",d=e??t!==void 0,c=u=>u?r?oe(new Date,"TIMESTAMP",l):typeof u=="string"?u:oe(u,"TIMESTAMP",l):o?oe(new Date,"TIMESTAMP",l):null,p=u=>{if(u!==void 0)return u===null?null:ct(u,void 0,l)};return I({type:"timestamp",...a,withTimezone:d,autoUpdate:r,prepare:u=>{let m=c(u);return n?n(m):m},serialize:u=>{let m=p(u);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...a.openApi||{}}})}function ey(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"TIME_ONLY",t):typeof d=="string"?d:oe(d,"TIME_ONLY",t):r?oe(new Date,"TIME_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:ct(d,void 0,t)};return I({type:"time",...s,autoUpdate:e,prepare:d=>{let c=a(d);return o?o(c):c},serialize:d=>{let c=l(d);return n?n(c):c},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function ty(i={}){return I({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function vt(i){try{return k.getMetadata(tr,i.prototype)||[]}catch{return []}}function Np(i,t,e){return((r,o)=>{let n=()=>Ie(i().table),s=()=>{let d=r.constructor.table,c=t||n();return Z(d,c,i().table)},a={type:"belongsTo",columnName:o,model:i,foreignKey:t?String(t):n,constraintName:e?.constraintName??s,onUpdate:e?.onUpdate,onDelete:e?.onDelete},l=k.getMetadata(fe,r)||[];l.push(a),k.defineMetadata(fe,l,r);})}function Sp(i,t){return((e,r)=>{let o=()=>Ie(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(fe,e)||[];s.push(n),k.defineMetadata(fe,s,e);})}function qp(i,t){return((e,r)=>{let o=()=>Ie(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(fe,e)||[];s.push(n),k.defineMetadata(fe,s,e);})}function Mp(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,c=o.constructor.table,p=()=>Ie(c),u=()=>Ie(i().table),m=()=>Z(S(d),s?String(s):p()),y={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??m,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:c,throughModel:d,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):u,wasModelProvided:l}},g=k.getMetadata(fe,o)||[];g.push(y),k.defineMetadata(fe,g,o);})}function Cp(i){return k.getMetadata(fe,i.prototype)||[]}function hr(i){return (k.getMetadata(fe,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=S(s),l=o();switch(r){case "belongsTo":return new Pr(l,n,a);case "hasOne":return new Er(l,n,a);case "hasMany":return new $r(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new f("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new Br(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:S(e.manyToManyOptions.throughModel),leftForeignKey:S(e.manyToManyOptions.leftForeignKey),rightForeignKey:S(e.manyToManyOptions.rightForeignKey)});default:throw new f("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Rp(i){return k.getMetadata(st,i)||k.getMetadata(st,i.prototype)}function _p(i){return k.getMetadata(rr,i.prototype)||[]}function Op(i){return k.getMetadata(or,i.prototype)||[]}function Ap(i){return k.getMetadata(nr,i.prototype)||[]}var Ha=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){if(t<=0)return [];let e=this.typeofModel;if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},ry=(i,t)=>new Ha(i,t);function oy(i,t){let e=a=>typeof a=="function",r=e(i)?i:z,o=e(i)?t:i,s=class s extends r{};s.column("id",{openApi:{type:"number",required:true},...o,primaryKey:true});let n=s;return n}function ny(i,t){let e=a=>typeof a=="function",r=e(i)?i:z,o=e(i)?t:i,s=class s extends r{};s.column("id",{openApi:{type:"number",required:true},...o,primaryKey:true});let n=s;return n}function xp(i,t){let e=a=>typeof a=="function",r=e(i)?i:z,o=e(i)?t:i,s=class s extends r{};s.ulidColumn("id",{type:"ulid",openApi:{type:"string",format:"ulid",required:true},...o,primaryKey:true});let n=s;return n}var sy=xp;function Ip(i,t){let e=a=>typeof a=="function",r=e(i)?i:z,o=e(i)?t:i,s=class s extends r{};s.uuidColumn("id",{type:"uuid",openApi:{type:"string",format:"uuid",required:true},...o,primaryKey:true});let n=s;return n}var iy=Ip;function ay(i,t){let e=s=>typeof s=="function",r=e(i)?i:z,o=e(i)?t:i;class n extends r{}return z.datetimeColumn("createdAt",{type:"datetime",autoCreate:true,openApi:{type:"string",format:"date-time",required:true},...o?.createdAt}),z.datetimeColumn("updatedAt",{autoUpdate:true,openApi:{type:"string",format:"date-time",required:true},...o?.updatedAt}),z.datetimeColumn("deletedAt",{nullable:true,openApi:{type:"string",format:"date-time",required:false},...o?.deletedAt}),n}var Dp=i=>{let t=()=>{for(let[r,o]of Object.entries(i))z.column(r,o);};function e(r){var s;let o=r??z;return s=class extends o{},t(),s}return e},ly=Dp;var Pp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw q.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new Q("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw q.error("RedisCacheAdapter::set failed to serialize data"),e}return String(t)}}deserializeData(t){try{return JSON.parse(t)}catch{return t}}async disconnect(){this.redisInstance&&await this.redisInstance.quit();}};var{plural:uy}=Sf__default.default;function $p(i){let t=i.name,e=L(t,"snake");return uy(e)}function Ep(){return {$annotations:{}}}var ut=class extends Oe{static get collection(){return this._collection||$p(this)}static query(t={}){return this.dispatchModelManager(t).query()}static rawCollection(){return this.mongoInstance.getCurrentConnection().db().collection(this.collection)}static async find(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).find(t)}static async findOne(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOne(t)}static async findOneOrFail(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOneOrFail(t)}static async insert(t,e={}){return await this.dispatchModelManager(e).insert(t)}static async insertMany(t,e={}){return await this.dispatchModelManager(e).insertMany(t)}static async updateRecord(t,e={}){return await this.dispatchModelManager(e).updateRecord(t)}static async deleteRecord(t,e={}){await this.dispatchModelManager(e).deleteRecord(t);}static establishConnection(){let t=xt.getInstance();if(!t)throw new f("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){Ur()(this.prototype,t);}static async afterFetch(t){return t}};ol([Ur()],ut.prototype,"id");async function ve(i,t,e){if(!t)return null;let r=Ep(),o=sl(i);return (!e||!e.length)&&(e=o),e.includes("id")||e.push("id"),r.$annotations||(r.$annotations={}),await Promise.all(Object.keys(t).map(async n=>{if(n==="_id"){r.id=t._id?.toString();return}if(!o.includes(n)){let a=L(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=L(n,i.modelCaseConvention);r[s]=t[n];})),Object.keys(r.$annotations).length||delete r.$annotations,await Promise.all(e.map(async n=>{if(n!=="id"&&!t.hasOwnProperty(n)){let s=L(n,i.modelCaseConvention);r[s]=null;}})),r}async function vr(i,t,e){return (await Promise.all(t.map(async o=>await ve(i,o,e)))).filter(o=>o!==null)}var kr=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,session:this.session}),o=await ve(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new f("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await vr(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await ve(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await vr(this.model,o,this.selectFields)}async update(t,e={}){if(e.ignoreHooks||this.model.beforeUpdate(this),(await this.collection.updateMany({_id:this.idObject,...this.whereObject},{$set:t,session:this.session})).modifiedCount===0)return [];let o=await this.collection.find({_id:Object.keys(this.idObject).length?this.idObject:void 0,...this.whereObject},{projection:this.selectFields}).toArray();return await vr(this.model,o,this.selectFields)}async delete(t={}){t.ignoreHooks||this.model.beforeDelete(this),await this.collection.deleteMany(this.whereObject,{session:this.session});}async count(t={}){return t.ignoreHooks||this.model.beforeFetch(this),this.collection.countDocuments(this.whereObject,{session:this.session})}select(t){return this.selectFields=t,this.selectObject=t.reduce((e,r)=>(e[r]=1,e),{}),this}where(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=ee("mongodb");if(t==="id")return this.idObject={$eq:new s.ObjectId(n)},this;let a={[t]:{[o]:n}};return this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this}andWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=ee("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this)}orWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=ee("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(a)):this.whereObject={$or:[a]},this)}whereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotIn(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotBetween(t,e){let r=ee("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereRaw(t){return this.whereObject={...this.whereObject,...t},this}andRawWhere(t){return this.whereObject={...this.whereObject,...t},this}orRawWhere(t){return this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(t),this}sortById(t){return this.sortObject={_id:t},this}sort(t){return typeof t=="number"?(this.sortObject={_id:t},this):typeof t=="string"?(this.sortObject={[t]:1},this):Array.isArray(t)?(this.sortObject=t.reduce((e,r)=>{if(typeof r=="string")return e[r]=1,e;let o=Object.keys(r)[0],n=Object.values(r)[0];return e[o]=+n,e},{}),this):(this.sortObject=t,this)}limit(t){return this.limitNumber=t,this}offset(t){return this.offsetNumber=t,this}};var Qr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=ut,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new f("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new kr(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await ve(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await ve(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await ve(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var ke=class ke extends Ze{constructor(e){super({type:"mongo",url:e?.url,logs:e?.logs});this.mongoClient=null;this.isConnected=false,this.mongoOptions=e?.options,this.url||(this.url=A.MONGO_URL);}async connect(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ae.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,ke.instance=this;}async connectWithoutSettingPrimary(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ae.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true;}getCurrentConnection(){if(!this.mongoClient)throw new f("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}static async connectToSecondarySource(e){let r=new ke(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!ke.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return ke.instance}startSession(){if(!this.mongoClient)throw new f("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}static async disconnect(){if(!this.instance)throw new f("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(e,r){let o=new ke(e);await o.connectWithoutSettingPrimary();try{await r(o);}finally{await o.disconnect();}}static query(e){return this.getInstance().query(e)}query(e){if(!this.isConnected)throw new f("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:e},this).query()}getModelManager(e,r,o){return new Qr(e,r,o,this.logs)}};ke.instance=null;var xt=ke;var Y=class Y{constructor(t){this.OK="OK";this.isConnected=false,this.ioRedisConnection=t;}static get ioredis(){return this.redisDataSourceInstance.ioRedisConnection}get ioredis(){return this.ioRedisConnection}static async connect(t){if(this.isConnected)return;let e=t?.port||+A.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new Q("ioredis")});this.redisDataSourceInstance=new Y(new r.default({host:t?.host||A.REDIS_HOST,username:t?.username||A.REDIS_USERNAME,port:e,password:t?.password||A.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new f("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new Q("ioredis")}),r=new e.default({host:t?.host||A.REDIS_HOST,username:t?.username||A.REDIS_USERNAME,port:t?.port||+A.REDIS_PORT||6379,password:t?.password||A.REDIS_PASSWORD,...t}),o=new Y(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new f("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Y.getValue(e)}catch{throw new f("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Y.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED");q.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Y.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Y.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Y.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Y.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=Y.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Y.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Y.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>Y.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Y.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>Y.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};Y.OK="OK";var za=Y;var Ya=class{constructor(t){this.dbType=t,this.migrationName=It__default.default.basename(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))),this.schema=new ne(this.dbType);}};async function yy(i){try{return import(url.pathToFileURL(i).href)}catch{let e=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))(i);return {default:e.default||e,...e}}}async function hy(i){let{build:t}=await import('esbuild').catch(()=>{throw new Error("esbuild is required to import TypeScript files. Install it with: npm install esbuild -D")}),e=Math.random().toString(36).slice(2,8),r=i.replace(/\.ts$/,`.bundled_${e}.mjs`);try{return await t({entryPoints:[i],bundle:!0,platform:"node",format:"esm",sourcemap:"inline",outfile:r,packages:"external",logLevel:"silent"}),await import(url.pathToFileURL(r).href)}finally{await up__default.default.promises.unlink(r).catch(()=>{});}}async function kp(i,t){let e=It__default.default.isAbsolute(i)?i:It__default.default.resolve(process.cwd(),i);return e.endsWith(".ts")?hy(e):yy(e)}var Ga=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(n=>n.table_name);case "mssql":return r.recordset.map(n=>n.TABLE_NAME);case "oracledb":return (r.rows||[]).map(n=>Array.isArray(n)?n[0]:n?.TABLE_NAME).filter(n=>typeof n=="string"&&n.length>0);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
216
+ END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return q.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return q.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return q.error(`Failed to release lock: ${n.message||JSON.stringify(o)} (dbType: ${r}, lockKey: ${e}). Full error: ${JSON.stringify(o)}`),false}}hashStringToLockId(e){let r=0;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);r=(r<<5)-r+n,r=r&r;}return Math.abs(r)}async executeOnSlave(e){let r=this.getSlave();if(!r)return e(this);try{return await e(r)}catch(o){let n=o instanceof Error?o:new Error(String(o));if(this.onSlaveServerFailure)return await this.onSlaveServerFailure(n,{host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,type:r.sqlType}),e(this);throw n}}async connectWithoutSettingPrimary(){this.sqlPool=await At(this.sqlType,this.inputDetails),this.ownsPool=true;}};Te=new WeakMap,$t(Oe,Te,null);var be=Oe;var xp=["postgres","cockroachdb"];var Dt=class Dt extends xe{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:_p(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Ip(this)}constructor(t){super(),t&&this.constructor.combineProps(this,t);}static from(t){let e=new this;return this.combineProps(e,t),e}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static async first(t){return this.dispatchModelManager(t).query().one({ignoreHooks:t?.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async find(t,e){return await this.dispatchModelManager(e).find(t)}static async findOneOrFail(t,e){return await this.dispatchModelManager(e).findOneOrFail(t)}static async findOne(t,e){return await this.dispatchModelManager(e).findOne(t)}static async findBy(t,e,r={}){return await this.dispatchModelManager(r).find({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneBy(t,e,r={}){return await this.dispatchModelManager(r).findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneByPrimaryKey(t,e={}){return await this.dispatchModelManager(e).findOneByPrimaryKey(t)}static async refresh(t,e={}){let r=this,o=r.dispatchModelManager(e),n=r.primaryKey,s=t[n],a=await o.findOneByPrimaryKey(s);a&&Object.assign(t,a);}static insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static insertMany(t,e={}){let o=this.dispatchModelManager(e);if(!t.length){let n=!e.returning||e.returning.length===0;return new V(()=>({sql:"",bindings:[]}),()=>"",async()=>n?void 0:[])}return o.insertMany(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async sync(t,e,r,o,n={}){if(Array.isArray(r)||(r=[r]),!r.length)return;let s=this,l=br(s).find(y=>y.columnName===t);if(!l)throw new f(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new f(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=L(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),c=L(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),p=r.map((y,g)=>({[d]:e[s.primaryKey],[c]:y[l.model.primaryKey],...o?o(y,g):{}}));class u extends Dt{static get table(){return l.throughModel}}u.databaseCaseConvention="preserve",u.modelCaseConvention="preserve",await u.dispatchModelManager(n).insertMany(p);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof f&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new f(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e,{returning:["*"]});return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),s=Object.keys(t).length>0,a=!r.returning||r.returning.length===0,l=s?await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t}):null;if(l){if(e[o.primaryKey]=l[o.primaryKey],r.updateOnConflict??true){if(a){await n.updateRecord(e);return}return await n.updateRecord(e,{returning:r.returning})}return a?void 0:l}return await n.insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}static async upsertMany(t,e,r={updateOnConflict:true}){if(!e.length)return [];let o=this,n=o.dispatchModelManager(r),s=!r.returning||r.returning.length===0;if(!e.every(u=>{let m=new Set(Object.keys(u));return t.every(y=>m.has(y))}))throw new f("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let a=Object.keys(e[0]),l=await n.upsertMany(t,a,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true});if(s)return;let d=o.sqlInstance.getDbType();if(xp.includes(d))return await we(l,o,r.returning);let c=n.query();r.returning?.length&&c.select(...r.returning);let p=new Map;return t.forEach(u=>{e.forEach(m=>{p.set(u,[...p.get(u)||[],m[u]]);});}),c.where(u=>{t.forEach(m=>{u.orWhereIn(m,p.get(m)||[]);});}),c.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(t)}static async save(t,e={}){let r=this,o=r.primaryKey;if(!o)throw new f(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=t[o],s=n?{[o]:n}:{},a=t,l=await r.upsert.call(this,s,a,{updateOnConflict:true,returning:["*"],...e});return r.combineProps(t,l),t}static async softDelete(t,e,r){let o=this,{column:n=o.softDeleteColumn,value:s=o.softDeleteValue}=e||{};return t[n]=s,await o.dispatchModelManager({trx:r?.trx,connection:r?.connection}).updateRecord(t),typeof s=="string"?(t[n]=new Date(s),t):(t[n]=s,t)}static async truncate(t={}){return this.dispatchModelManager(t).query().truncate()}static async getTableInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getTableInfo(t.table)}static async getIndexInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getIndexInfo(t.table)}static async getTableSchema(){let t=this;return t.establishConnection(),t.sqlInstance.getTableSchema(t.table)}static combineProps(t,e){for(let r in e)Object.assign(t,{[r]:e[r]});}static getColumns(){return Qt(this)}static getRelations(){return Dp(this)}static getIndexes(){return Pp(this)}static getUniques(){return $p(this)}static getChecks(){return Ep(this)}static column(t,...e){C(...e)(this.prototype,t);}static dateColumn(t,...e){C.date(...e)(this.prototype,t);}static datetimeColumn(t,...e){C.datetime(...e)(this.prototype,t);}static timestampColumn(t,...e){C.timestamp(...e)(this.prototype,t);}static timeColumn(t,...e){C.time(...e)(this.prototype,t);}static booleanColumn(t,...e){C.boolean(...e)(this.prototype,t);}static jsonColumn(t,...e){C.json(...e)(this.prototype,t);}static uuidColumn(t,...e){C.uuid(...e)(this.prototype,t);}static ulidColumn(t,...e){C.ulid(...e)(this.prototype,t);}static integerColumn(t,...e){C.integer(...e)(this.prototype,t);}static floatColumn(t,...e){C.float(...e)(this.prototype,t);}static incrementColumn(t,...e){C.increment(...e)(this.prototype,t);}static bigIncrementColumn(t,...e){C.bigIncrement(...e)(this.prototype,t);}static encryptionSymmetricColumn(t,...e){C.encryption.symmetric(...e)(this.prototype,t);}static encryptionAsymmetricColumn(t,...e){C.encryption.asymmetric(...e)(this.prototype,t);}static hasOne(t,...e){Br(...e)(this.prototype,t);}static hasMany(t,...e){vr(...e)(this.prototype,t);}static belongsTo(t,...e){Er(...e)(this.prototype,t);}static manyToMany(t,...e){kr(...e)(this.prototype,t);}static establishConnection(){let t=be.instance;if(!t)throw new f("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){let e;if(t?.connection)e=t.connection.getModelManager(this);else if(t?.trx)e=t.trx.sql.getModelManager(this);else {let r=this;r.establishConnection(),e=r.sqlInstance.getModelManager(r);}return t?.replicationMode&&e.setReplicationMode(t.replicationMode),e}};Dt.softDeleteColumn="deletedAt",Dt.softDeleteValue=Ye();var U=Dt;var Ne=class{constructor(t,e){this.model=U;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Qr=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Kr=class extends Ne{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Lr=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Wr=class extends Ne{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function tl(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(nr,e.prototype)||[];o.push({columns:r,name:t??ar(e.table,r.join("_"))}),k.defineMetadata(nr,o,e.prototype);}}function rl(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(sr,e.prototype)||[];o.push({columns:r,name:t??ce(e.table,r.join("_"))}),k.defineMetadata(sr,o,e.prototype);}}function ol(i,t){return e=>{let r=k.getMetadata(ir,e.prototype)||[];r.push({expression:i,name:t??Tp(e.table,i)}),k.defineMetadata(ir,r,e.prototype);}}function Gk(i){return t=>{let e=t,r=e.query;e.query=function(...o){let n=r.bind(this).call(this,...o);return i(n),n};}}function C(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(k.getMetadata(at,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");k.defineMetadata(at,r,e),k.defineMetadata(at,r,e.constructor);}let n=i.databaseName??L(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??$e(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=k.getMetadata(or,e)||[];a.push(s),k.defineMetadata(or,a,e);}}C.primary=Lf;C.date=oy;C.datetime=ny;C.timestamp=sy;C.time=iy;C.boolean=ry;C.json=ay;C.uuid=Vf;C.ulid=Jf;C.integer=Ff;C.bigInteger=Yf;C.float=Wf;C.decimal=Gf;C.increment=jf;C.bigIncrement=Uf;C.string=Hf;C.text=zf;C.binary=Zf;C.enum=Xf;C.encryption={symmetric:ey,asymmetric:ty};function Lf(i={}){return C({...i,primaryKey:true})}function Wf(i={}){return C({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function Ff(i={}){return C({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function jf(i={}){return C({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function Uf(i={}){return C({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function Vf(i={}){return C({type:"uuid",...i,prepare:t=>t||qe__default.default.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Jf(i={}){return C({type:"ulid",...i,prepare:t=>t||wl(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Hf(i={}){return C({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function zf(i={}){return C({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Yf(i={}){return C({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function Gf(i={}){return C({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Zf(i={}){return C({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Xf(i,t={}){return C({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function ey(i){return C({...i,prepare:t=>t&&hl(i.key,t),serialize:t=>t&&gl(i.key,t)})}function ty(i){return C({...i,prepare:t=>t&&bl(i.publicKey,t),serialize:t=>t&&Tl(i.privateKey,t)})}function ry(i={}){return C({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t,openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function oy(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?se(new Date,"DATE_ONLY",t):typeof d=="string"?d:se(d,"DATE_ONLY",t):r?se(new Date,"DATE_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:pt(d,void 0,t)};return C({type:"date",...s,autoUpdate:e,prepare:d=>{let c=a(d);return o?o(c):c},serialize:d=>{let c=l(d);return n?n(c):c},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function ny(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",d=e??t!==void 0,c=u=>u?r?se(new Date,"ISO",l):typeof u=="string"?u:se(u,"ISO",l):o?se(new Date,"ISO",l):null,p=u=>{if(u!==void 0)return u===null?null:pt(u,void 0,l)};return C({type:"datetime",...a,withTimezone:d,autoUpdate:r,prepare:u=>{let m=c(u);return n?n(m):m},serialize:u=>{let m=p(u);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...a.openApi||{}}})}function sy(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",d=e??t!==void 0,c=u=>u?r?se(new Date,"TIMESTAMP",l):typeof u=="string"?u:se(u,"TIMESTAMP",l):o?se(new Date,"TIMESTAMP",l):null,p=u=>{if(u!==void 0)return u===null?null:pt(u,void 0,l)};return C({type:"timestamp",...a,withTimezone:d,autoUpdate:r,prepare:u=>{let m=c(u);return n?n(m):m},serialize:u=>{let m=p(u);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...a.openApi||{}}})}function iy(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?se(new Date,"TIME_ONLY",t):typeof d=="string"?d:se(d,"TIME_ONLY",t):r?se(new Date,"TIME_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:pt(d,void 0,t)};return C({type:"time",...s,autoUpdate:e,prepare:d=>{let c=a(d);return o?o(c):c},serialize:d=>{let c=l(d);return n?n(c):c},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function ay(i={}){return C({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function Qt(i){try{return k.getMetadata(or,i.prototype)||[]}catch{return []}}function Er(i,t,e){return((r,o)=>{let n=()=>Pe(i().table),s=()=>{let d=r.constructor.table,c=t||n();return ee(d,c,i().table)},a={type:"belongsTo",columnName:o,model:i,foreignKey:t?String(t):n,constraintName:e?.constraintName??s,onUpdate:e?.onUpdate,onDelete:e?.onDelete},l=k.getMetadata(he,r)||[];l.push(a),k.defineMetadata(he,l,r);})}function Br(i,t){return((e,r)=>{let o=()=>Pe(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(he,e)||[];s.push(n),k.defineMetadata(he,s,e);})}function vr(i,t){return((e,r)=>{let o=()=>Pe(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(he,e)||[];s.push(n),k.defineMetadata(he,s,e);})}function kr(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,c=o.constructor.table,p=()=>Pe(c),u=()=>Pe(i().table),m=()=>ee(S(d),s?String(s):p()),y={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??m,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:c,throughModel:d,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):u,wasModelProvided:l}},g=k.getMetadata(he,o)||[];g.push(y),k.defineMetadata(he,g,o);})}function Dp(i){return k.getMetadata(he,i.prototype)||[]}function br(i){return (k.getMetadata(he,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=S(s),l=o();switch(r){case "belongsTo":return new Qr(l,n,a);case "hasOne":return new Lr(l,n,a);case "hasMany":return new Kr(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new f("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new Wr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:S(e.manyToManyOptions.throughModel),leftForeignKey:S(e.manyToManyOptions.leftForeignKey),rightForeignKey:S(e.manyToManyOptions.rightForeignKey)});default:throw new f("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Ip(i){return k.getMetadata(at,i)||k.getMetadata(at,i.prototype)}function Pp(i){return k.getMetadata(nr,i.prototype)||[]}function $p(i){return k.getMetadata(sr,i.prototype)||[]}function Ep(i){return k.getMetadata(ir,i.prototype)||[]}function H(i){return {_phantom:void 0,_apply:i}}function Fr(i){return {_phantom:void 0,_apply:i}}function G(i={}){return H((t,e)=>{C(i)(t,e);})}G.primary=function(t={}){return H((e,r)=>{C.primary(t)(e,r);})};G.string=function(t){return H((e,r)=>{C.string(t??{})(e,r);})};G.text=function(t){return H((e,r)=>{C.text(t??{})(e,r);})};G.integer=function(t){return H((e,r)=>{C.integer(t??{})(e,r);})};G.bigInteger=function(t){return H((e,r)=>{C.bigInteger(t??{})(e,r);})};G.float=function(t){return H((e,r)=>{C.float(t??{})(e,r);})};G.decimal=function(t){return H((e,r)=>{C.decimal(t??{})(e,r);})};G.increment=function(t={}){return H((e,r)=>{C.increment(t)(e,r);})};G.bigIncrement=function(t={}){return H((e,r)=>{C.bigIncrement(t)(e,r);})};G.boolean=function(t){return H((e,r)=>{C.boolean(t??{})(e,r);})};G.date=function(t){return H((e,r)=>{C.date(t??{})(e,r);})};G.datetime=function(t){return H((e,r)=>{C.datetime(t??{})(e,r);})};G.timestamp=function(t){return H((e,r)=>{C.timestamp(t??{})(e,r);})};G.time=function(t){return H((e,r)=>{C.time(t??{})(e,r);})};G.json=function(t){return H((e,r)=>{C.json(t??{})(e,r);})};G.uuid=function(t){return H((e,r)=>{C.uuid(t??{})(e,r);})};G.ulid=function(t){return H((e,r)=>{C.ulid(t??{})(e,r);})};G.binary=function(t){return H((e,r)=>{C.binary(t??{})(e,r);})};G.enum=function(t,e){return H((r,o)=>{C.enum(t,e??{})(r,o);})};G.encryption={symmetric(i){return H((t,e)=>{C.encryption.symmetric(i)(t,e);})},asymmetric(i){return H((t,e)=>{C.encryption.asymmetric(i)(t,e);})}};var ly=G,dy={hasOne(i,t,e){return Fr((r,o)=>{Br(()=>i(r.constructor),t)(r,o);})},hasMany(i,t,e){return Fr((r,o)=>{vr(()=>i(r.constructor),t)(r,o);})},belongsTo(i,t,e){return Fr((r,o)=>{Er(()=>i(r.constructor),t,e)(r,o);})},manyToMany(i,t,e,r){return Fr((o,n)=>{kr(()=>i(o.constructor),t,e,r)(o,n);})}};function uy(i,t){let{columns:e,relations:r,indexes:o,uniques:n,checks:s,hooks:a,options:l}=t;class d extends U{}d.table=i,l?.modelCaseConvention&&(d.modelCaseConvention=l.modelCaseConvention),l?.databaseCaseConvention&&(d.databaseCaseConvention=l.databaseCaseConvention),l?.softDeleteColumn&&(d.softDeleteColumn=l.softDeleteColumn),l?.softDeleteValue!==void 0&&(d.softDeleteValue=l.softDeleteValue);for(let[c,p]of Object.entries(e))p._apply(d.prototype,c);if(r)for(let[c,p]of Object.entries(r))p._apply(d.prototype,c);if(o)for(let c of o)cy(d,c);if(n)for(let c of n)my(d,c);if(s)for(let c of s)py(d,c);return a&&(a.beforeFetch&&(d.beforeFetch=a.beforeFetch),a.afterFetch&&(d.afterFetch=a.afterFetch),a.beforeInsert&&(d.beforeInsert=a.beforeInsert),a.beforeInsertMany&&(d.beforeInsertMany=a.beforeInsertMany),a.beforeUpdate&&(d.beforeUpdate=a.beforeUpdate),a.beforeDelete&&(d.beforeDelete=a.beforeDelete)),d}function cy(i,t){Array.isArray(t)?tl(t)(i):tl(t.columns,t.name)(i);}function my(i,t){Array.isArray(t)?rl(t)(i):rl(t.columns,t.name)(i);}function py(i,t){typeof t=="string"?ol(t)(i):ol(t.expression,t.name)(i);}var nl=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){if(t<=0)return [];let e=this.typeofModel;if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},fy=(i,t)=>new nl(i,t);function yy(i,t){let e=a=>typeof a=="function",r=e(i)?i:U,o=e(i)?t:i,s=class s extends r{};s.column("id",{openApi:{type:"number",required:true},...o,primaryKey:true});let n=s;return n}function hy(i,t){let e=a=>typeof a=="function",r=e(i)?i:U,o=e(i)?t:i,s=class s extends r{};s.column("id",{openApi:{type:"number",required:true},...o,primaryKey:true});let n=s;return n}function Bp(i,t){let e=a=>typeof a=="function",r=e(i)?i:U,o=e(i)?t:i,s=class s extends r{};s.ulidColumn("id",{type:"ulid",openApi:{type:"string",format:"ulid",required:true},...o,primaryKey:true});let n=s;return n}var gy=Bp;function vp(i,t){let e=a=>typeof a=="function",r=e(i)?i:U,o=e(i)?t:i,s=class s extends r{};s.uuidColumn("id",{type:"uuid",openApi:{type:"string",format:"uuid",required:true},...o,primaryKey:true});let n=s;return n}var by=vp;function Ty(i,t){let e=s=>typeof s=="function",r=e(i)?i:U,o=e(i)?t:i;class n extends r{}return U.datetimeColumn("createdAt",{type:"datetime",autoCreate:true,openApi:{type:"string",format:"date-time",required:true},...o?.createdAt}),U.datetimeColumn("updatedAt",{autoUpdate:true,openApi:{type:"string",format:"date-time",required:true},...o?.updatedAt}),U.datetimeColumn("deletedAt",{nullable:true,openApi:{type:"string",format:"date-time",required:false},...o?.deletedAt}),n}var kp=i=>{let t=()=>{for(let[r,o]of Object.entries(i))U.column(r,o);};function e(r){var s;let o=r??U;return s=class extends o{},t(),s}return e},wy=kp;var Qp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw q.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new Q("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw q.error("RedisCacheAdapter::set failed to serialize data"),e}return String(t)}}deserializeData(t){try{return JSON.parse(t)}catch{return t}}async disconnect(){this.redisInstance&&await this.redisInstance.quit();}};var{plural:Sy}=Of__default.default;function Kp(i){let t=i.name,e=L(t,"snake");return Sy(e)}function Lp(){return {$annotations:{}}}var mt=class extends xe{static get collection(){return this._collection||Kp(this)}static query(t={}){return this.dispatchModelManager(t).query()}static rawCollection(){return this.mongoInstance.getCurrentConnection().db().collection(this.collection)}static async find(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).find(t)}static async findOne(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOne(t)}static async findOneOrFail(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOneOrFail(t)}static async insert(t,e={}){return await this.dispatchModelManager(e).insert(t)}static async insertMany(t,e={}){return await this.dispatchModelManager(e).insertMany(t)}static async updateRecord(t,e={}){return await this.dispatchModelManager(e).updateRecord(t)}static async deleteRecord(t,e={}){await this.dispatchModelManager(e).deleteRecord(t);}static establishConnection(){let t=It.getInstance();if(!t)throw new f("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){Zr()(this.prototype,t);}static async afterFetch(t){return t}};pl([Zr()],mt.prototype,"id");async function Qe(i,t,e){if(!t)return null;let r=Lp(),o=yl(i);return (!e||!e.length)&&(e=o),e.includes("id")||e.push("id"),r.$annotations||(r.$annotations={}),await Promise.all(Object.keys(t).map(async n=>{if(n==="_id"){r.id=t._id?.toString();return}if(!o.includes(n)){let a=L(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=L(n,i.modelCaseConvention);r[s]=t[n];})),Object.keys(r.$annotations).length||delete r.$annotations,await Promise.all(e.map(async n=>{if(n!=="id"&&!t.hasOwnProperty(n)){let s=L(n,i.modelCaseConvention);r[s]=null;}})),r}async function jr(i,t,e){return (await Promise.all(t.map(async o=>await Qe(i,o,e)))).filter(o=>o!==null)}var Ur=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,session:this.session}),o=await Qe(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new f("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await jr(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await Qe(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await jr(this.model,o,this.selectFields)}async update(t,e={}){if(e.ignoreHooks||this.model.beforeUpdate(this),(await this.collection.updateMany({_id:this.idObject,...this.whereObject},{$set:t,session:this.session})).modifiedCount===0)return [];let o=await this.collection.find({_id:Object.keys(this.idObject).length?this.idObject:void 0,...this.whereObject},{projection:this.selectFields}).toArray();return await jr(this.model,o,this.selectFields)}async delete(t={}){t.ignoreHooks||this.model.beforeDelete(this),await this.collection.deleteMany(this.whereObject,{session:this.session});}async count(t={}){return t.ignoreHooks||this.model.beforeFetch(this),this.collection.countDocuments(this.whereObject,{session:this.session})}select(t){return this.selectFields=t,this.selectObject=t.reduce((e,r)=>(e[r]=1,e),{}),this}where(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=re("mongodb");if(t==="id")return this.idObject={$eq:new s.ObjectId(n)},this;let a={[t]:{[o]:n}};return this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this}andWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=re("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this)}orWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=re("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(a)):this.whereObject={$or:[a]},this)}whereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotIn(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotNull(t){if(t==="id")return q.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotBetween(t,e){let r=re("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereRaw(t){return this.whereObject={...this.whereObject,...t},this}andRawWhere(t){return this.whereObject={...this.whereObject,...t},this}orRawWhere(t){return this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(t),this}sortById(t){return this.sortObject={_id:t},this}sort(t){return typeof t=="number"?(this.sortObject={_id:t},this):typeof t=="string"?(this.sortObject={[t]:1},this):Array.isArray(t)?(this.sortObject=t.reduce((e,r)=>{if(typeof r=="string")return e[r]=1,e;let o=Object.keys(r)[0],n=Object.values(r)[0];return e[o]=+n,e},{}),this):(this.sortObject=t,this)}limit(t){return this.limitNumber=t,this}offset(t){return this.offsetNumber=t,this}};var Vr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=mt,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new f("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Ur(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await Qe(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await Qe(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Qe(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var Ke=class Ke extends et{constructor(e){super({type:"mongo",url:e?.url,logs:e?.logs});this.mongoClient=null;this.isConnected=false,this.mongoOptions=e?.options,this.url||(this.url=x.MONGO_URL);}async connect(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await de.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,Ke.instance=this;}async connectWithoutSettingPrimary(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await de.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true;}getCurrentConnection(){if(!this.mongoClient)throw new f("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}static async connectToSecondarySource(e){let r=new Ke(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!Ke.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Ke.instance}startSession(){if(!this.mongoClient)throw new f("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}static async disconnect(){if(!this.instance)throw new f("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(e,r){let o=new Ke(e);await o.connectWithoutSettingPrimary();try{await r(o);}finally{await o.disconnect();}}static query(e){return this.getInstance().query(e)}query(e){if(!this.isConnected)throw new f("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:e},this).query()}getModelManager(e,r,o){return new Vr(e,r,o,this.logs)}};Ke.instance=null;var It=Ke;var Z=class Z{constructor(t){this.OK="OK";this.isConnected=false,this.ioRedisConnection=t;}static get ioredis(){return this.redisDataSourceInstance.ioRedisConnection}get ioredis(){return this.ioRedisConnection}static async connect(t){if(this.isConnected)return;let e=t?.port||+x.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new Q("ioredis")});this.redisDataSourceInstance=new Z(new r.default({host:t?.host||x.REDIS_HOST,username:t?.username||x.REDIS_USERNAME,port:e,password:t?.password||x.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new f("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new Q("ioredis")}),r=new e.default({host:t?.host||x.REDIS_HOST,username:t?.username||x.REDIS_USERNAME,port:t?.port||+x.REDIS_PORT||6379,password:t?.password||x.REDIS_PASSWORD,...t}),o=new Z(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new f("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Z.getValue(e)}catch{throw new f("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Z.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED");q.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Z.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Z.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Z.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Z.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=Z.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Z.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Z.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Z.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Z.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Z.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Z.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>Z.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Z.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>Z.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};Z.OK="OK";var sl=Z;var il=class{constructor(t){this.dbType=t,this.migrationName=Pt__default.default.basename(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))),this.schema=new ie(this.dbType);}};async function _y(i){try{return import(url.pathToFileURL(i).href)}catch{let e=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))(i);return {default:e.default||e,...e}}}async function Oy(i){let{build:t}=await import('esbuild').catch(()=>{throw new Error("esbuild is required to import TypeScript files. Install it with: npm install esbuild -D")}),e=Math.random().toString(36).slice(2,8),r=i.replace(/\.ts$/,`.bundled_${e}.mjs`);try{return await t({entryPoints:[i],bundle:!0,platform:"node",format:"esm",sourcemap:"inline",outfile:r,packages:"external",logLevel:"silent"}),await import(url.pathToFileURL(r).href)}finally{await wp__default.default.promises.unlink(r).catch(()=>{});}}async function jp(i,t){let e=Pt__default.default.isAbsolute(i)?i:Pt__default.default.resolve(process.cwd(),i);return e.endsWith(".ts")?Oy(e):_y(e)}var al=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(n=>n.table_name);case "mssql":return r.recordset.map(n=>n.TABLE_NAME);case "oracledb":return (r.rows||[]).map(n=>Array.isArray(n)?n[0]:n?.TABLE_NAME).filter(n=>typeof n=="string"&&n.length>0);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
217
217
  FROM information_schema.tables
218
218
  WHERE table_catalog = '${e}'
219
219
  AND table_schema = 'public'
@@ -327,5 +327,5 @@ CREATE TABLE [migrations] (
327
327
  "id" NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
328
328
  "name" VARCHAR2(255) NOT NULL,
329
329
  "timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
330
- )`}},we=new Ga;var wy=async(i,t)=>{if(i.endsWith(".ts"))return kp(i);try{return import(url.pathToFileURL(i).href)}catch{let o=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));try{let n=o(i);return {default:n.default||n,...n}}catch{throw new f(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function Kr(i,t){switch(i){case "mariadb":case "mysql":let e=t;return await e.query(we.migrationTableTemplateMysql()),(await e.query(we.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":let o=t;return await o.query(we.migrationTableTemplatePg()),(await o.query(we.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await Kp(we.migrationTableTemplateSQLite(),[],t),await Kp(we.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(we.migrationTableTemplateMssql()),(await s.request().query(we.selectAllFromMigrationsTemplate())).recordset;case "oracledb":let d=await t.getConnection();try{try{await d.execute(we.migrationTableTemplateOracle());}catch(p){if(p.errorNum!==955)throw p}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(p=>({id:p[0],name:p[1],timestamp:p[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Lr(i,t,e){let r=qy(t),o=[];for(let n of r){let s=await Sy(n,t),a=new s(i||A.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function Ny(i,t){let e=await wy(i);if(!e.default)throw new f("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}async function Sy(i,t=A.MIGRATION_PATH||"database/migrations",e){t=It.join(t,i);let r=It__default.default.resolve(process.cwd(),t),o=await Ny(r);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function qy(i){let t=process.cwd(),e=It__default.default.resolve(i||A.MIGRATION_PATH||"database/migrations"),r=It__default.default.resolve(t,e);try{let o=up__default.default.readdirSync(r).filter(n=>{let s=It__default.default.extname(n),a=It__default.default.join(r,n);return up__default.default.statSync(a).isFile()&&(s===".ts"||s===".js")});if(o.length)return o;throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}catch{throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}}async function Kp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function Za(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;q.info("Rolling back migrations for database type: "+n);try{let l=await Kr(n,i.getPool()),d=await Lr(n,e,r),c=l.map(m=>m.name),p=d.filter(m=>c.includes(m.migrationName));if(p.length===0){q.info("No pending migrations.");return}if(t);let u=new Qe(i);s&&(a=await i.transaction(),i=a.sql),await u.downMigrations(p),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}q.info("Migrations rolled back successfully");}async function Xa(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;q.info("Running migrations for database type: "+n);try{let l=await Kr(n,i.getPool()),c=(await Lr(n,e,r)).filter(u=>!l.map(m=>m.name).includes(u.migrationName));if(!c.length){q.info("No pending migrations.");return}if(t);let p=new Qe(i);s&&(a=await i.transaction(),i=a.sql),await p.upMigrations(c),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}q.info("Migrations ran successfully");}var Qe=class{constructor(t){this.migrationTable="migrations";this.sql=t||he.instance;}async upMigrations(t){for(let e of t){q.info(`Running migration ${e.migrationName}`),await e.up();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.addMigrationToMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async downMigrations(t){t=t.reverse();for(let e of t){q.info(`Rolling back migration ${e.migrationName}`),await e.down();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.deleteMigrationFromMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async addMigrationToMigrationTable(t){let e=new Date,r=this.sql.getDbType()==="oracledb"?e:e.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"");await this.sql.query(this.migrationTable).insert({name:t.migrationName,timestamp:r});}async deleteMigrationFromMigrationTable(t){await this.sql.query(this.migrationTable).where("name",t.migrationName).delete();}},el=class{constructor(t=A.MIGRATION_PATH||"database/migrations",e){this.migrationPath=t,this.sqlDataSourceInput=e;}async up(){return this.migrate("up")}async down(){return this.migrate("down")}async migrate(t){A.MIGRATION_PATH=this.migrationPath;let e;if(this.sqlDataSourceInput instanceof he)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new he(r),await e.connect();}return t==="up"?Xa(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):Za(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},My=(i,t)=>new el(i,t);var tl=class{constructor(t){this.logger=q;this.sqlDataSource=t;}};exports.BaseSeeder=tl;exports.Collection=ut;exports.HysteriaError=f;exports.InMemoryAdapter=$t;exports.Migration=Ya;exports.MixinFactory=ly;exports.Model=z;exports.ModelQueryBuilder=dt;exports.MongoDataSource=xt;exports.RawNode=x;exports.RedisCacheAdapter=Pp;exports.Schema=ne;exports.SchemaBuilder=yt;exports.SqlDataSource=he;exports.UlidMixin=sy;exports.UuidMixin=iy;exports.WriteOperation=U;exports.belongsTo=Np;exports.bigIntMixin=oy;exports.check=Lk;exports.column=I;exports.createMixin=Dp;exports.createModelFactory=ry;exports.defineMigrator=My;exports.generateOpenApiModel=dh;exports.generateOpenApiModelSchema=uh;exports.generateOpenApiModelWithMetadata=gl;exports.getChecks=Ap;exports.getCollectionProperties=sl;exports.getIndexes=_p;exports.getModelColumns=vt;exports.getPrimaryKey=Rp;exports.getRelations=hr;exports.getRelationsMetadata=Cp;exports.getUniques=Op;exports.hasMany=qp;exports.hasOne=Sp;exports.incrementMixin=ny;exports.index=Qk;exports.logger=q;exports.manyToMany=Mp;exports.property=Ur;exports.redis=za;exports.timestampMixin=ay;exports.ulidMixin=xp;exports.unique=Kk;exports.uuidMixin=Ip;exports.view=Wk;exports.withPerformance=W;//# sourceMappingURL=index.cjs.map
330
+ )`}},Se=new al;var Iy=async(i,t)=>{if(i.endsWith(".ts"))return jp(i);try{return import(url.pathToFileURL(i).href)}catch{let o=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));try{let n=o(i);return {default:n.default||n,...n}}catch{throw new f(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function Jr(i,t){switch(i){case "mariadb":case "mysql":let e=t;return await e.query(Se.migrationTableTemplateMysql()),(await e.query(Se.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":let o=t;return await o.query(Se.migrationTableTemplatePg()),(await o.query(Se.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await Vp(Se.migrationTableTemplateSQLite(),[],t),await Vp(Se.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(Se.migrationTableTemplateMssql()),(await s.request().query(Se.selectAllFromMigrationsTemplate())).recordset;case "oracledb":let d=await t.getConnection();try{try{await d.execute(Se.migrationTableTemplateOracle());}catch(p){if(p.errorNum!==955)throw p}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(p=>({id:p[0],name:p[1],timestamp:p[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Hr(i,t,e){let r=Ey(t),o=[];for(let n of r){let s=await $y(n,t),a=new s(i||x.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function Py(i,t){let e=await Iy(i);if(!e.default)throw new f("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}async function $y(i,t=x.MIGRATION_PATH||"database/migrations",e){t=Pt.join(t,i);let r=Pt__default.default.resolve(process.cwd(),t),o=await Py(r);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function Ey(i){let t=process.cwd(),e=Pt__default.default.resolve(i||x.MIGRATION_PATH||"database/migrations"),r=Pt__default.default.resolve(t,e);try{let o=wp__default.default.readdirSync(r).filter(n=>{let s=Pt__default.default.extname(n),a=Pt__default.default.join(r,n);return wp__default.default.statSync(a).isFile()&&(s===".ts"||s===".js")});if(o.length)return o;throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}catch{throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}}async function Vp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function ll(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;q.info("Rolling back migrations for database type: "+n);try{let l=await Jr(n,i.getPool()),d=await Hr(n,e,r),c=l.map(m=>m.name),p=d.filter(m=>c.includes(m.migrationName));if(p.length===0){q.info("No pending migrations.");return}if(t);let u=new Le(i);s&&(a=await i.transaction(),i=a.sql),await u.downMigrations(p),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}q.info("Migrations rolled back successfully");}async function dl(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;q.info("Running migrations for database type: "+n);try{let l=await Jr(n,i.getPool()),c=(await Hr(n,e,r)).filter(u=>!l.map(m=>m.name).includes(u.migrationName));if(!c.length){q.info("No pending migrations.");return}if(t);let p=new Le(i);s&&(a=await i.transaction(),i=a.sql),await p.upMigrations(c),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}q.info("Migrations ran successfully");}var Le=class{constructor(t){this.migrationTable="migrations";this.sql=t||be.instance;}async upMigrations(t){for(let e of t){q.info(`Running migration ${e.migrationName}`),await e.up();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.addMigrationToMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async downMigrations(t){t=t.reverse();for(let e of t){q.info(`Rolling back migration ${e.migrationName}`),await e.down();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.deleteMigrationFromMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async addMigrationToMigrationTable(t){let e=new Date,r=this.sql.getDbType()==="oracledb"?e:e.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"");await this.sql.query(this.migrationTable).insert({name:t.migrationName,timestamp:r});}async deleteMigrationFromMigrationTable(t){await this.sql.query(this.migrationTable).where("name",t.migrationName).delete();}},ul=class{constructor(t=x.MIGRATION_PATH||"database/migrations",e){this.migrationPath=t,this.sqlDataSourceInput=e;}async up(){return this.migrate("up")}async down(){return this.migrate("down")}async migrate(t){x.MIGRATION_PATH=this.migrationPath;let e;if(this.sqlDataSourceInput instanceof be)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new be(r),await e.connect();}return t==="up"?dl(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):ll(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},By=(i,t)=>new ul(i,t);var cl=class{constructor(t){this.logger=q;this.sqlDataSource=t;}};exports.BaseSeeder=cl;exports.Collection=mt;exports.HysteriaError=f;exports.InMemoryAdapter=Bt;exports.Migration=il;exports.MixinFactory=wy;exports.Model=U;exports.ModelQueryBuilder=ct;exports.MongoDataSource=It;exports.RawNode=D;exports.RedisCacheAdapter=Qp;exports.Schema=ie;exports.SchemaBuilder=gt;exports.SqlDataSource=be;exports.UlidMixin=gy;exports.UuidMixin=by;exports.WriteOperation=V;exports.belongsTo=Er;exports.bigIntMixin=yy;exports.check=ol;exports.col=ly;exports.column=C;exports.createMixin=kp;exports.createModelFactory=fy;exports.defineMigrator=By;exports.defineModel=uy;exports.generateOpenApiModel=Nh;exports.generateOpenApiModelSchema=Sh;exports.generateOpenApiModelWithMetadata=_l;exports.getChecks=Ep;exports.getCollectionProperties=yl;exports.getIndexes=Pp;exports.getModelColumns=Qt;exports.getPrimaryKey=Ip;exports.getRelations=br;exports.getRelationsMetadata=Dp;exports.getUniques=$p;exports.hasMany=vr;exports.hasOne=Br;exports.incrementMixin=hy;exports.index=tl;exports.logger=q;exports.manyToMany=kr;exports.property=Zr;exports.redis=sl;exports.rel=dy;exports.timestampMixin=Ty;exports.ulidMixin=Bp;exports.unique=rl;exports.uuidMixin=vp;exports.view=Gk;exports.withPerformance=W;//# sourceMappingURL=index.cjs.map
331
331
  //# sourceMappingURL=index.cjs.map