hysteria-orm 10.6.6 → 10.6.7

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,4 +1,4 @@
1
- 'use strict';var Se=require('crypto'),We=require('dayjs'),Ap=require('dayjs/plugin/customParseFormat.js'),xp=require('dayjs/plugin/timezone.js'),Ip=require('dayjs/plugin/utc.js'),zm=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),It=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 Se__default=/*#__PURE__*/_interopDefault(Se);var We__default=/*#__PURE__*/_interopDefault(We);var Ap__default=/*#__PURE__*/_interopDefault(Ap);var xp__default=/*#__PURE__*/_interopDefault(xp);var Ip__default=/*#__PURE__*/_interopDefault(Ip);var zm__default=/*#__PURE__*/_interopDefault(zm);var It__default=/*#__PURE__*/_interopDefault(It);var of__default=/*#__PURE__*/_interopDefault(of);var Cp=Object.defineProperty;var Ha=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 za=(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&&Cp(t,e,o),o};var kr=(i,t,e)=>t.has(i)||Ha("Cannot "+e);var Le=(i,t,e)=>(kr(i,t,"read from private field"),e?e.call(i):t.get(i)),Dt=(i,t,e)=>t.has(i)?Ha("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Kr=(i,t,e,r)=>(kr(i,t,"write to private field"),t.set(i,e),e),Ya=(i,t,e)=>(kr(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 Lr=Symbol("mongoProperties");function Wr(){return (i,t)=>{let e=K.getMetadata(Lr,i)||[];e.push(t),K.defineMetadata(Lr,e,i);}}function Ga(i){return K.getMetadata(Lr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function _p(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 Op(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"?_p(i):t==="camel"?Op(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}We__default.default.extend(Ip__default.default);We__default.default.extend(xp__default.default);We__default.default.extend(Ap__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()}},ut=(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 Za=(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)}},Xa=(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)}},el=(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)}},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=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",Fr=jr.length,Ep=10,Bp=16,vp=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Fr;e=jr.charAt(o)+e,i=(i-o)/Fr;}return e},Qp=i=>{let t=Se.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=jr.charAt(o%Fr);}return e},rl=()=>{let i=Math.floor(Date.now()/1e3),t=vp(i,Ep),e=Qp(Bp);return t+e};function Ur(i){return i.replace(/^[`"]|[`"]$/g,"")}function Vr(i,t,e){if(!i.includes(".")){let n=Ur(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=Ur(r),o=Ur(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function S(i){return typeof i=="function"?i():i}var H=(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]=H(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]=H(o,t);}return e};var Oe=class{};Oe.modelCaseConvention="camel",Oe.databaseCaseConvention="snake";var ol;ol=Symbol.toStringTag;var V=class{constructor(t,e,r){this.unWrapFn=t;this.toQueryFn=e;this.executor=r;this[ol]="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 kp=async(i,t,e,r,o=[],n=false)=>{let s=Object.create(t.prototype),a=new Set(e.filter(u=>u.hidden).map(u=>u.columnName)),l=new Map(e.map(u=>[u.databaseName,u])),d=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async u=>{let m=i[u],c=l.get(u)?.columnName??u,p=r.has(c),h=a.has(c),g=n?true:d?d.has(c):true;if(p){if(h||!g)return;if(m===null){s[c]=null;return}let T=r.get(c);if(T&&T.serialize){s[c]=await T.serialize(m);return}s[c]=m;return}(!n||d&&d.has(c))&&(s[c]=m);})),d)for(let u of d)u in s||(s[u]=null);return s},he=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 c=l.match(/\s+as\s+(.+)$/i);c&&s.push(c[1].trim());continue}let u=l;if(u.includes(".")&&(u=u.split(".").pop()),u==="*")continue;let m=o.get(u)?.columnName??u;s.push(m);}e=s;let a=await Promise.all(i.map(async l=>await kp(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 sl=null;function nl(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(m=>m.columnName===n||m.databaseName===n);if(!l)continue;let d=typeof l.type=="string"?l.type:"string",u=Pt[d]||"string";if(u==="string"||u==="textarea"){i.whereLike(n,`%${a}%`);continue}if(u==="boolean"){i.where(n,a==="true"||a===true);continue}if(u==="date"||u==="datetime"){if(typeof a=="object"&&a!==null){let m=a;m.from&&i.where(n,">=",m.from),m.to&&i.where(n,"<=",m.to);continue}i.where(n,a);continue}i.where(n,a);}}function ct(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 Kp(){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=sl;}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(u=>u.columnName===n||u.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 nl(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return nl(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(ct(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(ct(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(ct(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db,returning:["*"]});return ct(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 ct(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 Lp(){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 Wp(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),t=await Kp(),e=await Lp();i.default.registerAdapter({Database:e,Resource:t});}async function Jr(i,t){sl=i;let e=await import('adminjs').catch(()=>{throw new Q("adminjs")});await Wp();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 il(i,t){let{admin:e}=await Jr(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},jp=()=>{try{zm__default.default.readFileSync(".env","utf8").split(`
1
+ 'use strict';var Se=require('crypto'),We=require('dayjs'),Ap=require('dayjs/plugin/customParseFormat.js'),xp=require('dayjs/plugin/timezone.js'),Ip=require('dayjs/plugin/utc.js'),zm=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),It=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 Se__default=/*#__PURE__*/_interopDefault(Se);var We__default=/*#__PURE__*/_interopDefault(We);var Ap__default=/*#__PURE__*/_interopDefault(Ap);var xp__default=/*#__PURE__*/_interopDefault(xp);var Ip__default=/*#__PURE__*/_interopDefault(Ip);var zm__default=/*#__PURE__*/_interopDefault(zm);var It__default=/*#__PURE__*/_interopDefault(It);var of__default=/*#__PURE__*/_interopDefault(of);var Cp=Object.defineProperty;var Ha=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 za=(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&&Cp(t,e,o),o};var kr=(i,t,e)=>t.has(i)||Ha("Cannot "+e);var Le=(i,t,e)=>(kr(i,t,"read from private field"),e?e.call(i):t.get(i)),Dt=(i,t,e)=>t.has(i)?Ha("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Kr=(i,t,e,r)=>(kr(i,t,"write to private field"),t.set(i,e),e),Ya=(i,t,e)=>(kr(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 Lr=Symbol("mongoProperties");function Wr(){return (i,t)=>{let e=K.getMetadata(Lr,i)||[];e.push(t),K.defineMetadata(Lr,e,i);}}function Ga(i){return K.getMetadata(Lr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function _p(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 Op(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"?_p(i):t==="camel"?Op(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}We__default.default.extend(Ip__default.default);We__default.default.extend(xp__default.default);We__default.default.extend(Ap__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()}},ut=(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 Za=(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)}},Xa=(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)}},el=(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)}},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=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",Fr=jr.length,Ep=10,Bp=16,vp=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Fr;e=jr.charAt(o)+e,i=(i-o)/Fr;}return e},Qp=i=>{let t=Se.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=jr.charAt(o%Fr);}return e},rl=()=>{let i=Math.floor(Date.now()/1e3),t=vp(i,Ep),e=Qp(Bp);return t+e};function Ur(i){return i.replace(/^[`"]|[`"]$/g,"")}function Vr(i,t,e){if(!i.includes(".")){let n=Ur(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=Ur(r),o=Ur(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 ol;ol=Symbol.toStringTag;var U=class{constructor(t,e,r){this.unWrapFn=t;this.toQueryFn=e;this.executor=r;this[ol]="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 kp=async(i,t,e,r,o=[],n=false)=>{let s=Object.create(t.prototype),a=new Set(e.filter(u=>u.hidden).map(u=>u.columnName)),l=new Map(e.map(u=>[u.databaseName,u])),d=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async u=>{let m=i[u],c=l.get(u)?.columnName??u,p=r.has(c),h=a.has(c),g=n?true:d?d.has(c):true;if(p){if(h||!g)return;if(m===null){s[c]=null;return}let T=r.get(c);if(T&&T.serialize){s[c]=await T.serialize(m);return}s[c]=m;return}(!n||d&&d.has(c))&&(s[c]=m);})),d)for(let u of d)u in s||(s[u]=null);return s},he=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 c=l.match(/\s+as\s+(.+)$/i);c&&s.push(c[1].trim());continue}let u=l;if(u.includes(".")&&(u=u.split(".").pop()),u==="*")continue;let m=o.get(u)?.columnName??u;s.push(m);}e=s;let a=await Promise.all(i.map(async l=>await kp(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 sl=null;function nl(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(m=>m.columnName===n||m.databaseName===n);if(!l)continue;let d=typeof l.type=="string"?l.type:"string",u=Pt[d]||"string";if(u==="string"||u==="textarea"){i.whereLike(n,`%${a}%`);continue}if(u==="boolean"){i.where(n,a==="true"||a===true);continue}if(u==="date"||u==="datetime"){if(typeof a=="object"&&a!==null){let m=a;m.from&&i.where(n,">=",m.from),m.to&&i.where(n,"<=",m.to);continue}i.where(n,a);continue}i.where(n,a);}}function ct(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 Kp(){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=sl;}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(u=>u.columnName===n||u.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 nl(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return nl(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(ct(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(ct(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(ct(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db,returning:["*"]});return ct(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 ct(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 Lp(){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 Wp(){let i=await import('adminjs').catch(()=>{throw new Q("adminjs")}),t=await Kp(),e=await Lp();i.default.registerAdapter({Database:e,Resource:t});}async function Jr(i,t){sl=i;let e=await import('adminjs').catch(()=>{throw new Q("adminjs")});await Wp();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 il(i,t){let{admin:e}=await Jr(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},jp=()=>{try{zm__default.default.readFileSync(".env","utf8").split(`
2
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=jp();var Ye=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
3
3
  Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}}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 Up=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},Vp=i=>i.openApi?.required??false,Jp=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=Up(r));return e},Hp=i=>{let t=i.getColumns(),e=[];for(let r of t)Vp(r)&&e.push(r.columnName);return e||[]},Hr=i=>{let t=Jp(i),e=Hp(i);return {type:"object",properties:t,required:e.length?e:[]}},Wy=i=>i.map(t=>Hr(t)),Fy=i=>Hr(i),al=i=>i.map(t=>({...Hr(t),modelName:t.name,$id:t.name}));var zr=(i,t)=>{let e=Se__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var Ge={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function Gp(){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 Yr(i,t){let e=Gp(),r=i.toUpperCase();return i==="error"?`${Ge.error}[${r}] ${e}
4
4
  ${t}${Ge.reset}
@@ -161,8 +161,8 @@ ORDER BY ordinal_position`,bindings:[]}}},Lc=new Ii;var Di=class{toSql(t){let e=
161
161
  name as column_name
162
162
  FROM pragma_table_info('${t.table}')
163
163
  WHERE pk > 0
164
- ORDER BY pk`,bindings:[]}}},Bm=new Ra;var _a=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},vm=new _a;var Oa=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 y(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 y(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 u of l)u==="("&&d++,u===")"&&d--;if(d>0)return e}return `as "${r}"`})}},Qm=new Oa;var Aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("sqlite",e.column),o=ae.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}},km=new Aa;var xa=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new y(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},Km=new xa;var Ia=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}}},Lm=new Ia;var Da=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new y(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}}},Wm=new Da;var Pa=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 y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new y(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new y(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 y(this.model).formatStringColumn("sqlite",t):t}},Fm=new Pa;var $a=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}}},jm=new $a;var Ea=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new y(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}}},Um=new Ea;var Ba=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}}},Vm=new Ba;var va=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}}},Jm=new va;var Hm={mssql:{alter_table:{add_column:ul,add_constraint:cl,add_primary_key:ml,alter_column_type:pl,alter_table:fl,drop_column:yl,drop_constraint:hl,drop_default:gl,drop_not_null:bl,drop_primary_key:Tl,rename_column:wl,rename_table:Nl,set_default:Sl,set_not_null:ql,set_table_options:Ml},column:{column_type:Cl},constraint:{after:Rl,constraint:_l},create_table:{create_table:Ol},delete:{delete:Al},distinct:{distinct:xl,distinct_on:Il},drop_table:{drop_table:Dl},extension:{create_extension:Pl},from:{from:$l},group_by:{group_by:El},having:{having:Bl},index_op:{create_index:vl,drop_index:Ql},insert:{insert:kl},join:{join:Kl},limit:{limit:Ll},lock:{lock:Wl},offset:{offset:Fl},on_duplicate:{on_duplicate:jl},order_by:{order_by:Ul},raw:{raw:Vl},schema:{foreign_key_info:Jl,index_info:Hl,primary_key_info:zl,table_info:Yl},select:{select:Gl,select_json:Zl},truncate:{truncate:Xl},union:{union:ed},update:{update:td},where:{where:rd,where_group:od,where_json:nd,where_subquery:sd},with:{with:id}},mysql:{alter_table:{add_column:ad,add_constraint:ld,add_primary_key:dd,alter_column_type:ud,alter_table:cd,drop_column:md,drop_constraint:pd,drop_default:fd,drop_not_null:yd,drop_primary_key:hd,rename_column:gd,rename_table:bd,set_default:Td,set_not_null:wd,set_table_options:Nd},column:{column_type:Sd},constraint:{after:qd,constraint:Md},create_table:{create_table:Cd},delete:{delete:Rd},distinct:{distinct:_d,distinct_on:Od},drop_table:{drop_table:Ad},extension:{create_extension:xd},from:{from:Id},group_by:{group_by:Dd},having:{having:Pd},index_op:{create_index:$d,drop_index:Ed},insert:{insert:Bd},join:{join:vd},limit:{limit:Qd},lock:{lock:kd},offset:{offset:Kd},on_duplicate:{on_duplicate:Ld},order_by:{order_by:Wd},raw:{raw:Fd},schema:{foreign_key_info:jd,index_info:Ud,primary_key_info:Vd,table_info:Jd},select:{select:Hd,select_json:zd},truncate:{truncate:Yd},union:{union:Gd},update:{update:Zd},where:{where:Xd,where_group:eu,where_json:tu,where_subquery:ru},with:{with:ou}},oracledb:{alter_table:{add_column:nu,add_constraint:su,add_primary_key:iu,alter_column_type:au,alter_table:lu,drop_column:du,drop_constraint:uu,drop_default:cu,drop_not_null:mu,drop_primary_key:pu,rename_column:fu,rename_table:yu,set_default:hu,set_not_null:gu,set_table_options:bu},column:{column_type:Tu},constraint:{after:wu,constraint:Nu},create_table:{create_table:Su},delete:{delete:qu},distinct:{distinct:Mu,distinct_on:Cu},drop_table:{drop_table:Ru},extension:{create_extension:_u},from:{from:Ou},group_by:{group_by:Au},having:{having:xu},index_op:{create_index:Iu,drop_index:Du},insert:{insert:Pu},join:{join:$u},limit:{limit:Eu},lock:{lock:Bu},offset:{offset:vu},on_duplicate:{on_duplicate:Qu},order_by:{order_by:ku},raw:{raw:Ku},schema:{foreign_key_info:Lu,index_info:Wu,primary_key_info:Fu,table_info:ju},select:{select:Uu,select_json:Vu},truncate:{truncate:Ju},union:{union:Hu},update:{update:zu},where:{where:Yu,where_group:Gu,where_json:Zu,where_subquery:Xu},with:{with:ec}},postgres:{alter_table:{add_column:tc,add_constraint:rc,add_primary_key:oc,alter_column_type:nc,alter_table:sc,drop_column:ic,drop_constraint:ac,drop_default:lc,drop_not_null:dc,drop_primary_key:uc,rename_column:cc,rename_table:mc,set_default:pc,set_not_null:fc,set_table_options:yc},column:{column_type:hc},constraint:{after:gc,constraint:bc},create_table:{create_table:Tc},delete:{delete:wc},distinct:{distinct:Nc,distinct_on:Sc},drop_table:{drop_table:qc},extension:{create_extension:Mc},from:{from:Cc},group_by:{group_by:Rc},having:{having:_c},index_op:{create_index:Oc,drop_index:Ac},insert:{insert:xc},join:{join:Ic},limit:{limit:Dc},lock:{lock:Pc},offset:{offset:$c},on_duplicate:{on_duplicate:Ec},order_by:{order_by:Bc},raw:{raw:vc},schema:{foreign_key_info:Qc,index_info:kc,primary_key_info:Kc,table_info:Lc},select:{select:Wc,select_json:Fc},truncate:{truncate:jc},union:{union:Uc},update:{update:Vc},where:{where:Jc,where_group:Hc,where_json:zc,where_subquery:Yc},with:{with:Gc}},sqlite:{alter_table:{add_column:Zc,add_constraint:Xc,alter_column_type:em,alter_table:tm,drop_column:rm,drop_constraint:om,drop_default:nm,drop_not_null:sm,drop_primary_key:im,rename_column:am,rename_table:lm,set_default:dm,set_not_null:um,set_table_options:cm},column:{column_type:mm},constraint:{after:pm,constraint:fm},create_table:{create_table:ym},delete:{delete:hm},distinct:{distinct:gm,distinct_on:bm},drop_table:{drop_table:Tm},extension:{create_extension:wm},from:{from:Nm},group_by:{group_by:Sm},having:{having:qm},index_op:{create_index:Mm,drop_index:Cm},insert:{insert:Rm},join:{join:_m},limit:{limit:Om},lock:{lock:Am},offset:{offset:xm},on_duplicate:{on_duplicate:Im},order_by:{order_by:Dm},raw:{raw:Pm},schema:{foreign_key_info:$m,index_info:Em,primary_key_info:Bm,table_info:vm},select:{select:Qm,select_json:km},truncate:{truncate:Km},union:{union:Lm},update:{update:Wm},where:{where:Fm,where_group:jm,where_json:Um,where_subquery:Vm},with:{with:Jm}}};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(C=>!!C&&C.folder==="distinctOn"),n=!o&&t.find(C=>!!C&&C.folder==="distinct"),s=this.dbType==="mssql"?t.find(C=>!!C&&C.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(C=>C!==null&&C.folder!=="distinct"&&C.folder!=="distinctOn"),d=l.some(C=>C.folder==="offset"),u=l.some(C=>C.folder==="order_by"),m=l.find(C=>C.folder==="limit"),c=l.find(C=>C.folder==="offset"),p=this.dbType==="mssql"&&m&&!d&&!u,h=this.dbType==="mssql"&&!p&&(m||c),g=this.dbType==="oracledb"&&(m||c),T=[],N=[],q=null;p&&m&&N.push(m.limit);for(let C=0;C<l.length;C++){let I=l[C];if(p&&I.folder==="limit"||h&&(I.folder==="limit"||I.folder==="offset")||g&&(I.folder==="limit"||I.folder==="offset"))continue;I.currParamIndex=e+N.length;let P=Hm[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 _=P.toSql(I);if(!_.sql||!_.sql.trim().length)continue;let k=l[C+1],$=!k||k.keyword!==I.keyword?"":k.chainsWith;if(I.folder==="lock"||I.folder==="on_duplicate"||I.folder==="schema"){T.push(`${_.sql}${$}`),N.push(..._.bindings),q=I.keyword;continue}if(q!==I.keyword||I.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let G=I.keyword;if(I.folder==="with"&&this.dbType!=="mssql"){let X=C,Ne=false;for(;X<l.length&&l[X].keyword===I.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=p?`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}${$}`);}q=I.keyword;}else T.push(`${_.sql}${$}`);N.push(..._.bindings);}if(h){u||T.push("order by (select null)");let C=c?.offset??0;N.push(C);let P=`offset @${e+N.length-1} rows`;if(m){N.push(m.limit);let _=e+N.length-1;P+=` fetch next @${_} rows only`;}T.push(P);}if(g){u||T.push("order by null");let C=c?.offset??0;N.push(C);let P=`offset :${e+N.length-1} rows`;if(m){N.push(m.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 vt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Qt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Lt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ue=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var tt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Wt=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 ge=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 Ft=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=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 jt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var rt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Ut=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 Vt=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 Jt=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 U=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 Ht=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 zt=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 Yt=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 Gt=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 Zt=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 ot=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 Xt=Symbol("columns"),nt=Symbol("primaryKey"),ce=Symbol("relations"),er=Symbol("indexes"),tr=Symbol("uniques"),Ie=i=>`${of__default.default.singular(i)}_id`,rr=(i,t)=>`idx_${i}_${t}`,le=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,De=(i,t)=>`pk_${i}_${t}`;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 st=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 or=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var nr=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 U("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new U("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 U("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 U("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 U("not_null",{columns:[S(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new U("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 U("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new U("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??le(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new U("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||le(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 U("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new U("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new or(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new U("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 nr(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 sr=class extends Pe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new D(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(m=>m.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(m=>{let c=m;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new Lt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(m=>{let c=m;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new ue(m));});}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(p=>p.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(p=>p.constraintType==="null"),u=o.getNodes().find(p=>p.constraintType==="not_null")||l,m=o.getNodes().find(p=>p.constraintType==="default"),c={};u&&(c.nullable=u.constraintType==="null"),m&&(m.defaultValue===void 0||m.defaultValue===null?c.dropDefault=true:c.default=m.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new Wt(S(a),s,c)),u&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(u.constraintType==="not_null"?this.nodes.push(new Jt(S(a))):u.constraintType==="null"&&this.nodes.push(new jt(S(a)))),m&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(m.defaultValue===void 0||m.defaultValue===null?this.nodes.push(new pt(S(a))):this.nodes.push(new Vt(S(a),m.defaultValue))),o.getNodes().forEach(p=>{let h=p;switch(h.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:h.constraintName});break;case "foreign_key":this.foreignKey(S(a),h.references?.table??"",S(h.references?.columns?.[0]??""),{constraintName:h.constraintName,onDelete:h.onDelete,onUpdate:h.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ft(t));}renameColumn(t,e){this.nodes.push(new Ut(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 tt([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 ue(new U(...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 ue(new U("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 ue(new U("unique",{columns:[t],constraintName:e?.constraintName??le(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 be(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??le(this.table,t);this.nodes.push(new be(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 be(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 rt(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 me=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 D(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!zm__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=zm__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 Ht(t,n,o.getNamedConstraints(),r?.ifNotExists,a),d=s.parse([l]).sql,u=d.startsWith("create table")?d:`create table ${d}`;this.rawQuery(u),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new sr(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 ge(t,s),u=n.parse([d]).sql;if(!u||!u.trim())return;let m=u.startsWith("alter table")?u:`alter table ${u}`;this.rawQuery(m),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 zt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new ge(t,[new et(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new ot(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||rr(t,e.join("_")),n=new Gt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Zt(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new tt(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??le(t,o.join("_")),s=new U("unique",{columns:o,constraintName:n}),a=new ge(t,[new ue(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 be(o),s=new ge(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)?le(t,e.join("_")):le(t,e),n=r?.constraintName??o,s=new be(n),a=new ge(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new rt,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new U(...e),o=new ge(t,[new ue(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new be(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 U("check",{checkExpression:e,constraintName:o}),s=new ge(t,[new ue(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){this.dropConstraint(t,e);}createExtension(t,e=true){let r=new Yt(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 ir,Gm,yt=class{constructor(t,e){Dt(this,ir);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new me(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=Ya(this,ir,Gm).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(`;
165
- `)}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"}};ir=new WeakSet,Gm=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 ar=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 u of d)u.type==="belongsTo"&&u.model().table===n.table&&a.push(`fk.${l.table}.${u.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(u=>u.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let u=l.getRelations();for(let m of u)m.columnName===d.columnName&&a.push(`fk.${n.table}.${m.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(u=>u.table===a&&u.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){return this.sql.getDbType()==="sqlite"?[]:t.relation.name?this.sql.schema().alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}).toQueries():[]}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 lr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new ar(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 me(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 u=a||De(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});}).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(u=>u.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]});}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.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 me(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 c=t.relation.model(),p=c.primaryKey,g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=L(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),h=p.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",T=p.find(N=>N.columnName===g);if(T)n=T.databaseName;else {let N=c?.databaseCaseConvention||"preserve";n=L(n||g,N);}}}else {let p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=L(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=L(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=L(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=S(c),h=a.find(g=>g.columnName===p);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=L(p,g);}}let u=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let p=o||Z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:u,onUpdate:m});}).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 af(i){return i.replace(/\s+/g," ").trim()}function lf(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function $e(i,t){let e=af(t.toLowerCase()),r=lf(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 dr=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:[],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 m of n.indexes)o.indexes.map(c=>c.name).includes(m.name)||e.data.indexesToAdd.push({table:r.table,index:m.name});let u=r.getUniques?.()||[];for(let m of u)e.data.uniquesToAdd.push({table:r.table,name:m.name||"mandatory",columns:m.columns});for(let m of n.relations){if(m.type!=="belongsTo")continue;let c=S(m.constraintName);o.foreignKeys.find(h=>h.name===c)||e.data.relationsToAdd.push({table:r.table,relation:m,onDelete:m.onDelete,onUpdate:m.onUpdate});}return}for(let u of n.columns)o.columns.some(c=>c.name===u.databaseName||c.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(c=>c.databaseName===u.name||c.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(c=>c.name===u.name&&c.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(c=>c.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(c=>c.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}for(let u of n.columns){let m=o.columns.find(h=>h.name===u.databaseName||h.name===u.columnName);if(!m)continue;let c=!e.areColumnsEqual(m,u,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:u});(c||p)&&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 p=S(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:S(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?S(u.constraintName):Z(p,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(p=>p.name===m))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,u,p))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let l=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let m=S(u.foreignKey)||u.columnName,p=r.getColumns().find(h=>h.columnName===m)?.databaseName||m;return S(u.constraintName)||Z(r.table,p,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&l.has(u.name))continue;n.relations.find(c=>c.type!=="belongsTo"&&c.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,c,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(c=>e.relationMatchesDbRelation(r,u,c));m&&!e.areRelationsEqual(m,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let d=r.primaryKey;if(d&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[d]}),o.primaryKey&&!d&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),d&&o.primaryKey){let u=r.getColumns().find(m=>m.columnName===d);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:d});}})),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 lr(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,u=t.isNullable;o=o&&d===u;}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",m=d.getColumns().find(h=>h.columnName===u),c=d.table,p=m?.databaseName||u;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}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(),u=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,m=l.find(g=>g.columnName===u);m&&(u=m.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}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 u=String(t.dbColumns.defaultValue),m=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,u),p=this.normalizeDefaultValue(e,o||r,m);return c!==p?"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);return n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o)?"current_timestamp":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",u=s.getColumns().find($=>$.columnName===l),m=a.getColumns().find($=>$.columnName===d);if(!u||!m)continue;let c=S(o.manyToManyOptions.leftForeignKey)||l,p=S(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(u,c),T=this.clonePkAsColumn(m,p),N=h.columns.find($=>$.name===c),q=h.columns.find($=>$.name===p),O=N?this.areColumnsEqual(N,g,h.indexes):false,C=q?this.areColumnsEqual(q,T,h.indexes):false;for(let $ of h.foreignKeys){let G=$.referencedTable===s.table,X=$.referencedTable===a.table;if(!G&&!X)continue;let Ne=G?c:p,_e=$.columns[0];_e&&_e!==Ne&&(this.data.relationsToDrop.push({table:n,relation:$}),_e!==c&&_e!==p&&this.data.columnsToDrop.push({table:n,column:_e}));}let I={};O||(I[g.databaseName]=g),C||(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,c,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),k=h.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),Ke=h.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===p);if(!k){let $=h.foreignKeys.find(G=>G.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(P);}if(!Ke){let $=h.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,u=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=S(a.constraintName)||Z(o.table,u,a.model().table);s.add(m);}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,u=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let T=g.primaryKey||"id";u=g.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let T=m.has(g.columns[0]),N=g.referencedTable===d,q=g.referencedColumns[0]===u;return T&&N&&q}),p=S(o.relation.constraintName)||Z(o.table,l,d),h=e.get(o.table)||new Set;if(c||p&&h.has(p))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),q=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,C=await this.sql.getTableSchema(g),I=C.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),P=C.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===N&&_.referencedTable===o.relation.model().table);if(q&&I||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 m=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.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 it=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 z=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 pe=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 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 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 ne=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 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 df=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,uf=/^\d{4}-\d{2}-\d{2}$/,Qa=i=>typeof i!="string"?i:df.test(i)?new Date(i.replace(" ","T")+"Z"):uf.test(i)?new Date(i+"T00:00:00Z"):i,cf=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);}}),Xm=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await cf(r):t[e]=r;}return t};var ur=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);});}},ep=(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,u)=>{n.run(i,t,function(m){m&&u(m),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,u)=>{n.all(i,t,(m,c)=>{m&&u(m),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.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((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([h]);return}let g=h?.[a]||this.lastID;if(!g)return c(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[g],(N,q)=>{if(N)return c(N);m([q]);});});});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((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(d);});});let u=[];return new Promise(async(m,c)=>{try{let p=d.map(async h=>{let g=new y(s),{columns:T,values:N}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),q=Object.fromEntries(T.map((P,_)=>[P,N[_]])),O=new b(s,e.getDbType()),{sql:C,bindings:I}=O.parse([new z(new F(s.table),[q])]);return new Promise((P,_)=>{n.run(C,I,function(k){if(k)return _(k);let Ke=h[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);});});})});u=await Promise.all(p),m(u);}catch(p){c(p);}})}return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.message)):d(this.changes);});})};var J=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,u=i.replace(/\?/g,()=>`$${++d}`),m=await ht(()=>l.query(u,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?m.rows:o==="raw"?m:m.rowCount;case "sqlite":let c=await ht(()=>ep(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(c)?c:[c]:c;case "mssql":let p=e.getPool(),h=e.sqlConnection?e.sqlConnection.request():p.request();t.forEach((I,P)=>{h.input(`p${P}`,I);});let g=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${g++}`),N=await ht(()=>h.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?N.rowsAffected[0]:o==="raw"?N:N.recordset;case "oracledb":let q=4002,O=null,C=!!e.sqlConnection;try{O=e.sqlConnection?e.sqlConnection:await e.getConnection();let I=t.map(Qa),P=0,_=i.replace(/\?/g,()=>`:${++P}`),k=await ht(()=>O.execute(_,I,{outFormat:q,autoCommit:!C}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?k.rowsAffected:o==="raw"?k:await Promise.all(k.rows?.map(async $=>{let G=await Xm($),X={};for(let Ne in G)X[Ne.toLowerCase()]=G[Ne];return X})??[])}finally{O&&!C&&await O.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},mr=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}),u=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,h=()=>{try{a.release();}catch{}};return u.on("data",g=>{if(o.onData){m++,Promise.resolve(o.onData(l,g)).then(()=>{m--,c&&m===0&&!p&&(h(),l.end());}).catch(T=>{p=true,h(),l.destroy(T);});return}l.write(g);}),u.on("end",()=>{c=true,m===0&&!p&&(h(),l.end());}),u.on("error",g=>{p=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),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}),u=0,m=i.replace(/\?/g,()=>`$${++u}`),c=new l.default(m,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(c),h=0,g=false,T=false,N=q=>{try{a.release(q);}catch{}};return p.on("data",q=>{if(o.onData){h++,Promise.resolve(o.onData(d,q)).then(()=>{h--,g&&h===0&&!T&&(N(),d.end());}).catch(O=>{T=true,N(O),d.destroy(O);});return}d.write(q);}),p.on("end",()=>{g=true,h===0&&!T&&(N(),d.end());}),p.on("error",q=>{T=true,N(q),d.destroy(q);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new ur(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((h,g)=>{l.input(`p${g}`,h);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),m=0,c=false,p=false;return l.on("row",h=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,h)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(g=>{p=true,a.destroy(g);});return}a.write(h);}}),l.on("error",h=>{p=true,a.destroy(h);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(u),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,u=0,m=i.replace(/\?/g,()=>`:${++u}`),c=t.map(Qa),p=a.queryStream(m,c,{outFormat:d}),h=0,g=false,T=false,N=async()=>{try{await a.close();}catch{}};return p.on("data",q=>{if(T)return;let O={};for(let C in q)O[C.toLowerCase()]=q[C];if(o.onData){h++,Promise.resolve(o.onData(l,O)).then(()=>{h--,g&&h===0&&!T&&(N(),l.end());}).catch(C=>{T=true,N(),l.destroy(C);});return}l.write(O);}),p.on("end",()=>{g=true,h===0&&!T&&(N(),l.end());}),p.on("error",q=>{T=true,N(),l.destroy(q);}),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++,ll(`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=pr(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 fr(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 tp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var at=i=>typeof i=="number"?i:parseFloat(i);var de=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 yr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var hr=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 se=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 gr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var br=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 Tr=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"&&M.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new gr(t),this}offset(t){return typeof t!="number"&&M.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new br(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 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 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 R(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new R(t,"or",true,"=",e??[],true)),this}};var wr=class extends Tr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Nr=class extends wr{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 de(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=L(o,this.model.databaseCaseConvention);this.selectNodes.push(new de(n));}),this}selectRaw(e){return this.selectNodes.push(new de(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":L(r,this.model.databaseCaseConvention);return this.selectNodes.push(new de(`${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 yr,this}distinctOn(...e){return this.distinctOnNode=new hr(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 Sr=class extends Nr{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}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 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 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 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 qr=class extends Sr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"or",false,"raw",e)),this}};var v=class i extends qr{constructor(e,r=fe.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 y(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 de(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new de(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 mr(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:tp(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?at(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?at(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&M.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:fr(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 st("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 st("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 st("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 z(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((p,h)=>[p,a[h]]));this.insertNode=new z(this.fromNode,[l],r,n);let{sql:d,bindings:u}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await J(d,u,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}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 z(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 m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((h,g)=>[h,p[g]]))}));this.insertNode=new z(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),u=await J(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return u})}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 z(new F(this.model.table),[a],void 0,true),this.onDuplicateNode=new pe(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"),u=Object.fromEntries(l.map((g,T)=>[g,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([u],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new z(new F(this.model.table),[u],void 0,true),new pe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),h=await J(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}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 z(new F(this.model.table),s,void 0,true),this.onDuplicateNode=new pe(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 c=>{let{columns:p,values:h}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),g=Object.fromEntries(p.map((T,N)=>[T,h[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 z(new F(this.model.table),a,void 0,true),new pe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),u=await this.getSqlDataSource("write"),m=await J(l,d,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}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),u=[],m=e.map(k=>`select ${a.map($=>(u.push(k[$]),`@${u.length}`)).join(", ")}`),c=a.map(d).join(", "),p=m.join(" union all "),h=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(", "),q=n.returning&&n.returning.length?n.returning.map(k=>`inserted.${d(k)}`).join(", "):a.map(k=>`inserted.${d(k)}`).join(", "),C=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",I=`merge into ${l} as target using (${p}) as source (${c}) on ${h} ${C} when not matched then insert (${T}) values (${N}) output ${q};`,P=await this.getSqlDataSource("write"),_=await J(I,u,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 V(()=>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 J(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}truncate(){return this.truncateNode=new ot(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 it(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=He()}=e||{};return this.updateNode=new Me(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 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 J(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 de("*")]);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=H(this.modelSelectedColumns),e.distinctNode=H(this.distinctNode),e.distinctOnNode=H(this.distinctOnNode),e.selectNodes=H(this.selectNodes),e.withQuery=H(this.withQuery),e.joinNodes=H(this.joinNodes),e.whereNodes=H(this.whereNodes),e.groupByNodes=H(this.groupByNodes),e.havingNodes=H(this.havingNodes),e.orderByNodes=H(this.orderByNodes),e.lockQueryNodes=H(this.lockQueryNodes),e.unionNodes=H(this.unionNodes),e.withNodes=H(this.withNodes),e.fromNode=H(this.fromNode),e.limitNode=H(this.limitNode),e.offsetNode=H(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 de("*")]),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 lt=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 he(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 mr(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),u=await he([d],this.model,this.modelSelectedColumns);u&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([u]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}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:fr(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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereNotExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereNotExists(u),this}clone(){let e=super.clone();return e.relationQueryBuilders=H(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(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let h=n.get(String(p));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let h=s.get(String(p));c[e.columnName]=h||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(c=>{let p=c[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=a.get(String(p))||[];c[e.columnName]=h;});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,u=l.leftForeignKey,m=this.modelColumnsMap.get(u)||this.modelColumnsDatabaseNames.get(u)||L(u,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let h=String(p);d.has(h)||d.set(h,[]),delete c[m],d.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=d.get(String(p))||[];c[e.columnName]=h;});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}`,u=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(d,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${u}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>Vr(_,d,e.model.table));return m.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let N=Se__default.default.randomBytes(6).toString("hex"),q=`${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 C=`${Se__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,I=e.with(q,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,C]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${O}) as rn_${N}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));h&&I.whereRaw(`rn_${N} <= ${h+(g||0)}`),g&&I.whereRaw(`rn_${N} > ${g}`);let P=T.map(_=>Vr(_,q,e.model.table));return I.select(...P).select([`${q}.${C}`,p.leftForeignKey]).from(q);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 y(r.model),a=new y(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}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${u}`),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}`),u=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${u}`),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(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let m=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).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 rp(i){let t=i.name,e=L(t,"snake");return of__default.default(e)}function op(){return {}}var wt=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 y(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 z(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 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"),u={};l.forEach((N,q)=>{let O=d[q];u[N]=O,t[N]??(t[N]=O);});let m=!e.returning||e.returning.length===0,{sql:c,bindings:p}=this.astParser.parse([new z(new F(this.model.table),[u],e.returning,m)]),h=await J(c,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(h,[t],"one",e.returning);let g=h[0];return g?(await this.model.afterFetch?.([g]),await he([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 z(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 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"),q={};T.forEach((O,C)=>{let I=N[C];q[O]=I,g[O]??(g[O]=I);}),l.push(q);}let d=!e.returning||e.returning.length===0,{sql:u,bindings:m}=this.astParser.parse([new z(new F(this.model.table),l,e.returning,d)]),c=await J(u,m,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(c,t,"many",e.returning)||[];let p=c;return p.length?(await this.model.afterFetch?.(p),await he(p,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(u=>Object.fromEntries(Object.keys(u).map(m=>[m,u[m]]))),s=new z(new F(this.model.table),n,void 0,true),a=new pe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let u=this.astParser.parse([s,a]);return {sql:xe(this.sqlDataSource,u.sql),bindings:u.bindings}},d=()=>{let{sql:u,bindings:m}=l();return Xe(u,m)};return new V(l,d,async()=>{let u=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async h=>{let{columns:g,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(h),Object.values(h),"insert"),N=Object.fromEntries(g.map((q,O)=>[q,T[O]]));u.push(N);})),this.sqlType==="mssql")return this.executeMssqlMerge(u,t,e,o,r);let{sql:m,bindings:c}=this.astParser.parse([new z(new F(this.model.table),u,void 0,true),new pe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await J(m,c,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=[],u=t.map(P=>`select ${s.map(k=>(d.push(P[k]),`@${d.length}`)).join(", ")}`),m=s.map(l).join(", "),c=u.join(" union all "),p=e.map(P=>`target.${l(P)} = source.${l(P)}`).join(" and "),h=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)&&h?`when matched then update set ${h}`:"",C=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${O} when not matched then insert (${g}) values (${T}) output ${N};`;return await J(C,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(p=>p.columnName)),o=Object.keys(t).filter(p=>r.has(p)),n=o.map(p=>t[p]),{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:u,bindings:m}=this.astParser.parse([new Me(new F(this.model.table),s,a),new R(l,"and",false,"=",t[l])]);await J(u,m,this.sqlDataSource,this.sqlType,"affectedRows");let c=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!c)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return c}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 it(new F(this.model.table)),e]);await J(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new lt(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 he([a],this.model):null}return await he(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(u=>u[this.model.primaryKey]),l=a.map(u=>`'${u}'`).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((p,h)=>{let g=a[h];l[p]=g,n[p]??(n[p]=g);});let{sql:d,bindings:u}=this.astParser.parse([new z(new F(this.model.table),[l],e.returning)]);await J(d,u,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,h]of Object.entries(l))h!=null&&p!==o&&m.where(p,"=",h);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});c?(o&&c[o]&&(n[o]=c[o]),r.push(c)):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 np=(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 Mr=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 Cr=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 Rr=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 _r=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 Or=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 Ar=Rt;var ie=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Rr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Or.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Ar.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await Mr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Cr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await _r.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}}};ie.mysqlDriver=null,ie.pgDriver=null,ie.sqliteDriver=null,ie.mssqlDriver=null,ie.oracledbDriver=null,ie.mongodbDriver=null;var ff=async i=>(await ie.getDriver(i)).client,_t=async(i,t)=>{let e=await ff(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,u=t,m=u?.database;return new d.Database(m,u?.driverOptions?.mode??void 0,P=>{if(P)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,h=t,{options:g,...T}=h.driverOptions??{},N=new p.ConnectionPool({server:h.host??"localhost",port:h.port,database:h.database,user:h.username,password:h.password,...T,options:{trustServerCertificate:A.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});return await N.connect(),N;case "oracledb":let q=e,O=t,C=`${O.host}/${O.database}`;return await q.createPool({user:O.username,password:O.password,connectString:C,...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{await t(e),await e.commit();}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");M.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 M.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");M.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 M.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){M.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 M.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 ye,Re=class Re extends Ye{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:Gr(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,ye))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Le(this,ye)}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,ye)){M.warn("Connection already closed");return}await Le(this,ye).disconnect(),Kr(this,ye,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,ye)?.globalTransaction}async connect(){if(Le(Re,ye))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;})),Kr(Re,ye,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 u=zr(JSON.stringify(d)),m=u?`${e}:${u}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...d);return await this.cacheAdapter.set(m,p,l),p}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=zr(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(np(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new lt(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){M.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){if(typeof e=="function")try{await this.globalTransaction.nestedTransaction(e);return}catch(l){throw l}return await 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{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}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{M.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){M.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"){M.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await dr.makeDiff(this)).getSqlStatements();if(!o.length){M.info("No new changes detected between database schema and models metadata");return}if(M.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);M.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),M.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=>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]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s}}getModelOpenApiSchema(){return al(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 Jr(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 il(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 Kt(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(mt(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(),u=$e(s,d),m=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof m=="string"?m.toLowerCase()!=="no":typeof m=="boolean"?m:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=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:u,isNullable:c,defaultValue:p,length:h,precision:g,scale:T,withTimezone:N}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Qt(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(mt(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let u=d.Key_name,m=d.Non_unique===0,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.Column_name),l.set(u,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let u=d.index_name,m=!!d.is_unique,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.column_name),l.set(u,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,m=await this.rawQuery(`PRAGMA index_info(${d})`),p=this.extractRowsFromRawResult(m).map(h=>h.name);a.push({name:d,columns:p,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new vt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(mt(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let u=Number(d.id),m=l.get(u)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};m.columns.push(String(d.from)),m.referencedColumns.push(String(d.to)),l.set(u,m);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),u=d||`${l.referenced_table}_${l.column_name}`,m=a.get(u)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};m.columns.push(String(l.column_name)),m.referencedColumns.push(String(l.referenced_column)),a.set(u,m);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new kt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(mt(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 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
164
+ ORDER BY pk`,bindings:[]}}},Bm=new Ra;var _a=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},vm=new _a;var Oa=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 y(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 y(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 u of l)u==="("&&d++,u===")"&&d--;if(d>0)return e}return `as "${r}"`})}},Qm=new Oa;var Aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("sqlite",e.column),o=ae.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}},km=new Aa;var xa=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new y(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},Km=new xa;var Ia=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}}},Lm=new Ia;var Da=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new y(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}}},Wm=new Da;var Pa=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 y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new y(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new y(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 y(this.model).formatStringColumn("sqlite",t):t}},Fm=new Pa;var $a=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}}},jm=new $a;var Ea=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new y(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}}},Um=new Ea;var Ba=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}}},Vm=new Ba;var va=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}}},Jm=new va;var Hm={mssql:{alter_table:{add_column:ul,add_constraint:cl,add_primary_key:ml,alter_column_type:pl,alter_table:fl,drop_column:yl,drop_constraint:hl,drop_default:gl,drop_not_null:bl,drop_primary_key:Tl,rename_column:wl,rename_table:Nl,set_default:Sl,set_not_null:ql,set_table_options:Ml},column:{column_type:Cl},constraint:{after:Rl,constraint:_l},create_table:{create_table:Ol},delete:{delete:Al},distinct:{distinct:xl,distinct_on:Il},drop_table:{drop_table:Dl},extension:{create_extension:Pl},from:{from:$l},group_by:{group_by:El},having:{having:Bl},index_op:{create_index:vl,drop_index:Ql},insert:{insert:kl},join:{join:Kl},limit:{limit:Ll},lock:{lock:Wl},offset:{offset:Fl},on_duplicate:{on_duplicate:jl},order_by:{order_by:Ul},raw:{raw:Vl},schema:{foreign_key_info:Jl,index_info:Hl,primary_key_info:zl,table_info:Yl},select:{select:Gl,select_json:Zl},truncate:{truncate:Xl},union:{union:ed},update:{update:td},where:{where:rd,where_group:od,where_json:nd,where_subquery:sd},with:{with:id}},mysql:{alter_table:{add_column:ad,add_constraint:ld,add_primary_key:dd,alter_column_type:ud,alter_table:cd,drop_column:md,drop_constraint:pd,drop_default:fd,drop_not_null:yd,drop_primary_key:hd,rename_column:gd,rename_table:bd,set_default:Td,set_not_null:wd,set_table_options:Nd},column:{column_type:Sd},constraint:{after:qd,constraint:Md},create_table:{create_table:Cd},delete:{delete:Rd},distinct:{distinct:_d,distinct_on:Od},drop_table:{drop_table:Ad},extension:{create_extension:xd},from:{from:Id},group_by:{group_by:Dd},having:{having:Pd},index_op:{create_index:$d,drop_index:Ed},insert:{insert:Bd},join:{join:vd},limit:{limit:Qd},lock:{lock:kd},offset:{offset:Kd},on_duplicate:{on_duplicate:Ld},order_by:{order_by:Wd},raw:{raw:Fd},schema:{foreign_key_info:jd,index_info:Ud,primary_key_info:Vd,table_info:Jd},select:{select:Hd,select_json:zd},truncate:{truncate:Yd},union:{union:Gd},update:{update:Zd},where:{where:Xd,where_group:eu,where_json:tu,where_subquery:ru},with:{with:ou}},oracledb:{alter_table:{add_column:nu,add_constraint:su,add_primary_key:iu,alter_column_type:au,alter_table:lu,drop_column:du,drop_constraint:uu,drop_default:cu,drop_not_null:mu,drop_primary_key:pu,rename_column:fu,rename_table:yu,set_default:hu,set_not_null:gu,set_table_options:bu},column:{column_type:Tu},constraint:{after:wu,constraint:Nu},create_table:{create_table:Su},delete:{delete:qu},distinct:{distinct:Mu,distinct_on:Cu},drop_table:{drop_table:Ru},extension:{create_extension:_u},from:{from:Ou},group_by:{group_by:Au},having:{having:xu},index_op:{create_index:Iu,drop_index:Du},insert:{insert:Pu},join:{join:$u},limit:{limit:Eu},lock:{lock:Bu},offset:{offset:vu},on_duplicate:{on_duplicate:Qu},order_by:{order_by:ku},raw:{raw:Ku},schema:{foreign_key_info:Lu,index_info:Wu,primary_key_info:Fu,table_info:ju},select:{select:Uu,select_json:Vu},truncate:{truncate:Ju},union:{union:Hu},update:{update:zu},where:{where:Yu,where_group:Gu,where_json:Zu,where_subquery:Xu},with:{with:ec}},postgres:{alter_table:{add_column:tc,add_constraint:rc,add_primary_key:oc,alter_column_type:nc,alter_table:sc,drop_column:ic,drop_constraint:ac,drop_default:lc,drop_not_null:dc,drop_primary_key:uc,rename_column:cc,rename_table:mc,set_default:pc,set_not_null:fc,set_table_options:yc},column:{column_type:hc},constraint:{after:gc,constraint:bc},create_table:{create_table:Tc},delete:{delete:wc},distinct:{distinct:Nc,distinct_on:Sc},drop_table:{drop_table:qc},extension:{create_extension:Mc},from:{from:Cc},group_by:{group_by:Rc},having:{having:_c},index_op:{create_index:Oc,drop_index:Ac},insert:{insert:xc},join:{join:Ic},limit:{limit:Dc},lock:{lock:Pc},offset:{offset:$c},on_duplicate:{on_duplicate:Ec},order_by:{order_by:Bc},raw:{raw:vc},schema:{foreign_key_info:Qc,index_info:kc,primary_key_info:Kc,table_info:Lc},select:{select:Wc,select_json:Fc},truncate:{truncate:jc},union:{union:Uc},update:{update:Vc},where:{where:Jc,where_group:Hc,where_json:zc,where_subquery:Yc},with:{with:Gc}},sqlite:{alter_table:{add_column:Zc,add_constraint:Xc,alter_column_type:em,alter_table:tm,drop_column:rm,drop_constraint:om,drop_default:nm,drop_not_null:sm,drop_primary_key:im,rename_column:am,rename_table:lm,set_default:dm,set_not_null:um,set_table_options:cm},column:{column_type:mm},constraint:{after:pm,constraint:fm},create_table:{create_table:ym},delete:{delete:hm},distinct:{distinct:gm,distinct_on:bm},drop_table:{drop_table:Tm},extension:{create_extension:wm},from:{from:Nm},group_by:{group_by:Sm},having:{having:qm},index_op:{create_index:Mm,drop_index:Cm},insert:{insert:Rm},join:{join:_m},limit:{limit:Om},lock:{lock:Am},offset:{offset:xm},on_duplicate:{on_duplicate:Im},order_by:{order_by:Dm},raw:{raw:Pm},schema:{foreign_key_info:$m,index_info:Em,primary_key_info:Bm,table_info:vm},select:{select:Qm,select_json:km},truncate:{truncate:Km},union:{union:Lm},update:{update:Wm},where:{where:Fm,where_group:jm,where_json:Um,where_subquery:Vm},with:{with:Jm}}};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(C=>!!C&&C.folder==="distinctOn"),n=!o&&t.find(C=>!!C&&C.folder==="distinct"),s=this.dbType==="mssql"?t.find(C=>!!C&&C.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(C=>C!==null&&C.folder!=="distinct"&&C.folder!=="distinctOn"),d=l.some(C=>C.folder==="offset"),u=l.some(C=>C.folder==="order_by"),m=l.find(C=>C.folder==="limit"),c=l.find(C=>C.folder==="offset"),p=this.dbType==="mssql"&&m&&!d&&!u,h=this.dbType==="mssql"&&!p&&(m||c),g=this.dbType==="oracledb"&&(m||c),T=[],N=[],q=null;p&&m&&N.push(m.limit);for(let C=0;C<l.length;C++){let I=l[C];if(p&&I.folder==="limit"||h&&(I.folder==="limit"||I.folder==="offset")||g&&(I.folder==="limit"||I.folder==="offset"))continue;I.currParamIndex=e+N.length;let P=Hm[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 _=P.toSql(I);if(!_.sql||!_.sql.trim().length)continue;let k=l[C+1],$=!k||k.keyword!==I.keyword?"":k.chainsWith;if(I.folder==="lock"||I.folder==="on_duplicate"||I.folder==="schema"){T.push(`${_.sql}${$}`),N.push(..._.bindings),q=I.keyword;continue}if(q!==I.keyword||I.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let G=I.keyword;if(I.folder==="with"&&this.dbType!=="mssql"){let X=C,Ne=false;for(;X<l.length&&l[X].keyword===I.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=p?`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}${$}`);}q=I.keyword;}else T.push(`${_.sql}${$}`);N.push(..._.bindings);}if(h){u||T.push("order by (select null)");let C=c?.offset??0;N.push(C);let P=`offset @${e+N.length-1} rows`;if(m){N.push(m.limit);let _=e+N.length-1;P+=` fetch next @${_} rows only`;}T.push(P);}if(g){u||T.push("order by null");let C=c?.offset??0;N.push(C);let P=`offset :${e+N.length-1} rows`;if(m){N.push(m.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 vt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Qt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Kt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Lt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ue=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var tt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Wt=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 ge=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 Ft=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=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 jt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var rt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Ut=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 Vt=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 Jt=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 Ht=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 zt=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 Yt=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 Gt=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 Zt=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 ot=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 Xt=Symbol("columns"),nt=Symbol("primaryKey"),ce=Symbol("relations"),er=Symbol("indexes"),tr=Symbol("uniques"),Ie=i=>`${of__default.default.singular(i)}_id`,rr=(i,t)=>`idx_${i}_${t}`,le=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,De=(i,t)=>`pk_${i}_${t}`;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 st=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 or=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var nr=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 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??le(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new j("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||le(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 or(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 nr(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 sr=class extends Pe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new D(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(m=>m.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(m=>{let c=m;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new Lt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(m=>{let c=m;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new ue(m));});}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(p=>p.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(p=>p.constraintType==="null"),u=o.getNodes().find(p=>p.constraintType==="not_null")||l,m=o.getNodes().find(p=>p.constraintType==="default"),c={};u&&(c.nullable=u.constraintType==="null"),m&&(m.defaultValue===void 0||m.defaultValue===null?c.dropDefault=true:c.default=m.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new Wt(S(a),s,c)),u&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(u.constraintType==="not_null"?this.nodes.push(new Jt(S(a))):u.constraintType==="null"&&this.nodes.push(new jt(S(a)))),m&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(m.defaultValue===void 0||m.defaultValue===null?this.nodes.push(new pt(S(a))):this.nodes.push(new Vt(S(a),m.defaultValue))),o.getNodes().forEach(p=>{let h=p;switch(h.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:h.constraintName});break;case "foreign_key":this.foreignKey(S(a),h.references?.table??"",S(h.references?.columns?.[0]??""),{constraintName:h.constraintName,onDelete:h.onDelete,onUpdate:h.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ft(t));}renameColumn(t,e){this.nodes.push(new Ut(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 tt([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 ue(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 ue(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 ue(new j("unique",{columns:[t],constraintName:e?.constraintName??le(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 be(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??le(this.table,t);this.nodes.push(new be(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 be(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 rt(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 me=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 D(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!zm__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=zm__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 Ht(t,n,o.getNamedConstraints(),r?.ifNotExists,a),d=s.parse([l]).sql,u=d.startsWith("create table")?d:`create table ${d}`;this.rawQuery(u),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new sr(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 ge(t,s),u=n.parse([d]).sql;if(!u||!u.trim())return;let m=u.startsWith("alter table")?u:`alter table ${u}`;this.rawQuery(m),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 zt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new ge(t,[new et(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new ot(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||rr(t,e.join("_")),n=new Gt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Zt(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new tt(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??le(t,o.join("_")),s=new j("unique",{columns:o,constraintName:n}),a=new ge(t,[new ue(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 be(o),s=new ge(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)?le(t,e.join("_")):le(t,e),n=r?.constraintName??o,s=new be(n),a=new ge(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new rt,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 ge(t,[new ue(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new be(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 ge(t,[new ue(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){this.dropConstraint(t,e);}createExtension(t,e=true){let r=new Yt(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 ir,Gm,yt=class{constructor(t,e){Dt(this,ir);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new me(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=Ya(this,ir,Gm).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(`;
165
+ `)}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"}};ir=new WeakSet,Gm=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 ar=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 u of d)u.type==="belongsTo"&&u.model().table===n.table&&a.push(`fk.${l.table}.${u.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(u=>u.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let u=l.getRelations();for(let m of u)m.columnName===d.columnName&&a.push(`fk.${n.table}.${m.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(u=>u.table===a&&u.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){return this.sql.getDbType()==="sqlite"?[]:t.relation.name?this.sql.schema().alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}).toQueries():[]}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 lr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new ar(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 me(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 u=a||De(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});}).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(u=>u.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]});}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.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 me(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 c=t.relation.model(),p=c.primaryKey,g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=L(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),h=p.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",T=p.find(N=>N.columnName===g);if(T)n=T.databaseName;else {let N=c?.databaseCaseConvention||"preserve";n=L(n||g,N);}}}else {let p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=L(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=L(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=L(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=S(c),h=a.find(g=>g.columnName===p);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=L(p,g);}}let u=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let p=o||Z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:u,onUpdate:m});}).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 af(i){return i.replace(/\s+/g," ").trim()}function lf(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function $e(i,t){let e=af(t.toLowerCase()),r=lf(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 dr=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:[],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 m of n.indexes)o.indexes.map(c=>c.name).includes(m.name)||e.data.indexesToAdd.push({table:r.table,index:m.name});let u=r.getUniques?.()||[];for(let m of u)e.data.uniquesToAdd.push({table:r.table,name:m.name||"mandatory",columns:m.columns});for(let m of n.relations){if(m.type!=="belongsTo")continue;let c=S(m.constraintName);o.foreignKeys.find(h=>h.name===c)||e.data.relationsToAdd.push({table:r.table,relation:m,onDelete:m.onDelete,onUpdate:m.onUpdate});}return}for(let u of n.columns)o.columns.some(c=>c.name===u.databaseName||c.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(c=>c.databaseName===u.name||c.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(c=>c.name===u.name&&c.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(c=>c.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(c=>c.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}for(let u of n.columns){let m=o.columns.find(h=>h.name===u.databaseName||h.name===u.columnName);if(!m)continue;let c=!e.areColumnsEqual(m,u,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:u});(c||p)&&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 p=S(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:S(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?S(u.constraintName):Z(p,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(p=>p.name===m))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,u,p))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let l=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let m=S(u.foreignKey)||u.columnName,p=r.getColumns().find(h=>h.columnName===m)?.databaseName||m;return S(u.constraintName)||Z(r.table,p,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&l.has(u.name))continue;n.relations.find(c=>c.type!=="belongsTo"&&c.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,c,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(c=>e.relationMatchesDbRelation(r,u,c));m&&!e.areRelationsEqual(m,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let d=r.primaryKey;if(d&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[d]}),o.primaryKey&&!d&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),d&&o.primaryKey){let u=r.getColumns().find(m=>m.columnName===d);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:d});}})),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 lr(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,u=t.isNullable;o=o&&d===u;}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",m=d.getColumns().find(h=>h.columnName===u),c=d.table,p=m?.databaseName||u;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}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(),u=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,m=l.find(g=>g.columnName===u);m&&(u=m.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}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 u=String(t.dbColumns.defaultValue),m=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,u),p=this.normalizeDefaultValue(e,o||r,m);return c!==p?"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);return n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o)?"current_timestamp":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",u=s.getColumns().find($=>$.columnName===l),m=a.getColumns().find($=>$.columnName===d);if(!u||!m)continue;let c=S(o.manyToManyOptions.leftForeignKey)||l,p=S(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(u,c),T=this.clonePkAsColumn(m,p),N=h.columns.find($=>$.name===c),q=h.columns.find($=>$.name===p),O=N?this.areColumnsEqual(N,g,h.indexes):false,C=q?this.areColumnsEqual(q,T,h.indexes):false;for(let $ of h.foreignKeys){let G=$.referencedTable===s.table,X=$.referencedTable===a.table;if(!G&&!X)continue;let Ne=G?c:p,_e=$.columns[0];_e&&_e!==Ne&&(this.data.relationsToDrop.push({table:n,relation:$}),_e!==c&&_e!==p&&this.data.columnsToDrop.push({table:n,column:_e}));}let I={};O||(I[g.databaseName]=g),C||(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,c,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),k=h.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),Ke=h.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===p);if(!k){let $=h.foreignKeys.find(G=>G.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(P);}if(!Ke){let $=h.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,u=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=S(a.constraintName)||Z(o.table,u,a.model().table);s.add(m);}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,u=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let T=g.primaryKey||"id";u=g.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let T=m.has(g.columns[0]),N=g.referencedTable===d,q=g.referencedColumns[0]===u;return T&&N&&q}),p=S(o.relation.constraintName)||Z(o.table,l,d),h=e.get(o.table)||new Set;if(c||p&&h.has(p))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),q=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,C=await this.sql.getTableSchema(g),I=C.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),P=C.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===N&&_.referencedTable===o.relation.model().table);if(q&&I||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 m=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.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 it=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 pe=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 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 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 ne=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 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 df=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,uf=/^\d{4}-\d{2}-\d{2}$/,Qa=i=>typeof i!="string"?i:df.test(i)?new Date(i.replace(" ","T")+"Z"):uf.test(i)?new Date(i+"T00:00:00Z"):i,cf=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);}}),Xm=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await cf(r):t[e]=r;}return t};var ur=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);});}},ep=(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,u)=>{n.run(i,t,function(m){m&&u(m),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,u)=>{n.all(i,t,(m,c)=>{m&&u(m),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.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((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([h]);return}let g=h?.[a]||this.lastID;if(!g)return c(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[g],(N,q)=>{if(N)return c(N);m([q]);});});});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((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(d);});});let u=[];return new Promise(async(m,c)=>{try{let p=d.map(async h=>{let g=new y(s),{columns:T,values:N}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),q=Object.fromEntries(T.map((P,_)=>[P,N[_]])),O=new b(s,e.getDbType()),{sql:C,bindings:I}=O.parse([new H(new F(s.table),[q])]);return new Promise((P,_)=>{n.run(C,I,function(k){if(k)return _(k);let Ke=h[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);});});})});u=await Promise.all(p),m(u);}catch(p){c(p);}})}return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.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,u=i.replace(/\?/g,()=>`$${++d}`),m=await ht(()=>l.query(u,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?m.rows:o==="raw"?m:m.rowCount;case "sqlite":let c=await ht(()=>ep(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(c)?c:[c]:c;case "mssql":let p=e.getPool(),h=e.sqlConnection?e.sqlConnection.request():p.request();t.forEach((I,P)=>{h.input(`p${P}`,I);});let g=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${g++}`),N=await ht(()=>h.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?N.rowsAffected[0]:o==="raw"?N:N.recordset;case "oracledb":let q=4002,O=null,C=!!e.sqlConnection;try{O=e.sqlConnection?e.sqlConnection:await e.getConnection();let I=t.map(Qa),P=0,_=i.replace(/\?/g,()=>`:${++P}`),k=await ht(()=>O.execute(_,I,{outFormat:q,autoCommit:!C}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?k.rowsAffected:o==="raw"?k:await Promise.all(k.rows?.map(async $=>{let G=await Xm($),X={};for(let Ne in G)X[Ne.toLowerCase()]=G[Ne];return X})??[])}finally{O&&!C&&await O.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},mr=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}),u=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,h=()=>{try{a.release();}catch{}};return u.on("data",g=>{if(o.onData){m++,Promise.resolve(o.onData(l,g)).then(()=>{m--,c&&m===0&&!p&&(h(),l.end());}).catch(T=>{p=true,h(),l.destroy(T);});return}l.write(g);}),u.on("end",()=>{c=true,m===0&&!p&&(h(),l.end());}),u.on("error",g=>{p=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),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}),u=0,m=i.replace(/\?/g,()=>`$${++u}`),c=new l.default(m,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(c),h=0,g=false,T=false,N=q=>{try{a.release(q);}catch{}};return p.on("data",q=>{if(o.onData){h++,Promise.resolve(o.onData(d,q)).then(()=>{h--,g&&h===0&&!T&&(N(),d.end());}).catch(O=>{T=true,N(O),d.destroy(O);});return}d.write(q);}),p.on("end",()=>{g=true,h===0&&!T&&(N(),d.end());}),p.on("error",q=>{T=true,N(q),d.destroy(q);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new ur(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((h,g)=>{l.input(`p${g}`,h);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),m=0,c=false,p=false;return l.on("row",h=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,h)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(g=>{p=true,a.destroy(g);});return}a.write(h);}}),l.on("error",h=>{p=true,a.destroy(h);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(u),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,u=0,m=i.replace(/\?/g,()=>`:${++u}`),c=t.map(Qa),p=a.queryStream(m,c,{outFormat:d}),h=0,g=false,T=false,N=async()=>{try{await a.close();}catch{}};return p.on("data",q=>{if(T)return;let O={};for(let C in q)O[C.toLowerCase()]=q[C];if(o.onData){h++,Promise.resolve(o.onData(l,O)).then(()=>{h--,g&&h===0&&!T&&(N(),l.end());}).catch(C=>{T=true,N(),l.destroy(C);});return}l.write(O);}),p.on("end",()=>{g=true,h===0&&!T&&(N(),l.end());}),p.on("error",q=>{T=true,N(),l.destroy(q);}),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++,ll(`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=pr(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 fr(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 tp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var at=i=>typeof i=="number"?i:parseFloat(i);var de=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 yr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var hr=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 se=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 gr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var br=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 Tr=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"&&M.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new gr(t),this}offset(t){return typeof t!="number"&&M.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new br(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 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 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 R(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new R(t,"or",true,"=",e??[],true)),this}};var wr=class extends Tr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(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 u=new Je(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Nr=class extends wr{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 de(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=L(o,this.model.databaseCaseConvention);this.selectNodes.push(new de(n));}),this}selectRaw(e){return this.selectNodes.push(new de(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":L(r,this.model.databaseCaseConvention);return this.selectNodes.push(new de(`${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 yr,this}distinctOn(...e){return this.distinctOnNode=new hr(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 Sr=class extends Nr{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}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 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 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 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 qr=class extends Sr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"or",false,"raw",e)),this}};var v=class i extends qr{constructor(e,r=fe.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 y(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 de(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new de(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 mr(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:tp(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?at(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?at(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?at(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&M.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:fr(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 st("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 st("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 st("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((p,h)=>[p,a[h]]));this.insertNode=new H(this.fromNode,[l],r,n);let{sql:d,bindings:u}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await V(d,u,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}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 m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((h,g)=>[h,p[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"),u=await V(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return u})}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 pe(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"),u=Object.fromEntries(l.map((g,T)=>[g,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([u],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new H(new F(this.model.table),[u],void 0,true),new pe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),h=await V(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}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 pe(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 c=>{let{columns:p,values:h}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),g=Object.fromEntries(p.map((T,N)=>[T,h[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 pe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),u=await this.getSqlDataSource("write"),m=await V(l,d,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}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),u=[],m=e.map(k=>`select ${a.map($=>(u.push(k[$]),`@${u.length}`)).join(", ")}`),c=a.map(d).join(", "),p=m.join(" union all "),h=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(", "),q=n.returning&&n.returning.length?n.returning.map(k=>`inserted.${d(k)}`).join(", "):a.map(k=>`inserted.${d(k)}`).join(", "),C=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",I=`merge into ${l} as target using (${p}) as source (${c}) on ${h} ${C} when not matched then insert (${T}) values (${N}) output ${q};`,P=await this.getSqlDataSource("write"),_=await V(I,u,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 ot(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 it(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 de("*")]);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 de("*")]),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 lt=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 he(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 mr(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),u=await he([d],this.model,this.modelSelectedColumns);u&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([u]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}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:fr(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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereNotExists(u),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 u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereNotExists(u),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(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let h=n.get(String(p));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let h=s.get(String(p));c[e.columnName]=h||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(c=>{let p=c[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=a.get(String(p))||[];c[e.columnName]=h;});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,u=l.leftForeignKey,m=this.modelColumnsMap.get(u)||this.modelColumnsDatabaseNames.get(u)||L(u,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let h=String(p);d.has(h)||d.set(h,[]),delete c[m],d.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=d.get(String(p))||[];c[e.columnName]=h;});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}`,u=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(d,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${u}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>Vr(_,d,e.model.table));return m.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let N=Se__default.default.randomBytes(6).toString("hex"),q=`${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 C=`${Se__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,I=e.with(q,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,C]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${O}) as rn_${N}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));h&&I.whereRaw(`rn_${N} <= ${h+(g||0)}`),g&&I.whereRaw(`rn_${N} > ${g}`);let P=T.map(_=>Vr(_,q,e.model.table));return I.select(...P).select([`${q}.${C}`,p.leftForeignKey]).from(q);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 y(r.model),a=new y(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}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${u}`),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}`),u=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${u}`),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(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let m=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).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 rp(i){let t=i.name,e=L(t,"snake");return of__default.default(e)}function op(){return {}}var wt=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 y(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"),u={};l.forEach((N,q)=>{let O=d[q];u[N]=O,t[N]??(t[N]=O);});let m=!e.returning||e.returning.length===0,{sql:c,bindings:p}=this.astParser.parse([new H(new F(this.model.table),[u],e.returning,m)]),h=await V(c,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(h,[t],"one",e.returning);let g=h[0];return g?(await this.model.afterFetch?.([g]),await he([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"),q={};T.forEach((O,C)=>{let I=N[C];q[O]=I,g[O]??(g[O]=I);}),l.push(q);}let d=!e.returning||e.returning.length===0,{sql:u,bindings:m}=this.astParser.parse([new H(new F(this.model.table),l,e.returning,d)]),c=await V(u,m,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(c,t,"many",e.returning)||[];let p=c;return p.length?(await this.model.afterFetch?.(p),await he(p,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(u=>Object.fromEntries(Object.keys(u).map(m=>[m,u[m]]))),s=new H(new F(this.model.table),n,void 0,true),a=new pe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let u=this.astParser.parse([s,a]);return {sql:xe(this.sqlDataSource,u.sql),bindings:u.bindings}},d=()=>{let{sql:u,bindings:m}=l();return Xe(u,m)};return new U(l,d,async()=>{let u=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async h=>{let{columns:g,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(h),Object.values(h),"insert"),N=Object.fromEntries(g.map((q,O)=>[q,T[O]]));u.push(N);})),this.sqlType==="mssql")return this.executeMssqlMerge(u,t,e,o,r);let{sql:m,bindings:c}=this.astParser.parse([new H(new F(this.model.table),u,void 0,true),new pe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await V(m,c,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=[],u=t.map(P=>`select ${s.map(k=>(d.push(P[k]),`@${d.length}`)).join(", ")}`),m=s.map(l).join(", "),c=u.join(" union all "),p=e.map(P=>`target.${l(P)} = source.${l(P)}`).join(" and "),h=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)&&h?`when matched then update set ${h}`:"",C=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${O} when not matched then insert (${g}) values (${T}) output ${N};`;return await V(C,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(p=>p.columnName)),o=Object.keys(t).filter(p=>r.has(p)),n=o.map(p=>t[p]),{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:u,bindings:m}=this.astParser.parse([new Me(new F(this.model.table),s,a),new R(l,"and",false,"=",t[l])]);await V(u,m,this.sqlDataSource,this.sqlType,"affectedRows");let c=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!c)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return c}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 it(new F(this.model.table)),e]);await V(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new lt(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 he([a],this.model):null}return await he(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(u=>u[this.model.primaryKey]),l=a.map(u=>`'${u}'`).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((p,h)=>{let g=a[h];l[p]=g,n[p]??(n[p]=g);});let{sql:d,bindings:u}=this.astParser.parse([new H(new F(this.model.table),[l],e.returning)]);await V(d,u,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,h]of Object.entries(l))h!=null&&p!==o&&m.where(p,"=",h);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});c?(o&&c[o]&&(n[o]=c[o]),r.push(c)):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 np=(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 Mr=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 Cr=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 Rr=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 _r=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 Or=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 Ar=Rt;var ie=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Rr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Or.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Ar.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await Mr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Cr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await _r.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}}};ie.mysqlDriver=null,ie.pgDriver=null,ie.sqliteDriver=null,ie.mssqlDriver=null,ie.oracledbDriver=null,ie.mongodbDriver=null;var ff=async i=>(await ie.getDriver(i)).client,_t=async(i,t)=>{let e=await ff(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,u=t,m=u?.database;return new d.Database(m,u?.driverOptions?.mode??void 0,P=>{if(P)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,h=t,{options:g,...T}=h.driverOptions??{},N=new p.ConnectionPool({server:h.host??"localhost",port:h.port,database:h.database,user:h.username,password:h.password,...T,options:{trustServerCertificate:A.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});return await N.connect(),N;case "oracledb":let q=e,O=t,C=`${O.host}/${O.database}`;return await q.createPool({user:O.username,password:O.password,connectString:C,...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{await t(e),await e.commit();}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");M.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 M.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");M.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 M.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){M.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 M.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 ye,Re=class Re extends Ye{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:Gr(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,ye))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Le(this,ye)}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,ye)){M.warn("Connection already closed");return}await Le(this,ye).disconnect(),Kr(this,ye,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,ye)?.globalTransaction}async connect(){if(Le(Re,ye))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;})),Kr(Re,ye,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 u=zr(JSON.stringify(d)),m=u?`${e}:${u}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...d);return await this.cacheAdapter.set(m,p,l),p}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=zr(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(np(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new lt(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){M.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){if(typeof e=="function")try{await this.globalTransaction.nestedTransaction(e);return}catch(l){throw l}return await 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{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}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{M.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){M.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"){M.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await dr.makeDiff(this)).getSqlStatements();if(!o.length){M.info("No new changes detected between database schema and models metadata");return}if(M.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);M.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),M.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 D(e)}async getTableSchema(e){let[r,o,n,s]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s}}getModelOpenApiSchema(){return al(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 Jr(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 il(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 Kt(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(mt(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(),u=$e(s,d),m=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof m=="string"?m.toLowerCase()!=="no":typeof m=="boolean"?m:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=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:u,isNullable:c,defaultValue:p,length:h,precision:g,scale:T,withTimezone:N}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Qt(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(mt(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let u=d.Key_name,m=d.Non_unique===0,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.Column_name),l.set(u,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let u=d.index_name,m=!!d.is_unique,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.column_name),l.set(u,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,m=await this.rawQuery(`PRAGMA index_info(${d})`),p=this.extractRowsFromRawResult(m).map(h=>h.name);a.push({name:d,columns:p,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new vt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(mt(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let u=Number(d.id),m=l.get(u)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};m.columns.push(String(d.from)),m.referencedColumns.push(String(d.to)),l.set(u,m);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),u=d||`${l.referenced_table}_${l.column_name}`,m=a.get(u)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};m.columns.push(String(l.column_name)),m.referencedColumns.push(String(l.referenced_column)),a.set(u,m);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new kt(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(mt(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 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
166
166
  v_result NUMBER;
167
167
  BEGIN
168
168
  v_result := DBMS_LOCK.REQUEST(
@@ -185,7 +185,7 @@ ORDER BY ordinal_position`,bindings:[]}}},Lc=new Ii;var Di=class{toSql(t){let e=
185
185
  ELSE
186
186
  :result := 0;
187
187
  END IF;
188
- END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return M.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return M.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return M.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;}};ye=new WeakMap,Dt(Re,ye,null);var fe=Re;var sp=["postgres","cockroachdb"];var At=class At extends Oe{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:rp(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return cp(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=pr(s).find(h=>h.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),u=L(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),m=r.map((h,g)=>({[d]:e[s.primaryKey],[u]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends At{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(m);}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(c=>{let p=new Set(Object.keys(c));return t.every(h=>p.has(h))}))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(sp.includes(d))return await he(l,o,r.returning);let u=n.query();r.returning?.length&&u.select(...r.returning);let m=new Map;return t.forEach(c=>{e.forEach(p=>{m.set(c,[...m.get(c)||[],p[c]]);});}),u.where(c=>{t.forEach(p=>{c.orWhereIn(p,m.get(p)||[]);});}),u.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 Bt(this)}static getRelations(){return up(this)}static getIndexes(){return mp(this)}static getUniques(){return pp(this)}static column(t,...e){x(...e)(this.prototype,t);}static dateColumn(t,...e){x.date(...e)(this.prototype,t);}static datetimeColumn(t,...e){x.datetime(...e)(this.prototype,t);}static timestampColumn(t,...e){x.timestamp(...e)(this.prototype,t);}static timeColumn(t,...e){x.time(...e)(this.prototype,t);}static booleanColumn(t,...e){x.boolean(...e)(this.prototype,t);}static jsonColumn(t,...e){x.json(...e)(this.prototype,t);}static uuidColumn(t,...e){x.uuid(...e)(this.prototype,t);}static ulidColumn(t,...e){x.ulid(...e)(this.prototype,t);}static integerColumn(t,...e){x.integer(...e)(this.prototype,t);}static floatColumn(t,...e){x.float(...e)(this.prototype,t);}static incrementColumn(t,...e){x.increment(...e)(this.prototype,t);}static bigIncrementColumn(t,...e){x.bigIncrement(...e)(this.prototype,t);}static encryptionSymmetricColumn(t,...e){x.encryption.symmetric(...e)(this.prototype,t);}static encryptionAsymmetricColumn(t,...e){x.encryption.asymmetric(...e)(this.prototype,t);}static hasOne(t,...e){ap(...e)(this.prototype,t);}static hasMany(t,...e){lp(...e)(this.prototype,t);}static belongsTo(t,...e){ip(...e)(this.prototype,t);}static manyToMany(t,...e){dp(...e)(this.prototype,t);}static establishConnection(){let t=fe.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 j=At;var Te=class{constructor(t,e){this.model=j;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var xr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Ir=class extends Te{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Dr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Pr=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 sQ(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(er,e.prototype)||[];o.push({columns:r,name:t??rr(e.table,r.join("_"))}),K.defineMetadata(er,o,e.prototype);}}function iQ(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(tr,e.prototype)||[];o.push({columns:r,name:t??le(e.table,r.join("_"))}),K.defineMetadata(tr,o,e.prototype);}}function aQ(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 x(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(K.getMetadata(nt,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");K.defineMetadata(nt,r,e),K.defineMetadata(nt,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(Xt,e)||[];a.push(s),K.defineMetadata(Xt,a,e);}}x.primary=gf;x.date=Pf;x.datetime=$f;x.timestamp=Ef;x.time=Bf;x.boolean=Df;x.json=vf;x.uuid=Sf;x.ulid=qf;x.integer=Tf;x.bigint=Rf;x.float=bf;x.decimal=_f;x.increment=wf;x.bigIncrement=Nf;x.string=Mf;x.text=Cf;x.binary=Of;x.enum=Af;x.encryption={symmetric:xf,asymmetric:If};function gf(i={}){return x({...i,primaryKey:true})}function bf(i={}){return x({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function Tf(i={}){return x({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 wf(i={}){return x({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 Nf(i={}){return x({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 Sf(i={}){return x({type:"uuid",...i,prepare:t=>t||Se__default.default.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function qf(i={}){return x({type:"ulid",...i,prepare:t=>t||rl(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Mf(i={}){return x({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Cf(i={}){return x({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Rf(i={}){return x({type:"bigint",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"||typeof t=="bigint"?t:BigInt(t)},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function _f(i={}){return x({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 Of(i={}){return x({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Af(i,t={}){return x({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function xf(i){return x({...i,prepare:t=>t&&Za(i.key,t),serialize:t=>t&&Xa(i.key,t)})}function If(i){return x({...i,prepare:t=>t&&el(i.publicKey,t),serialize:t=>t&&tl(i.privateKey,t)})}function Df(i={}){return x({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t,openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function Pf(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:ut(d,void 0,t)};return x({type:"date",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function $f(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"ISO",t):typeof d=="string"?d:oe(d,"ISO",t):r?oe(new Date,"ISO",t):null,l=d=>{if(d!==void 0)return d===null?null:ut(d,void 0,t)};return x({type:"datetime",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function Ef(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"TIMESTAMP",t):typeof d=="string"?d:oe(d,"TIMESTAMP",t):r?oe(new Date,"TIMESTAMP",t):null,l=d=>{if(d!==void 0)return d===null?null:ut(d,void 0,t)};return x({type:"timestamp",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function Bf(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:ut(d,void 0,t)};return x({type:"time",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function vf(i={}){return x({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 Bt(i){try{return K.getMetadata(Xt,i.prototype)||[]}catch{return []}}function ip(i,t,e){return((r,o)=>{let n=()=>Ie(i().table),s=()=>{let d=r.constructor.table,u=t||n();return Z(d,u,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(ce,r)||[];l.push(a),K.defineMetadata(ce,l,r);})}function ap(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(ce,e)||[];s.push(n),K.defineMetadata(ce,s,e);})}function lp(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(ce,e)||[];s.push(n),K.defineMetadata(ce,s,e);})}function dp(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,u=o.constructor.table,m=()=>Ie(u),c=()=>Ie(i().table),p=()=>Z(S(d),s?String(s):m()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??p,foreignKey:s?String(s):m,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:u,throughModel:d,leftForeignKey:s?String(s):m,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=K.getMetadata(ce,o)||[];g.push(h),K.defineMetadata(ce,g,o);})}function up(i){return K.getMetadata(ce,i.prototype)||[]}function pr(i){return (K.getMetadata(ce,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 xr(l,n,a);case "hasOne":return new Dr(l,n,a);case "hasMany":return new Ir(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 Pr(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 cp(i){return K.getMetadata(nt,i)||K.getMetadata(nt,i.prototype)}function mp(i){return K.getMetadata(er,i.prototype)||[]}function pp(i){return K.getMetadata(tr,i.prototype)||[]}var Ka=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:["*"]})}},Qf=(i,t)=>new Ka(i,t);function kf(i,t){let e=s=>typeof s=="function",r=e(i)?i:j,o=e(i)?t:i;class n extends r{}return j.column("id",{type:"bigint",openApi:{type:"number",required:true},...o,primaryKey:true}),n}function Kf(i,t){let e=s=>typeof s=="function",r=e(i)?i:j,o=e(i)?t:i;class n extends r{}return j.column("id",{type:"increment",openApi:{type:"number",required:true},...o,primaryKey:true}),n}function fp(i,t){let e=s=>typeof s=="function",r=e(i)?i:j,o=e(i)?t:i;class n extends r{}return j.column("id",{type:"ulid",openApi:{type:"string",format:"ulid",required:true},...o,primaryKey:true}),n}var Lf=fp;function yp(i,t){let e=s=>typeof s=="function",r=e(i)?i:j,o=e(i)?t:i;class n extends r{}return j.column("id",{type:"uuid",openApi:{type:"string",format:"uuid",required:true},...o,primaryKey:true}),n}var Wf=yp;function Ff(i,t){let e=s=>typeof s=="function",r=e(i)?i:j,o=e(i)?t:i;class n extends r{}return j.datetimeColumn("createdAt",{type:"datetime",autoCreate:true,openApi:{type:"string",format:"date-time",required:true},...o?.createdAt}),j.datetimeColumn("updatedAt",{autoUpdate:true,openApi:{type:"string",format:"date-time",required:true},...o?.updatedAt}),j.datetimeColumn("deletedAt",{nullable:true,openApi:{type:"string",format:"date-time",required:false},...o?.deletedAt}),n}var hp=i=>{let t=()=>{for(let[r,o]of Object.entries(i))j.column(r,o);};function e(r){var s;let o=r??j;return s=class extends o{},t(),s}return e},jf=hp;var gp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw M.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 M.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:Vf}=of__default.default;function bp(i){let t=i.name,e=L(t,"snake");return Vf(e)}function Tp(){return {$annotations:{}}}var dt=class extends Oe{static get collection(){return this._collection||bp(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){Wr()(this.prototype,t);}static async afterFetch(t){return t}};za([Wr()],dt.prototype,"id");async function ve(i,t,e){if(!t)return null;let r=Tp(),o=Ga(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 $r(i,t,e){return (await Promise.all(t.map(async o=>await ve(i,o,e)))).filter(o=>o!==null)}var Er=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 $r(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 $r(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 $r(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 M.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 M.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 M.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 M.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 M.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 M.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 Br=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=dt,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 Er(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 Qe=class Qe extends Ye{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 ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,Qe.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 ie.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 Qe(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!Qe.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Qe.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 Qe(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 Br(e,r,o,this.logs)}};Qe.instance=null;var xt=Qe;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");M.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 La=Y;var Wa=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 me(this.dbType);}};async function Gf(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 Zf(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 zm__default.default.promises.unlink(r).catch(()=>{});}}async function Sp(i,t){let e=It__default.default.isAbsolute(i)?i:It__default.default.resolve(process.cwd(),i);return e.endsWith(".ts")?Zf(e):Gf(e)}var Fa=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
188
+ END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return M.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return M.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return M.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;}};ye=new WeakMap,Dt(Re,ye,null);var fe=Re;var sp=["postgres","cockroachdb"];var At=class At extends Oe{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:rp(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return cp(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=pr(s).find(h=>h.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),u=L(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),m=r.map((h,g)=>({[d]:e[s.primaryKey],[u]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends At{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(m);}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(c=>{let p=new Set(Object.keys(c));return t.every(h=>p.has(h))}))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(sp.includes(d))return await he(l,o,r.returning);let u=n.query();r.returning?.length&&u.select(...r.returning);let m=new Map;return t.forEach(c=>{e.forEach(p=>{m.set(c,[...m.get(c)||[],p[c]]);});}),u.where(c=>{t.forEach(p=>{c.orWhereIn(p,m.get(p)||[]);});}),u.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 Bt(this)}static getRelations(){return up(this)}static getIndexes(){return mp(this)}static getUniques(){return pp(this)}static column(t,...e){x(...e)(this.prototype,t);}static dateColumn(t,...e){x.date(...e)(this.prototype,t);}static datetimeColumn(t,...e){x.datetime(...e)(this.prototype,t);}static timestampColumn(t,...e){x.timestamp(...e)(this.prototype,t);}static timeColumn(t,...e){x.time(...e)(this.prototype,t);}static booleanColumn(t,...e){x.boolean(...e)(this.prototype,t);}static jsonColumn(t,...e){x.json(...e)(this.prototype,t);}static uuidColumn(t,...e){x.uuid(...e)(this.prototype,t);}static ulidColumn(t,...e){x.ulid(...e)(this.prototype,t);}static integerColumn(t,...e){x.integer(...e)(this.prototype,t);}static floatColumn(t,...e){x.float(...e)(this.prototype,t);}static incrementColumn(t,...e){x.increment(...e)(this.prototype,t);}static bigIncrementColumn(t,...e){x.bigIncrement(...e)(this.prototype,t);}static encryptionSymmetricColumn(t,...e){x.encryption.symmetric(...e)(this.prototype,t);}static encryptionAsymmetricColumn(t,...e){x.encryption.asymmetric(...e)(this.prototype,t);}static hasOne(t,...e){ap(...e)(this.prototype,t);}static hasMany(t,...e){lp(...e)(this.prototype,t);}static belongsTo(t,...e){ip(...e)(this.prototype,t);}static manyToMany(t,...e){dp(...e)(this.prototype,t);}static establishConnection(){let t=fe.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 xr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Ir=class extends Te{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Dr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Pr=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 sQ(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(er,e.prototype)||[];o.push({columns:r,name:t??rr(e.table,r.join("_"))}),K.defineMetadata(er,o,e.prototype);}}function iQ(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(tr,e.prototype)||[];o.push({columns:r,name:t??le(e.table,r.join("_"))}),K.defineMetadata(tr,o,e.prototype);}}function aQ(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 x(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(K.getMetadata(nt,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");K.defineMetadata(nt,r,e),K.defineMetadata(nt,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(Xt,e)||[];a.push(s),K.defineMetadata(Xt,a,e);}}x.primary=gf;x.date=Pf;x.datetime=$f;x.timestamp=Ef;x.time=Bf;x.boolean=Df;x.json=vf;x.uuid=Sf;x.ulid=qf;x.integer=Tf;x.bigint=Rf;x.float=bf;x.decimal=_f;x.increment=wf;x.bigIncrement=Nf;x.string=Mf;x.text=Cf;x.binary=Of;x.enum=Af;x.encryption={symmetric:xf,asymmetric:If};function gf(i={}){return x({...i,primaryKey:true})}function bf(i={}){return x({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function Tf(i={}){return x({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 wf(i={}){return x({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 Nf(i={}){return x({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 Sf(i={}){return x({type:"uuid",...i,prepare:t=>t||Se__default.default.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function qf(i={}){return x({type:"ulid",...i,prepare:t=>t||rl(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Mf(i={}){return x({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Cf(i={}){return x({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Rf(i={}){return x({type:"bigint",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"||typeof t=="bigint"?t:BigInt(t)},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function _f(i={}){return x({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 Of(i={}){return x({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Af(i,t={}){return x({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function xf(i){return x({...i,prepare:t=>t&&Za(i.key,t),serialize:t=>t&&Xa(i.key,t)})}function If(i){return x({...i,prepare:t=>t&&el(i.publicKey,t),serialize:t=>t&&tl(i.privateKey,t)})}function Df(i={}){return x({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t,openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function Pf(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:ut(d,void 0,t)};return x({type:"date",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function $f(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"ISO",t):typeof d=="string"?d:oe(d,"ISO",t):r?oe(new Date,"ISO",t):null,l=d=>{if(d!==void 0)return d===null?null:ut(d,void 0,t)};return x({type:"datetime",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function Ef(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?oe(new Date,"TIMESTAMP",t):typeof d=="string"?d:oe(d,"TIMESTAMP",t):r?oe(new Date,"TIMESTAMP",t):null,l=d=>{if(d!==void 0)return d===null?null:ut(d,void 0,t)};return x({type:"timestamp",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function Bf(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:ut(d,void 0,t)};return x({type:"time",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function vf(i={}){return x({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 Bt(i){try{return K.getMetadata(Xt,i.prototype)||[]}catch{return []}}function ip(i,t,e){return((r,o)=>{let n=()=>Ie(i().table),s=()=>{let d=r.constructor.table,u=t||n();return Z(d,u,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(ce,r)||[];l.push(a),K.defineMetadata(ce,l,r);})}function ap(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(ce,e)||[];s.push(n),K.defineMetadata(ce,s,e);})}function lp(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(ce,e)||[];s.push(n),K.defineMetadata(ce,s,e);})}function dp(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,u=o.constructor.table,m=()=>Ie(u),c=()=>Ie(i().table),p=()=>Z(S(d),s?String(s):m()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??p,foreignKey:s?String(s):m,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:u,throughModel:d,leftForeignKey:s?String(s):m,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=K.getMetadata(ce,o)||[];g.push(h),K.defineMetadata(ce,g,o);})}function up(i){return K.getMetadata(ce,i.prototype)||[]}function pr(i){return (K.getMetadata(ce,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 xr(l,n,a);case "hasOne":return new Dr(l,n,a);case "hasMany":return new Ir(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 Pr(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 cp(i){return K.getMetadata(nt,i)||K.getMetadata(nt,i.prototype)}function mp(i){return K.getMetadata(er,i.prototype)||[]}function pp(i){return K.getMetadata(tr,i.prototype)||[]}var Ka=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:["*"]})}},Qf=(i,t)=>new Ka(i,t);function kf(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 Kf(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 fp(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 Lf=fp;function yp(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 Wf=yp;function Ff(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 hp=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},jf=hp;var gp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw M.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 M.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:Vf}=of__default.default;function bp(i){let t=i.name,e=L(t,"snake");return Vf(e)}function Tp(){return {$annotations:{}}}var dt=class extends Oe{static get collection(){return this._collection||bp(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){Wr()(this.prototype,t);}static async afterFetch(t){return t}};za([Wr()],dt.prototype,"id");async function ve(i,t,e){if(!t)return null;let r=Tp(),o=Ga(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 $r(i,t,e){return (await Promise.all(t.map(async o=>await ve(i,o,e)))).filter(o=>o!==null)}var Er=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 $r(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 $r(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 $r(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 M.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 M.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 M.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 M.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 M.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 M.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 Br=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=dt,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 Er(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 Qe=class Qe extends Ye{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 ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,Qe.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 ie.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 Qe(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!Qe.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Qe.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 Qe(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 Br(e,r,o,this.logs)}};Qe.instance=null;var xt=Qe;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");M.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 La=Y;var Wa=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 me(this.dbType);}};async function Gf(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 Zf(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 zm__default.default.promises.unlink(r).catch(()=>{});}}async function Sp(i,t){let e=It__default.default.isAbsolute(i)?i:It__default.default.resolve(process.cwd(),i);return e.endsWith(".ts")?Zf(e):Gf(e)}var Fa=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
189
189
  FROM information_schema.tables
190
190
  WHERE table_catalog = '${e}'
191
191
  AND table_schema = 'public'
@@ -299,5 +299,5 @@ CREATE TABLE [migrations] (
299
299
  "id" NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
300
300
  "name" VARCHAR2(255) NOT NULL,
301
301
  "timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
302
- )`}},we=new Fa;var ry=async(i,t)=>{if(i.endsWith(".ts"))return Sp(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 vr(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 Mp(we.migrationTableTemplateSQLite(),[],t),await Mp(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(m){if(m.errorNum!==955)throw m}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(m=>({id:m[0],name:m[1],timestamp:m[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Qr(i,t,e){let r=sy(t),o=[];for(let n of r){let s=await ny(n,t),a=new s(i||A.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function oy(i,t){let e=await ry(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 ny(i,t=A.MIGRATION_PATH||"database/migrations",e){t=It.join(t,i);let r=It__default.default.resolve(process.cwd(),t),o=await oy(r);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function sy(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=zm__default.default.readdirSync(r).filter(n=>{let s=It__default.default.extname(n),a=It__default.default.join(r,n);return zm__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 Mp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function ja(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;M.info("Rolling back migrations for database type: "+n);try{let l=await vr(n,i.getPool()),d=await Qr(n,e,r),u=l.map(p=>p.name),m=d.filter(p=>u.includes(p.migrationName));if(m.length===0){M.info("No pending migrations.");return}if(t);let c=new ke(i);s&&(a=await i.transaction(),i=a.sql),await c.downMigrations(m),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}M.info("Migrations rolled back successfully");}async function Ua(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;M.info("Running migrations for database type: "+n);try{let l=await vr(n,i.getPool()),u=(await Qr(n,e,r)).filter(c=>!l.map(p=>p.name).includes(c.migrationName));if(!u.length){M.info("No pending migrations.");return}if(t);let m=new ke(i);s&&(a=await i.transaction(),i=a.sql),await m.upMigrations(u),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}M.info("Migrations ran successfully");}var ke=class{constructor(t){this.migrationTable="migrations";this.sql=t||fe.instance;}async upMigrations(t){for(let e of t){M.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){M.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();}},Va=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 fe)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new fe(r),await e.connect();}return t==="up"?Ua(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):ja(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},iy=(i,t)=>new Va(i,t);var Ja=class{constructor(t){this.logger=M;this.sqlDataSource=t;}};exports.BaseSeeder=Ja;exports.Collection=dt;exports.HysteriaError=f;exports.InMemoryAdapter=$t;exports.Migration=Wa;exports.MixinFactory=jf;exports.Model=j;exports.ModelQueryBuilder=lt;exports.MongoDataSource=xt;exports.RawNode=D;exports.RedisCacheAdapter=gp;exports.Schema=me;exports.SchemaBuilder=yt;exports.SqlDataSource=fe;exports.UlidMixin=Lf;exports.UuidMixin=Wf;exports.WriteOperation=V;exports.belongsTo=ip;exports.bigIntMixin=kf;exports.column=x;exports.createMixin=hp;exports.createModelFactory=Qf;exports.defineMigrator=iy;exports.generateOpenApiModel=Wy;exports.generateOpenApiModelSchema=Fy;exports.generateOpenApiModelWithMetadata=al;exports.getCollectionProperties=Ga;exports.getIndexes=mp;exports.getModelColumns=Bt;exports.getPrimaryKey=cp;exports.getRelations=pr;exports.getRelationsMetadata=up;exports.getUniques=pp;exports.hasMany=lp;exports.hasOne=ap;exports.incrementMixin=Kf;exports.index=sQ;exports.logger=M;exports.manyToMany=dp;exports.property=Wr;exports.redis=La;exports.timestampMixin=Ff;exports.ulidMixin=fp;exports.unique=iQ;exports.uuidMixin=yp;exports.view=aQ;exports.withPerformance=W;//# sourceMappingURL=index.cjs.map
302
+ )`}},we=new Fa;var ry=async(i,t)=>{if(i.endsWith(".ts"))return Sp(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 vr(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 Mp(we.migrationTableTemplateSQLite(),[],t),await Mp(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(m){if(m.errorNum!==955)throw m}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(m=>({id:m[0],name:m[1],timestamp:m[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Qr(i,t,e){let r=sy(t),o=[];for(let n of r){let s=await ny(n,t),a=new s(i||A.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function oy(i,t){let e=await ry(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 ny(i,t=A.MIGRATION_PATH||"database/migrations",e){t=It.join(t,i);let r=It__default.default.resolve(process.cwd(),t),o=await oy(r);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function sy(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=zm__default.default.readdirSync(r).filter(n=>{let s=It__default.default.extname(n),a=It__default.default.join(r,n);return zm__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 Mp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function ja(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;M.info("Rolling back migrations for database type: "+n);try{let l=await vr(n,i.getPool()),d=await Qr(n,e,r),u=l.map(p=>p.name),m=d.filter(p=>u.includes(p.migrationName));if(m.length===0){M.info("No pending migrations.");return}if(t);let c=new ke(i);s&&(a=await i.transaction(),i=a.sql),await c.downMigrations(m),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}M.info("Migrations rolled back successfully");}async function Ua(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;M.info("Running migrations for database type: "+n);try{let l=await vr(n,i.getPool()),u=(await Qr(n,e,r)).filter(c=>!l.map(p=>p.name).includes(c.migrationName));if(!u.length){M.info("No pending migrations.");return}if(t);let m=new ke(i);s&&(a=await i.transaction(),i=a.sql),await m.upMigrations(u),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}M.info("Migrations ran successfully");}var ke=class{constructor(t){this.migrationTable="migrations";this.sql=t||fe.instance;}async upMigrations(t){for(let e of t){M.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){M.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();}},Va=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 fe)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new fe(r),await e.connect();}return t==="up"?Ua(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):ja(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},iy=(i,t)=>new Va(i,t);var Ja=class{constructor(t){this.logger=M;this.sqlDataSource=t;}};exports.BaseSeeder=Ja;exports.Collection=dt;exports.HysteriaError=f;exports.InMemoryAdapter=$t;exports.Migration=Wa;exports.MixinFactory=jf;exports.Model=z;exports.ModelQueryBuilder=lt;exports.MongoDataSource=xt;exports.RawNode=D;exports.RedisCacheAdapter=gp;exports.Schema=me;exports.SchemaBuilder=yt;exports.SqlDataSource=fe;exports.UlidMixin=Lf;exports.UuidMixin=Wf;exports.WriteOperation=U;exports.belongsTo=ip;exports.bigIntMixin=kf;exports.column=x;exports.createMixin=hp;exports.createModelFactory=Qf;exports.defineMigrator=iy;exports.generateOpenApiModel=Wy;exports.generateOpenApiModelSchema=Fy;exports.generateOpenApiModelWithMetadata=al;exports.getCollectionProperties=Ga;exports.getIndexes=mp;exports.getModelColumns=Bt;exports.getPrimaryKey=cp;exports.getRelations=pr;exports.getRelationsMetadata=up;exports.getUniques=pp;exports.hasMany=lp;exports.hasOne=ap;exports.incrementMixin=Kf;exports.index=sQ;exports.logger=M;exports.manyToMany=dp;exports.property=Wr;exports.redis=La;exports.timestampMixin=Ff;exports.ulidMixin=fp;exports.unique=iQ;exports.uuidMixin=yp;exports.view=aQ;exports.withPerformance=W;//# sourceMappingURL=index.cjs.map
303
303
  //# sourceMappingURL=index.cjs.map