hysteria-orm 10.2.2 → 10.2.3
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/cli.cjs +77 -21
- package/lib/cli.cjs.map +1 -1
- package/lib/cli.js +77 -21
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +67 -18
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +105 -12
- package/lib/index.d.ts +105 -12
- package/lib/index.js +67 -18
- package/lib/index.js.map +1 -1
- package/package.json +7 -1
package/lib/index.cjs
CHANGED
|
@@ -1,14 +1,53 @@
|
|
|
1
|
-
'use strict';var ge=require('crypto'),Oe=require('dayjs'),Yl=require('dayjs/plugin/customParseFormat.js'),Gl=require('dayjs/plugin/timezone.js'),Zl=require('dayjs/plugin/utc.js'),Sl=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),ct=require('path'),Nd=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module'),bundleRequire=require('bundle-require');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ge__default=/*#__PURE__*/_interopDefault(ge);var Oe__default=/*#__PURE__*/_interopDefault(Oe);var Yl__default=/*#__PURE__*/_interopDefault(Yl);var Gl__default=/*#__PURE__*/_interopDefault(Gl);var Zl__default=/*#__PURE__*/_interopDefault(Zl);var Sl__default=/*#__PURE__*/_interopDefault(Sl);var ct__default=/*#__PURE__*/_interopDefault(ct);var Nd__default=/*#__PURE__*/_interopDefault(Nd);var Vl=Object.defineProperty;var V=(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 U=(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&&Vl(t,e,o),o};var I=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);}}};I.store=new WeakMap;var wr=Symbol("mongoProperties");function Sr(){return (i,t)=>{let e=I.getMetadata(wr,i)||[];e.push(t),I.defineMetadata(wr,e,i);}}function qs(i){return I.getMetadata(wr,i.prototype)||[]}var c=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function Jl(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 zl(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function P(i,t){return t==="preserve"?i:t==="snake"?Jl(i):t==="camel"?zl(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}Oe__default.default.extend(Zl__default.default);Oe__default.default.extend(Gl__default.default);Oe__default.default.extend(Yl__default.default);var mt=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=Oe__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()}},Cs=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new c("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?Oe__default.default(i,t):Oe__default.default(i);if(!r.isValid())throw new c("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch{throw new c("DateUtils::parseDate","FAILED_TO_PARSE_DATE")}},ae=(i=new Date)=>Oe__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var Rs=(i,t)=>{try{let e=ge__default.default.createHash("sha256").update(i).digest(),r=ge__default.default.randomBytes(16),o=ge__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 c("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},_s=(i,t)=>{try{let e=ge__default.default.createHash("sha256").update(i).digest(),[r,o]=t.split(":"),n=ge__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(r,"hex")),s=n.update(o,"hex","utf8");return s+=n.final("utf8"),s}catch(e){throw new c("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Os=(i,t)=>{try{let e=ge__default.default.randomBytes(32),r=ge__default.default.randomBytes(16),o=ge__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=ge.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new c("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Ds=(i,t)=>{try{let[e,r,o]=t.split(":"),n=ge.privateDecrypt(i,Buffer.from(r,"hex")),s=ge__default.default.createDecipheriv("aes-256-cbc",n,Buffer.from(e,"hex")),a=s.update(o,"hex","utf8");return a+=s.final("utf8"),a}catch(e){throw new c("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var Nr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Mr=Nr.length,rd=10,od=16,nd=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Mr;e=Nr.charAt(o)+e,i=(i-o)/Mr;}return e},sd=i=>{let t=ge.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Nr.charAt(o%Mr);}return e},As=()=>{let i=Math.floor(Date.now()/1e3),t=nd(i,rd),e=sd(od);return t+e};function qr(i){return i.replace(/^[`"]|[`"]$/g,"")}function Cr(i,t,e){if(!i.includes(".")){let n=qr(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=qr(r),o=qr(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function w(i){return typeof i=="function"?i():i}var K=(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]=K(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]=K(o,t);}return e};var Se=class{};Se.modelCaseConvention="camel",Se.databaseCaseConvention="snake";var id=async(i,t,e,r,o=[],n=[],s=false)=>{let a=new t,l=new Set(e.filter(m=>m.hidden).map(m=>m.columnName)),d=new Map(e.map(m=>[m.databaseName,m])),u=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async m=>{let p=i[m],y=d.get(m)?.columnName??P(m,t.modelCaseConvention);if(y==="$annotations"&&!s){ad(i,m,a,t,n);return}if(!r.has(y)||l.has(y)||u&&!u.has(y))return;if(p===null){a[y]=null;return}let h=r.get(y);if(h&&h.serialize){a[y]=await h.serialize(p);return}a[y]=p;})),u)for(let m of u)m in a||(a[m]=null);return a},ad=(i,t,e,r,o=[])=>{let n=i[t];if(!n||!Object.keys(n).length)return;let s=o.length>0?new Set(o):null;if(!s)return;let a={};for(let l of Object.keys(n))s.has(l)&&(a[P(l,r.modelCaseConvention)]=n[l]);Object.keys(a).length>0&&(e[t]=a);},le=async(i,t,e=[],r=[],o=false)=>{if(!i.length)return null;let n=t.getColumns(),s=new Map(n.map(d=>[d.columnName,d])),a=[];for(let d of e){if(d.toLowerCase().includes("as"))continue;let u=d;if(u.includes(".")&&(u=u.split(".").pop()),u==="*")continue;let m=s.get(u)?.columnName??P(u,t.modelCaseConvention);a.push(m);}e=a;let l=await Promise.all(i.map(async d=>await id(d,t,n,s,e,r,o)));return l.length===1?l[0]:l};var B=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 Ps=null;function xs(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 He(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 ld(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Ps;}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 xs(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return xs(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(He(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(He(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(He(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db});return He(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 He(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 dd(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function cd(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),t=await ld(),e=await dd();i.default.registerAdapter({Database:e,Resource:t});}async function Rr(i,t){Ps=i;let e=await import('adminjs').catch(()=>{throw new B("adminjs")});await cd();let r=t.resources||Object.values(i.registeredModels);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 Is(i,t){let{admin:e}=await Rr(i,t),r;try{r=await import('@adminjs/express');}catch{throw new B("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var yt=new Map,ft=class{async get(t){return yt.get(t)}async set(t,e,r){yt.set(t,e),r&&setTimeout(()=>{yt.delete(t);},r);}async invalidate(t){yt.delete(t);}};var q={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"},md=()=>{try{Sl__default.default.readFileSync(".env","utf8").split(`
|
|
2
|
-
`).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":
|
|
3
|
-
Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}}handleCockroachdbSource(t){this.host=t?.host||
|
|
4
|
-
${t}${
|
|
5
|
-
`:i==="warn"?`${
|
|
6
|
-
${t}${
|
|
7
|
-
`:i==="info"?`${
|
|
8
|
-
${t}${
|
|
1
|
+
'use strict';var we=require('crypto'),xe=require('dayjs'),Qu=require('dayjs/plugin/customParseFormat.js'),ku=require('dayjs/plugin/timezone.js'),Lu=require('dayjs/plugin/utc.js'),cu=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),pt=require('path'),cm=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module'),bundleRequire=require('bundle-require');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var we__default=/*#__PURE__*/_interopDefault(we);var xe__default=/*#__PURE__*/_interopDefault(xe);var Qu__default=/*#__PURE__*/_interopDefault(Qu);var ku__default=/*#__PURE__*/_interopDefault(ku);var Lu__default=/*#__PURE__*/_interopDefault(Lu);var cu__default=/*#__PURE__*/_interopDefault(cu);var pt__default=/*#__PURE__*/_interopDefault(pt);var cm__default=/*#__PURE__*/_interopDefault(cm);var $u=Object.defineProperty;var Z=(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 Y=(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&&$u(t,e,o),o};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 Mr=Symbol("mongoProperties");function qr(){return (i,t)=>{let e=K.getMetadata(Mr,i)||[];e.push(t),K.defineMetadata(Mr,e,i);}}function Si(i){return K.getMetadata(Mr,i.prototype)||[]}var c=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function vu(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 Ku(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function $(i,t){return t==="preserve"?i:t==="snake"?vu(i):t==="camel"?Ku(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}xe__default.default.extend(Lu__default.default);xe__default.default.extend(ku__default.default);xe__default.default.extend(Qu__default.default);var yt=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=xe__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()}},Mi=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new c("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?xe__default.default(i,t):xe__default.default(i);if(!r.isValid())throw new c("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new c("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},pe=(i=new Date)=>xe__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var qi=(i,t)=>{try{let e=we__default.default.createHash("sha256").update(i).digest(),r=we__default.default.randomBytes(16),o=we__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 c("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Ci=(i,t)=>{try{let e=we__default.default.createHash("sha256").update(i).digest(),[r,o]=t.split(":"),n=we__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(r,"hex")),s=n.update(o,"hex","utf8");return s+=n.final("utf8"),s}catch(e){throw new c("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Ri=(i,t)=>{try{let e=we__default.default.randomBytes(32),r=we__default.default.randomBytes(16),o=we__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=we.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new c("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},_i=(i,t)=>{try{let[e,r,o]=t.split(":"),n=we.privateDecrypt(i,Buffer.from(r,"hex")),s=we__default.default.createDecipheriv("aes-256-cbc",n,Buffer.from(e,"hex")),a=s.update(o,"hex","utf8");return a+=s.final("utf8"),a}catch(e){throw new c("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var Rr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Cr=Rr.length,Wu=10,Vu=16,Hu=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Cr;e=Rr.charAt(o)+e,i=(i-o)/Cr;}return e},Ju=i=>{let t=we.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Rr.charAt(o%Cr);}return e},Oi=()=>{let i=Math.floor(Date.now()/1e3),t=Hu(i,Wu),e=Ju(Vu);return t+e};function _r(i){return i.replace(/^[`"]|[`"]$/g,"")}function Or(i,t,e){if(!i.includes(".")){let n=_r(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=_r(r),o=_r(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function w(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 Re=class{};Re.modelCaseConvention="camel",Re.databaseCaseConvention="snake";var zu=async(i,t,e,r,o=[],n=[],s=false)=>{let a=new t,l=new Set(e.filter(m=>m.hidden).map(m=>m.columnName)),d=new Map(e.map(m=>[m.databaseName,m])),u=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async m=>{let p=i[m],f=d.get(m)?.columnName??$(m,t.modelCaseConvention);if(f==="$annotations"&&!s){Yu(i,m,a,t,n);return}if(!r.has(f)||l.has(f)||u&&!u.has(f))return;if(p===null){a[f]=null;return}let g=r.get(f);if(g&&g.serialize){a[f]=await g.serialize(p);return}a[f]=p;})),u)for(let m of u)m in a||(a[m]=null);return a},Yu=(i,t,e,r,o=[])=>{let n=i[t];if(!n||!Object.keys(n).length)return;let s=o.length>0?new Set(o):null;if(!s)return;let a={};for(let l of Object.keys(n))s.has(l)&&(a[$(l,r.modelCaseConvention)]=n[l]);Object.keys(a).length>0&&(e[t]=a);},fe=async(i,t,e=[],r=[],o=false)=>{if(!i.length)return null;let n=t.getColumns(),s=new Map(n.map(d=>[d.columnName,d])),a=[];for(let d of e){if(d.toLowerCase().includes("as"))continue;let u=d;if(u.includes(".")&&(u=u.split(".").pop()),u==="*")continue;let m=s.get(u)?.columnName??$(u,t.modelCaseConvention);a.push(m);}e=a;let l=await Promise.all(i.map(async d=>await zu(d,t,n,s,e,r,o)));return l.length===1?l[0]:l};var B=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var ht={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 Di=null;function Ai(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=ht[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 Ge(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 Gu(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Di;}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=ht[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=ht[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 Ai(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return Ai(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(Ge(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(Ge(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(Ge(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db});return Ge(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 Ge(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 Zu(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function Xu(){let i=await import('adminjs').catch(()=>{throw new B("adminjs")}),t=await Gu(),e=await Zu();i.default.registerAdapter({Database:e,Resource:t});}async function Ar(i,t){Di=i;let e=await import('adminjs').catch(()=>{throw new B("adminjs")});await Xu();let r=t.resources||Object.values(i.registeredModels);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 Ii(i,t){let{admin:e}=await Ar(i,t),r;try{r=await import('@adminjs/express');}catch{throw new B("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var gt=new Map,bt=class{async get(t){return gt.get(t)}async set(t,e,r){gt.set(t,e),r&&setTimeout(()=>{gt.delete(t);},r);}async invalidate(t){gt.delete(t);}};var R={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},tm=()=>{try{cu__default.default.readFileSync(".env","utf8").split(`
|
|
2
|
+
`).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":R.DB_TYPE||(R.DB_TYPE=s);break;case "DB_HOST":R.DB_HOST||(R.DB_HOST=s);break;case "DB_PORT":R.DB_PORT||(R.DB_PORT=s);break;case "DB_USER":R.DB_USER||(R.DB_USER=s);break;case "DB_PASSWORD":R.DB_PASSWORD||(R.DB_PASSWORD=s);break;case "DB_DATABASE":R.DB_DATABASE||(R.DB_DATABASE=s);break;case "MIGRATION_PATH":R.MIGRATION_PATH||(R.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":R.REDIS_HOST||(R.REDIS_HOST=s);break;case "REDIS_PORT":R.REDIS_PORT||(R.REDIS_PORT=s);break;case "REDIS_USERNAME":R.REDIS_USERNAME||(R.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":R.REDIS_PASSWORD||(R.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":R.REDIS_DATABASE||(R.REDIS_DATABASE=s);break;case "MONGO_URL":R.MONGO_URL||(R.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":R.MSSQL_TRUST_SERVER_CERTIFICATE||(R.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return R}},q=tm();var ke=class{constructor(t){switch(this.type=t?.type||q.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;default:throw new c(`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
|
+
Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}}handleCockroachdbSource(t){this.host=t?.host||q.DB_HOST,this.port=+t?.port||+q.DB_PORT,this.username=t?.username||q.DB_USER,this.password=t?.password||q.DB_PASSWORD,this.database=t?.database||q.DB_DATABASE,this.logs=t?.logs||q.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||q.DB_HOST,this.port=+t?.port||+q.DB_PORT,this.username=t?.username||q.DB_USER,this.password=t?.password||q.DB_PASSWORD,this.database=t?.database||q.DB_DATABASE,this.logs=t?.logs||q.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||q.DB_HOST,this.port=+t?.port||+q.DB_PORT,this.username=t?.username||q.DB_USER,this.password=t?.password||q.DB_PASSWORD,this.database=t?.database||q.DB_DATABASE,this.logs=t?.logs||q.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||q.DB_DATABASE,this.logs=t?.logs||q.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||q.MONGO_URL,this.logs=t?.logs||q.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||q.DB_HOST,this.port=+t?.port||+q.DB_PORT,this.username=t?.username||q.DB_USER,this.password=t?.password||q.DB_PASSWORD,this.database=t?.database||q.DB_DATABASE,this.logs=t?.logs||q.DB_LOGS||false,this.port||(this.port=1433);}};var rm=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},om=i=>i.openApi?.required??false,nm=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=rm(r));return e},sm=i=>{let t=i.getColumns(),e=[];for(let r of t)om(r)&&e.push(r.columnName);return e||[]},Dr=i=>{let t=nm(i),e=sm(i);return {type:"object",properties:t,required:e.length?e:[]}},Ac=i=>i.map(t=>Dr(t)),Dc=i=>Dr(i),Pi=i=>i.map(t=>({...Dr(t),modelName:t.name,$id:t.name}));var Ir=(i,t)=>{let e=we__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var Le={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function lm(){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 Pr(i,t){let e=lm(),r=i.toUpperCase();return i==="error"?`${Le.error}[${r}] ${e}
|
|
4
|
+
${t}${Le.reset}
|
|
5
|
+
`:i==="warn"?`${Le.warn}[${r}] ${e}
|
|
6
|
+
${t}${Le.reset}
|
|
7
|
+
`:i==="info"?`${Le.info}[${r}] ${e}
|
|
8
|
+
${t}${Le.reset}
|
|
9
9
|
`:`[${r}] ${e}
|
|
10
10
|
${t}
|
|
11
|
-
`}var ke=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){if(t instanceof Error){this.loggerInstance.error(String(t));return}this.loggerInstance.error(t);}static warn(t){this.loggerInstance.warn(t);}};ke.loggerInstance={info(t){console.log(Dr("info",t));},error(t){console.error(Dr("error",t));},warn(t){console.warn(Dr("warn",t));}};function wd(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function Je(i,t,e){if(!t)return;i=sqlHighlight.highlight(i,{colors:{keyword:"\x1B[34m",string:"\x1B[32m",number:"\x1B[33m",bracket:"\x1B[36m",clear:"\x1B[0m",comment:"\x1B[90m",function:"\x1B[35m",identifier:"\x1B[37m",special:"\x1B[31m"}});let r=`${i} [${wd(e||[])}]`;ke.loggerInstance.info(r);}function Es(i,t,e=false){e&&ke.loggerInstance[t](i);}var M=ke;var ht=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";default:return "sql"}},$s=i=>{if(i==null)return "NULL";if(i instanceof Date)return `'${i.toISOString()}'`;let t=typeof i;return t==="boolean"?i?"TRUE":"FALSE":t==="number"&&Number.isFinite(i)||t==="bigint"?String(i):t==="string"?`'${i.replace(/'/g,"''")}'`:Array.isArray(i)||t==="object"&&Object.keys(i).length>0?`'${JSON.stringify(i).replace(/'/g,"''")}'`:String(i)},Ks=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,$s(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,$s(t[r]));}return e},ze=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):false:false,gt=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:ht(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var Ar=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},ks=new Ar;var xr=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Qs=new xr;var Pr=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Fs=new Pr;var Ir=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(e.options.dropDefault)a+=" drop default";else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}return e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},Ls=new Ir;var f=class{constructor(t){this.model=t;let e=bt(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":return `"${n}".*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??P(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${n}"."${a}"`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??P(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${o}"`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":return `"${e}"${r?` as "${r}"`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a==="*"||a==="$annotations"||(o.push(a),n.push(l));}await Promise.all(o.map(async(s,a)=>{let l=o[a],d=n[a],u=this.modelColumnsMap.get(l),m=d;u&&(r==="insert"&&u.prepare?m=await u.prepare(d):r==="update"&&(m=await u.prepare?.(d)??d)),n[a]=m;}));for(let s of this.modelColumnsMap.keys())if(!o.includes(s)){let a=this.modelColumnsMap.get(s);if(!a||r==="insert"&&s===this.model.primaryKey&&!a.prepare)continue;(r==="insert"||a.autoUpdate)&&(o.push(s),n.push(a.prepare?.(void 0)??void 0));}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new T(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var Br=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new T(this.model,"mysql"),s=[],a=[];for(let p of e.children){let{sql:y,bindings:h}=n.parse([p]);if(p.file==="add_column")s.push(y);else if(p.file==="add_constraint"||p.folder==="constraint"){let g=s[s.length-1]??"",S=/^\s*add\s+column\b/i.test(g),O=/^\s*add\s+constraint\b/i.test(y);if(S&&!O){let v=y.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${g} ${v}`;}else {let v=/^\s*add\b/i.test(y)?y:`add ${y}`;s.push(v);}}else p.file==="set_default"||p.file==="drop_default"||p.file==="set_not_null"||p.file,s.push(y);a.push(...h);}let l=s.join(", "),d=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${d}${o} ${l}`,bindings:a}}},js=new Br;var Er=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Ws=new Er;var vr=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},Us=new vr;var $r=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},Vs=new $r;var Kr=class{toSql(t){return {sql:"",bindings:[]}}},Hs=new Kr;var kr=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Js=new kr;var Qr=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},zs=new Qr;var Fr=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},Ys=new Fr;var Lr=class{toSql(t){let e=t,r=e.defaultValue;return r==="NULL"?r="null":r==="TRUE"||r==="FALSE"?r=r.toLowerCase():typeof r=="string"&&r!=="null"&&r!=="true"&&r!=="false"&&(r=`'${r}'`),{sql:`alter column \`${e.column}\` set default ${r}`,bindings:[]}}},Gs=new Lr;var jr=class{toSql(t){return {sql:"",bindings:[]}}},Zs=new jr;var Wr=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new f(this.model).formatStringColumn("mysql",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")return {sql:`${o} ${n}`,bindings:[]};if(n==="integer"||n==="int"){let s="int";return e.autoIncrement&&(s+=" auto_increment"),{sql:`${o} ${s}`,bindings:[]}}else {if(n==="tinyint")return {sql:`${o} tinyint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} mediumint`,bindings:[]};if(n==="bigint"){let s="bigint";return e.autoIncrement&&(s+=" auto_increment"),{sql:`${o} ${s}`,bindings:[]}}else {if(n==="float")return {sql:`${o} float`,bindings:[]};if(n==="double")return {sql:`${o} double`,bindings:[]};if(n==="real")return {sql:`${o} double`,bindings:[]};if(n==="decimal"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} decimal(${s}, ${a})`,bindings:[]}}else if(n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`.trimEnd(),bindings:[]}}else if(n==="datetime"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} datetime${s}`.trimEnd(),bindings:[]}}else if(n==="timestamp"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${s}`.trimEnd(),bindings:[]}}else {if(n==="year")return {sql:`${o} year`,bindings:[]};if(n==="boolean")return {sql:`${o} boolean`,bindings:[]};if(n==="varbinary"){let s=e.length??255;return {sql:`${o} varbinary(${s})`,bindings:[]}}else if(n==="binary"){let s=e.length??255;return {sql:`${o} binary(${s})`,bindings:[]}}else {if(n==="bytea"||n==="blob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} json`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} enum(${s})`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}}}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Xs=new Wr;var Ur=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},ei=new Ur;var Vr=class{toSql(t){let e=t,r=new f(this.model);if(e.constraintType==="primary_key"){let o=(e.columns??[]).map(s=>r.formatStringColumn("mysql",w(s))).join(", ");return {sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}primary key (${o})`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns.map(s=>r.formatStringColumn("mysql",w(s))).join(", "),n=e.constraintName?`constraint \`${e.constraintName}\` `:"";return e.constraintName?{sql:`${n}unique (${o})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let o=e.defaultValue;return o==="NULL"?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:o===null?{sql:"default null",bindings:[]}:(typeof o=="string"&&(o=`'${o}'`),{sql:`default ${o}`,bindings:[]})}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let o=(e.columns??[]).map(d=>r.formatStringColumn("mysql",w(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",w(d))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},ti=new Vr;var Hr=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new T(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:y}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=p;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let S=`${h} ${g}`.trim();S=S.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(S),a.push(...y);continue}s.push(h),s.push(g),a.push(...y);continue}s.push(p),a.push(...y);}for(let m of e.namedConstraints){let{sql:p,bindings:y}=n.parse([m]);s.push(p),a.push(...y);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},ri=new Hr;var Jr=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new f(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},oi=new Jr;var zr=class{toSql(t){return {sql:"distinct",bindings:[]}}},ni=new zr;var Yr=class{toSql(t){return M.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},si=new Yr;var Gr=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},ii=new Gr;var Zr=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new f(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mysql",e.table)} as \`${e.alias}\``,bindings:[]}:{sql:a.formatStringTable("mysql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new T(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},ai=new Zr;var Xr=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new f(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},li=new Xr;var b=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var eo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof b)&&!Array.isArray(e.value)&&(o=`${new f(this.model).formatStringColumn("mysql",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new f(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},di=new eo;var to=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("mysql",e.table),n=e.columns.map(a=>`\`${a}\``).join(", ");return {sql:`${e.unique?"unique ":""}\`${e.indexName}\` on ${o} (${n})`,bindings:[]}}},ci=new to;var ro=class{toSql(t){let e=t;if(!e.table)throw new Error("MySQL DROP INDEX requires table name");return {sql:`\`${e.indexName}\` on \`${e.table}\``,bindings:[]}}},ui=new ro;var oo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new f(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("mysql",m)).join(", "),l=[],d=[];for(let m of e.records){let p=s.map(h=>m[h]);l.push(...p);let y=Array(s.length).fill("?").join(", ");d.push(`(${y})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},mi=new oo;var no=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mysql",o),a=r.formatStringColumn("mysql",n);return {sql:`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},pi=new no;var so=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},yi=new so;var Sd={for_update:"for update",for_share:"lock in share mode"},io=class{toSql(t){let e=t,r=Sd[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},fi=new io;var ao=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},hi=new ao;var lo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model);if(e.mode==="ignore"){let n=e.conflictColumns?.[0]||"id",s=r.formatStringColumn("mysql",`${e.table}.${n}`);return {sql:`AS new ON DUPLICATE KEY UPDATE ${s} = ${s}`,bindings:[]}}return {sql:`AS new ON DUPLICATE KEY UPDATE ${e.columnsToUpdate.map(n=>`${r.formatStringColumn("mysql",n)} = new.${r.formatStringColumn("mysql",n)}`).join(", ")}`,bindings:[]}}},gi=new lo;var co=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new f(this.model).formatStringColumn("mysql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},bi=new co;var uo=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Ti=new uo;var mo=class{toSql(t){return {sql:`SELECT
|
|
11
|
+
`}var Fe=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){if(t instanceof Error){this.loggerInstance.error(String(t));return}this.loggerInstance.error(t);}static warn(t){this.loggerInstance.warn(t);}};Fe.loggerInstance={info(t){console.log(Pr("info",t));},error(t){console.error(Pr("error",t));},warn(t){console.warn(Pr("warn",t));}};function dm(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function ne(i,t,e){if(!t)return;i=sqlHighlight.highlight(i,{colors:{keyword:"\x1B[34m",string:"\x1B[32m",number:"\x1B[33m",bracket:"\x1B[36m",clear:"\x1B[0m",comment:"\x1B[90m",function:"\x1B[35m",identifier:"\x1B[37m",special:"\x1B[31m"}});let r=`${i} [${dm(e||[])}]`;Fe.loggerInstance.info(r);}function xi(i,t,e=false){e&&Fe.loggerInstance[t](i);}var M=Fe;var Tt=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";default:return "sql"}},xr=i=>{if(i==null)return "NULL";if(i instanceof Date)return `'${i.toISOString()}'`;let t=typeof i;return t==="boolean"?i?"TRUE":"FALSE":t==="number"&&Number.isFinite(i)||t==="bigint"?String(i):t==="string"?`'${i.replace(/'/g,"''")}'`:Array.isArray(i)||t==="object"&&Object.keys(i).length>0?`'${JSON.stringify(i).replace(/'/g,"''")}'`:String(i)},$i=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,xr(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,xr(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`@p${r}(?!\\d)`,"g");e=e.replace(o,xr(t[r]));}return e},Ze=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):false:false,wt=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:Tt(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var Er=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Bi=new Er;var $r=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},vi=new $r;var Br=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},Ki=new Br;var vr=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a="";e.options.nullable!==void 0&&(a=e.options.nullable?" null":" not null");let l=`alter column [${e.column}] ${s}${a}`;if(e.options.dropDefault&&(l=`drop constraint DF_${e.column}, ${l}`),e.options.default!==void 0&&!e.options.dropDefault){let d=e.options.default;d===null?d="null":typeof d=="string"&&(d==="NULL"?d="null":d==="TRUE"||d==="FALSE"?d=d==="TRUE"?"1":"0":d=`'${d}'`),l+=`, add constraint DF_${e.column} default ${d} for [${e.column}]`;}return e.options.unique!==void 0&&e.options.unique&&(l+=`, add constraint UQ_${e.column} unique ([${e.column}])`),{sql:l,bindings:[]}}},Qi=new vr;var T=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var je=class extends T{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var y=class{constructor(t){this.model=t;let e=Nt(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??$(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??$(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a==="*"||a==="$annotations"||(o.push(a),n.push(l));}await Promise.all(o.map(async(s,a)=>{let l=o[a],d=n[a],u=this.modelColumnsMap.get(l),m=d;u&&(r==="insert"&&u.prepare?m=await u.prepare(d):r==="update"&&(m=await u.prepare?.(d)??d)),n[a]=m;}));for(let s of this.modelColumnsMap.keys())if(!o.includes(s)){let a=this.modelColumnsMap.get(s);if(!a||r==="insert"&&s===this.model.primaryKey&&!a.prepare)continue;(r==="insert"||a.autoUpdate)&&(o.push(s),n.push(a.prepare?.(void 0)??void 0));}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var Kr=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};if(e.children.length===1&&e.children[0]instanceof je){let u=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${u.newName}'`,bindings:[]}}let n=new b(this.model,"mssql"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:p}=n.parse([u]);s.push(m.trim()),a.push(...p);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},ki=new Kr;var Qr=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Li=new Qr;var kr=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},Fi=new kr;var Lr=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},ji=new Lr;var Fr=class{toSql(t){let e=t;return M.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},Ui=new Fr;var jr=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Wi=new jr;var Ur=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Vi=new Ur;var Wr=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},Hi=new Wr;var v=class extends T{constructor(e){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e;}};var Vr=class{toSql(t){let e=t,r;return e.defaultValue instanceof v?r=e.defaultValue.rawValue:e.defaultValue==="NULL"||e.defaultValue===null?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="1"&&e.defaultValue!=="0"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`add constraint DF_${e.column} default ${r} for [${e.column}]`,bindings:[]}}},Ji=new Vr;var Hr=class{toSql(t){let e=t;return M.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},zi=new Hr;var Jr=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mssql",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} varchar(max)`,bindings:[]};if(n==="uuid")return {sql:`${o} uniqueidentifier`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigint identity(1,1)`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} tinyint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} int`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} float`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} decimal(${s}, ${a})`,bindings:[]}}if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}if(n==="datetime"||n==="timestamp"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} datetime2${s}`,bindings:[]}}if(n==="boolean"||n==="bool")return {sql:`${o} bit`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} varbinary(max)`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} nvarchar(max)`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar(255)`,bindings:[]}}return n==="integer"||n==="int"?e.autoIncrement?{sql:`${o} int identity(1,1)`,bindings:[]}:{sql:`${o} int`,bindings:[]}:{sql:`${o} ${n}${e.length?`(${e.length})`:""}`,bindings:[]}}},Yi=new Jr;var zr=class{toSql(t){return {sql:"",bindings:[]}}},Gi=new zr;var Yr=class{toSql(t){let e=t,r=new y(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint [${e.constraintName}] `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("mssql",w(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint [${e.constraintName}] `:"",s=o.map(a=>r.formatStringColumn("mssql",w(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof v?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("mssql",w(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mssql",w(d))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},Zi=new Yr;var Gr=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mssql"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:p}=n.parse([u]);if(u.folder==="constraint"){let f=s.pop()??"",g=m;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let h=`${f} ${g}`.trim();h=h.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(h),a.push(...p);continue}s.push(f),s.push(g),a.push(...p);continue}s.push(m),a.push(...p);}for(let u of e.namedConstraints){let{sql:m,bindings:p}=n.parse([u]);s.push(m),a.push(...p);}let l=s.join(", ");return {sql:`${o} (${l})`,bindings:a}}},Xi=new Gr;var Zr=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("mssql",e.fromNode),bindings:[]}}},ea=new Zr;var Xr=class{toSql(t){return {sql:"",bindings:[]}}},ta=new Xr;var eo=class{toSql(t){return M.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},ra=new eo;var to=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},oa=new to;var ro=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new y(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mssql",e.table)} as [${e.alias}]`,bindings:[]}:{sql:a.formatStringTable("mssql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mssql").parse(r),s=e.alias&&e.alias.length?` as [${e.alias}]`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},na=new ro;var oo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},sa=new oo;var no=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof T)&&!Array.isArray(e.value)&&(o=`${new y(this.model).formatStringColumn("mssql",e.column)} ${e.operator} @${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`@${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("mssql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},ia=new no;var so=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table),n=e.columns.map(a=>`[${a}]`).join(", ");return {sql:`${e.unique?"unique ":""}[${e.indexName}] on ${o} (${n})`,bindings:[]}}},aa=new so;var io=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},la=new io;var ao=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n).filter(p=>n[p]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("mssql",p)).join(", "),l=[],d=[],u=e.currParamIndex;for(let p of e.records){let f=s.map(h=>p[h]);l.push(...f);let g=s.map(()=>`@${u++}`).join(", ");d.push(`(${g})`);}let m=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let p=e.returning.map(f=>`inserted.${r.formatStringColumn("mssql",f)}`).join(", ");m=m.replace(") values",`) output ${p} values`);}else {let p=this.getOutputColumns(s,r);m=m.replace(") values",`) output ${p} values`);}return {sql:m,bindings:l}}getOutputColumns(t,e){let r=[...t],o=this.model.primaryKey;return o&&!t.includes(o)&&r.push(o),r.map(n=>`inserted.${e.formatStringColumn("mssql",n)}`).join(", ")}},da=new ao;var lo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mssql",o),a=r.formatStringColumn("mssql",n);return {sql:`${r.formatStringTable("mssql",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},ua=new lo;var uo=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},ma=new uo;var mo=class{toSql(t){return {sql:"",bindings:[]}}},ca=new mo;var co=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},pa=new co;var po=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(M.warn("MSSQL does not support ON CONFLICT or ON DUPLICATE KEY. Use MERGE statement for upsert operations. This clause will be ignored. Consider using raw queries for MSSQL upserts."),{sql:"",bindings:[]})}},fa=new po;var fo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("mssql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},ya=new fo;var yo=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},ha=new yo;var ho=class{toSql(t){return {sql:`SELECT
|
|
12
|
+
fk.name as name,
|
|
13
|
+
c.name as column_name,
|
|
14
|
+
rt.name as referenced_table,
|
|
15
|
+
rc.name as referenced_column,
|
|
16
|
+
fk.update_referential_action_desc as on_update,
|
|
17
|
+
fk.delete_referential_action_desc as on_delete
|
|
18
|
+
FROM sys.foreign_keys fk
|
|
19
|
+
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
|
|
20
|
+
INNER JOIN sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
|
|
21
|
+
INNER JOIN sys.tables rt ON fkc.referenced_object_id = rt.object_id
|
|
22
|
+
INNER JOIN sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
|
|
23
|
+
WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},ga=new ho;var go=class{toSql(t){return {sql:`SELECT
|
|
24
|
+
i.name as index_name,
|
|
25
|
+
c.name as column_name,
|
|
26
|
+
i.is_unique as is_unique
|
|
27
|
+
FROM sys.indexes i
|
|
28
|
+
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
29
|
+
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
30
|
+
WHERE i.object_id = OBJECT_ID('${t.table}')
|
|
31
|
+
AND i.is_primary_key = 0
|
|
32
|
+
AND i.type > 0`,bindings:[]}}},ba=new go;var bo=class{toSql(t){return {sql:`SELECT
|
|
33
|
+
tc.CONSTRAINT_NAME as name,
|
|
34
|
+
kcu.COLUMN_NAME as column_name
|
|
35
|
+
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
|
|
36
|
+
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
|
|
37
|
+
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
|
|
38
|
+
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
|
39
|
+
AND tc.TABLE_NAME = '${t.table}'
|
|
40
|
+
ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},Ta=new bo;var To=class{toSql(t){return {sql:`SELECT
|
|
41
|
+
c.COLUMN_NAME as column_name,
|
|
42
|
+
c.DATA_TYPE as data_type,
|
|
43
|
+
c.IS_NULLABLE as is_nullable,
|
|
44
|
+
c.COLUMN_DEFAULT as column_default,
|
|
45
|
+
c.CHARACTER_MAXIMUM_LENGTH as char_length,
|
|
46
|
+
c.NUMERIC_PRECISION as numeric_precision,
|
|
47
|
+
c.NUMERIC_SCALE as numeric_scale
|
|
48
|
+
FROM INFORMATION_SCHEMA.COLUMNS c
|
|
49
|
+
WHERE c.TABLE_NAME = '${t.table}'
|
|
50
|
+
ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},wa=new To;var wo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("mssql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mssql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mssql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("mssql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mssql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as [${t}]`:""}},Na=new wo;var No=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:`table ${new y(this.model).getFromForWriteOperations("mssql",e.fromNode)}`,bindings:[]}}},Sa=new No;var So=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Ma=new So;var Mo=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("mssql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let u=e.currParamIndex+d-n,m=e.values[d];return m instanceof v?(n++,`${r.formatStringColumn("mssql",l)} = ${m.rawValue}`):(s.push(m),`${r.formatStringColumn("mssql",l)} = @${u}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},qa=new Mo;var qo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.value,o=e.currParamIndex;if(this.isRawNode(r)){let a=this.formatRawIdentifierIfPossible(r.rawValue);return {sql:`${new y(this.model).formatStringColumn("mssql",e.column)} ${e.operator} ${a}`.trim(),bindings:[]}}if(Array.isArray(r)){let a=new y(this.model).formatStringColumn("mssql",e.column);if(e.operator.toLowerCase()==="between"){let u=`@${o} AND @${o+1}`,m=`${a} between ${u}`;return e.isNegated&&(m=`not (${m})`),{sql:m.trim(),bindings:r}}let l=r.map((u,m)=>`@${o+m}`).join(", "),d=`${a} ${e.operator} (${l})`;return e.isNegated&&(d=`not (${d})`),{sql:d.trim(),bindings:r}}let n=new y(this.model).formatStringColumn("mssql",e.column);if(e.operator.includes("null")){let a=`${n} ${e.operator}`;return e.isNegated&&(a=`not (${a})`),{sql:a.trim(),bindings:[]}}if(r===void 0)return {sql:"",bindings:[]};let s=`${n} ${e.operator} @${o}`;return e.isNegated&&(s=`not (${s})`),{sql:s.trim(),bindings:[r]}}isRawNode(t){if(!t||!(typeof t=="object"))return false;let r="rawValue"in t,o=t.isRawValue===true;return r&&o}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("mssql",t):t}},Ca=new qo;var Co=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"mssql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Ra=new Co;var Ro=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new y(this.model).formatStringColumn("mssql",e.column);switch(e.jsonOperator){case "=":o=`${s} = @${r}`,n=[JSON.stringify(e.value)];break;case "contains":case "not contains":o=`CHARINDEX(@${r}, ${s}) > 0`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},_a=new Ro;var _o=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mssql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Oa=new _o;var Oo=class{toSql(t){let e=t,r=new b(this.model,"mssql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return e.clause==="materialized"&&M.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},Aa=new Oo;var Ao=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Da=new Ao;var Do=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Ia=new Do;var Io=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Pa=new Io;var Po=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(e.options.dropDefault)a+=" drop default";else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}return e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},xa=new Po;var xo=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let p of e.children){let{sql:f,bindings:g}=n.parse([p]);if(p.file==="add_column")s.push(f);else if(p.file==="add_constraint"||p.folder==="constraint"){let h=s[s.length-1]??"",N=/^\s*add\s+column\b/i.test(h),I=/^\s*add\s+constraint\b/i.test(f);if(N&&!I){let Q=f.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${h} ${Q}`;}else {let Q=/^\s*add\b/i.test(f)?f:`add ${f}`;s.push(Q);}}else p.file==="set_default"||p.file==="drop_default"||p.file==="set_not_null"||p.file,s.push(f);a.push(...g);}let l=s.join(", "),d=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${d}${o} ${l}`,bindings:a}}},Ea=new xo;var Eo=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},$a=new Eo;var $o=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},Ba=new $o;var Bo=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},va=new Bo;var vo=class{toSql(t){return {sql:"",bindings:[]}}},Ka=new vo;var Ko=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Qa=new Ko;var Qo=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},ka=new Qo;var ko=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},La=new ko;var Lo=class{toSql(t){let e=t,r;return e.defaultValue instanceof v?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column \`${e.column}\` set default ${r}`,bindings:[]}}},Fa=new Lo;var Fo=class{toSql(t){return {sql:"",bindings:[]}}},ja=new Fo;var jo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mysql",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")return {sql:`${o} ${n}`,bindings:[]};if(n==="integer"||n==="int"){let s="int";return e.autoIncrement&&(s+=" auto_increment"),{sql:`${o} ${s}`,bindings:[]}}else {if(n==="tinyint")return {sql:`${o} tinyint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} mediumint`,bindings:[]};if(n==="bigint"){let s="bigint";return e.autoIncrement&&(s+=" auto_increment"),{sql:`${o} ${s}`,bindings:[]}}else {if(n==="float")return {sql:`${o} float`,bindings:[]};if(n==="double")return {sql:`${o} double`,bindings:[]};if(n==="real")return {sql:`${o} double`,bindings:[]};if(n==="decimal"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} decimal(${s}, ${a})`,bindings:[]}}else if(n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`.trimEnd(),bindings:[]}}else if(n==="datetime"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} datetime${s}`.trimEnd(),bindings:[]}}else if(n==="timestamp"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${s}`.trimEnd(),bindings:[]}}else {if(n==="year")return {sql:`${o} year`,bindings:[]};if(n==="boolean")return {sql:`${o} boolean`,bindings:[]};if(n==="varbinary"){let s=e.length??255;return {sql:`${o} varbinary(${s})`,bindings:[]}}else if(n==="binary"){let s=e.length??255;return {sql:`${o} binary(${s})`,bindings:[]}}else {if(n==="bytea"||n==="blob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} json`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} enum(${s})`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}}}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Ua=new jo;var Uo=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},Wa=new Uo;var Wo=class{toSql(t){let e=t,r=new y(this.model);if(e.constraintType==="primary_key"){let o=(e.columns??[]).map(s=>r.formatStringColumn("mysql",w(s))).join(", ");return {sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}primary key (${o})`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns.map(s=>r.formatStringColumn("mysql",w(s))).join(", "),n=e.constraintName?`constraint \`${e.constraintName}\` `:"";return e.constraintName?{sql:`${n}unique (${o})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let o=e.defaultValue;return o instanceof v?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let o=(e.columns??[]).map(d=>r.formatStringColumn("mysql",w(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",w(d))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},Va=new Wo;var Vo=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:f}=n.parse([m]);if(m.folder==="constraint"){let g=s.pop()??"",h=p;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let N=`${g} ${h}`.trim();N=N.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(N),a.push(...f);continue}s.push(g),s.push(h),a.push(...f);continue}s.push(p),a.push(...f);}for(let m of e.namedConstraints){let{sql:p,bindings:f}=n.parse([m]);s.push(p),a.push(...f);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},Ha=new Vo;var Ho=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},Ja=new Ho;var Jo=class{toSql(t){return {sql:"distinct",bindings:[]}}},za=new Jo;var zo=class{toSql(t){return M.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},Ya=new zo;var Yo=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Ga=new Yo;var Go=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new y(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("mysql",e.table)} as \`${e.alias}\``,bindings:[]}:{sql:a.formatStringTable("mysql",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Za=new Go;var Zo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},Xa=new Zo;var Xo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof T)&&!Array.isArray(e.value)&&(o=`${new y(this.model).formatStringColumn("mysql",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},el=new Xo;var en=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table),n=e.columns.map(a=>`\`${a}\``).join(", ");return {sql:`${e.unique?"unique ":""}\`${e.indexName}\` on ${o} (${n})`,bindings:[]}}},tl=new en;var tn=class{toSql(t){let e=t;if(!e.table)throw new Error("MySQL DROP INDEX requires table name");return {sql:`\`${e.indexName}\` on \`${e.table}\``,bindings:[]}}},rl=new tn;var rn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("mysql",m)).join(", "),l=[],d=[];for(let m of e.records){let p=s.map(g=>m[g]);l.push(...p);let f=Array(s.length).fill("?").join(", ");d.push(`(${f})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},ol=new rn;var on=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("mysql",o),a=r.formatStringColumn("mysql",n);return {sql:`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},nl=new on;var nn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},sl=new nn;var um={for_update:"for update",for_share:"lock in share mode"},sn=class{toSql(t){let e=t,r=um[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},il=new sn;var an=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},al=new an;var ln=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model);if(e.mode==="ignore"){let n=e.conflictColumns?.[0]||"id",s=r.formatStringColumn("mysql",`${e.table}.${n}`);return {sql:`AS new ON DUPLICATE KEY UPDATE ${s} = ${s}`,bindings:[]}}return {sql:`AS new ON DUPLICATE KEY UPDATE ${e.columnsToUpdate.map(n=>`${r.formatStringColumn("mysql",n)} = new.${r.formatStringColumn("mysql",n)}`).join(", ")}`,bindings:[]}}},ll=new ln;var dn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("mysql",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},dl=new dn;var un=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},ul=new un;var mn=class{toSql(t){return {sql:`SELECT
|
|
12
51
|
k.CONSTRAINT_NAME AS name,
|
|
13
52
|
k.COLUMN_NAME AS column_name,
|
|
14
53
|
k.REFERENCED_TABLE_NAME AS referenced_table,
|
|
@@ -19,12 +58,12 @@ ${t}
|
|
|
19
58
|
JOIN information_schema.REFERENTIAL_CONSTRAINTS r
|
|
20
59
|
ON k.CONSTRAINT_NAME = r.CONSTRAINT_NAME AND k.CONSTRAINT_SCHEMA = r.CONSTRAINT_SCHEMA
|
|
21
60
|
WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
22
|
-
ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},
|
|
61
|
+
ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},ml=new mn;var cn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},cl=new cn;var pn=class{toSql(t){return {sql:`SELECT
|
|
23
62
|
CONSTRAINT_NAME AS name,
|
|
24
63
|
COLUMN_NAME AS column_name
|
|
25
64
|
FROM information_schema.KEY_COLUMN_USAGE k
|
|
26
65
|
WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.CONSTRAINT_NAME = 'PRIMARY'
|
|
27
|
-
ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},Mi=new yo;var fo=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default, CHARACTER_MAXIMUM_LENGTH AS char_length, NUMERIC_PRECISION AS numeric_precision, NUMERIC_SCALE AS numeric_scale FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${t.table}' ORDER BY ORDINAL_POSITION`,bindings:[]}}},Ni=new fo;var ho=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new f(this.model).formatStringColumn("mysql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new f(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},qi=new ho;var go=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new f(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},Ci=new go;var bo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Ri=new bo;var de=class extends b{constructor(e){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e;}};var To=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new f(this.model),o=r.getFromForWriteOperations("mysql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof de?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},_i=new To;var wo=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 f(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new f(this.model).formatStringColumn("mysql",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new f(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new f(this.model).formatStringColumn("mysql",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new f(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new f(this.model).formatStringColumn("mysql",t):t}},Oi=new wo;var So=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Di=new So;var Mo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new f(this.model).formatStringColumn("mysql",e.column);switch(e.jsonOperator){case "=":r=`${n} = CAST(? AS JSON)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},Ai=new Mo;var No=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 T(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},xi=new No;var qo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},Pi=new qo;var Co=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Ii=new Co;var Ro=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Bi=new Ro;var _o=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Ei=new _o;var Oo=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},vi=new Oo;var Do=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new T(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:y}=n.parse([m]);s.push(p.trim()),a.push(...y);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},$i=new Do;var Ao=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Ki=new Ao;var xo=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},ki=new xo;var Po=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Qi=new Po;var Io=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Fi=new Io;var Bo=class{toSql(t){return {sql:"",bindings:[]}}},Li=new Bo;var Eo=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},ji=new Eo;var vo=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Wi=new vo;var $o=class{toSql(t){let e=t,r=e.defaultValue;return r==="NULL"?r="null":r==="TRUE"||r==="FALSE"?r=r.toLowerCase():typeof r=="string"&&r!=="null"&&r!=="true"&&r!=="false"&&(r=`'${r}'`),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Ui=new $o;var Ko=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Vi=new Ko;var ko=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new f(this.model).formatStringColumn("postgres",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":" without time zone",a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${a}${s}`.trimEnd(),bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} text check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Hi=new ko;var Qo=class{toSql(t){return {sql:"",bindings:[]}}},Ji=new Qo;var Fo=class{toSql(t){let e=t,r=new f(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",w(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",w(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o==="NULL"?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:o===null?{sql:"default null",bindings:[]}:(typeof o=="string"&&(o=`'${o}'`),{sql:`default ${o}`,bindings:[]})}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("postgres",w(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("postgres",w(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},zi=new Fo;var Lo=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new T(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:y}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=p;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let S=`${h} ${g}`.trim();S=S.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(S),a.push(...y);continue}s.push(h),s.push(g),a.push(...y);continue}s.push(p),a.push(...y);}for(let m of e.namedConstraints){let{sql:p,bindings:y}=n.parse([m]);s.push(p),a.push(...y);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},Yi=new Lo;var jo=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new f(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Gi=new jo;var Wo=class{toSql(t){return {sql:"",bindings:[]}}},Zi=new Wo;var Uo=class{toSql(t){return {sql:`(${t.columns.map(o=>new f(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},Xi=new Uo;var Vo=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},ea=new Vo;var Ho=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new f(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new T(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},ta=new Ho;var Jo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new f(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},ra=new Jo;var zo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof b)&&!Array.isArray(e.value)&&(o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},oa=new zo;var Yo=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},na=new Yo;var Go=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},sa=new Go;var Zo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new f(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("postgres",p)).join(", "),l=[],d=[],u=e.currParamIndex;for(let p of e.records){let y=s.map(g=>p[g]);l.push(...y);let h=s.map((g,S)=>{let O=y[S];return `$${u++}${this.formatTypeCast(O)}`}).join(", ");d.push(`(${h})`);}let m=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let p=e.returning.map(y=>r.formatStringColumn("postgres",y)).join(", ");m+=` returning ${p}`;}else m+=" returning *";return {sql:m,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},ia=new Zo;var Xo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n);return {sql:`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},aa=new Xo;var en=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},la=new en;var Md={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},tn=class{toSql(t){let e=t,r=Md[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},da=new tn;var rn=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},ca=new rn;var on=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("postgres",a)).join(", ");if(e.mode==="ignore")return {sql:`on conflict (${o}) do nothing`,bindings:[]};let n=e.columnsToUpdate.map(a=>`${r.formatStringColumn("postgres",a)} = excluded.${r.formatStringColumn("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}else s+=" returning *";return {sql:s,bindings:[]}}},ua=new on;var nn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new f(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},ma=new nn;var sn=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},pa=new sn;var an=class{toSql(t){return {sql:`SELECT
|
|
66
|
+
ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},pl=new pn;var fn=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default, CHARACTER_MAXIMUM_LENGTH AS char_length, NUMERIC_PRECISION AS numeric_precision, NUMERIC_SCALE AS numeric_scale FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${t.table}' ORDER BY ORDINAL_POSITION`,bindings:[]}}},fl=new fn;var yn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("mysql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},yl=new yn;var hn=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("mysql",e.fromNode),bindings:[]}}},hl=new hn;var gn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},gl=new gn;var bn=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("mysql",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof v?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},bl=new bn;var Tn=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("mysql",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new y(this.model).formatStringColumn("mysql",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new y(this.model).formatStringColumn("mysql",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new y(this.model).formatStringColumn("mysql",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new y(this.model).formatStringColumn("mysql",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("mysql",t):t}},Tl=new Tn;var wn=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},wl=new wn;var Nn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new y(this.model).formatStringColumn("mysql",e.column);switch(e.jsonOperator){case "=":r=`${n} = CAST(? AS JSON)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`JSON_CONTAINS(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},Nl=new Nn;var Sn=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Sl=new Sn;var Mn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},Ml=new Mn;var qn=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},ql=new qn;var Cn=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Cl=new Cn;var Rn=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Rl=new Rn;var _n=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},_l=new _n;var On=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:f}=n.parse([m]);s.push(p.trim()),a.push(...f);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},Ol=new On;var An=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Al=new An;var Dn=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Dl=new Dn;var In=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Il=new In;var Pn=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Pl=new Pn;var xn=class{toSql(t){return {sql:"",bindings:[]}}},xl=new xn;var En=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},El=new En;var $n=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},$l=new $n;var Bn=class{toSql(t){let e=t,r;return e.defaultValue instanceof v?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Bl=new Bn;var vn=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},vl=new vn;var Kn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("postgres",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let s=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${s}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":" without time zone",a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${a}${s}`.trimEnd(),bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} text check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Kl=new Kn;var Qn=class{toSql(t){return {sql:"",bindings:[]}}},Ql=new Qn;var kn=class{toSql(t){let e=t,r=new y(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",w(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",w(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof v?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("postgres",w(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("postgres",w(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},kl=new kn;var Ln=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:f}=n.parse([m]);if(m.folder==="constraint"){let g=s.pop()??"",h=p;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let N=`${g} ${h}`.trim();N=N.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(N),a.push(...f);continue}s.push(g),s.push(h),a.push(...f);continue}s.push(p),a.push(...f);}for(let m of e.namedConstraints){let{sql:p,bindings:f}=n.parse([m]);s.push(p),a.push(...f);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},Ll=new Ln;var Fn=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Fl=new Fn;var jn=class{toSql(t){return {sql:"",bindings:[]}}},jl=new jn;var Un=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},Ul=new Un;var Wn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Wl=new Wn;var Vn=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new y(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Vl=new Vn;var Hn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Hl=new Hn;var Jn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof T)&&!Array.isArray(e.value)&&(o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Jl=new Jn;var zn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},zl=new zn;var Yn=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},Yl=new Yn;var Gn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(p=>r.formatStringColumn("postgres",p)).join(", "),l=[],d=[],u=e.currParamIndex;for(let p of e.records){let f=s.map(h=>p[h]);l.push(...f);let g=s.map((h,N)=>{let I=f[N];return `$${u++}${this.formatTypeCast(I)}`}).join(", ");d.push(`(${g})`);}let m=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let p=e.returning.map(f=>r.formatStringColumn("postgres",f)).join(", ");m+=` returning ${p}`;}else m+=" returning *";return {sql:m,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Gl=new Gn;var Zn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n);return {sql:`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},Zl=new Zn;var Xn=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},Xl=new Xn;var mm={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},es=class{toSql(t){let e=t,r=mm[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},ed=new es;var ts=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},td=new ts;var rs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("postgres",a)).join(", ");if(e.mode==="ignore")return {sql:`on conflict (${o}) do nothing`,bindings:[]};let n=e.columnsToUpdate.map(a=>`${r.formatStringColumn("postgres",a)} = excluded.${r.formatStringColumn("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}else s+=" returning *";return {sql:s,bindings:[]}}},rd=new rs;var os=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},od=new os;var ns=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},nd=new ns;var ss=class{toSql(t){return {sql:`SELECT
|
|
28
67
|
tc.constraint_name as name,
|
|
29
68
|
kcu.column_name as column_name,
|
|
30
69
|
ccu.table_name as referenced_table,
|
|
@@ -39,7 +78,7 @@ ${t}
|
|
|
39
78
|
JOIN information_schema.referential_constraints rc
|
|
40
79
|
ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema
|
|
41
80
|
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
|
|
42
|
-
ORDER BY kcu.ordinal_position`,bindings:[]}}},
|
|
81
|
+
ORDER BY kcu.ordinal_position`,bindings:[]}}},sd=new ss;var is=class{toSql(t){return {sql:`SELECT
|
|
43
82
|
i.relname as index_name,
|
|
44
83
|
a.attname as column_name,
|
|
45
84
|
ix.indisunique as is_unique
|
|
@@ -58,14 +97,14 @@ ${t}
|
|
|
58
97
|
AND t.relname = '${t.table}'
|
|
59
98
|
AND t.relnamespace = n.oid
|
|
60
99
|
AND n.nspname = current_schema()
|
|
61
|
-
AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},
|
|
100
|
+
AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},id=new is;var as=class{toSql(t){return {sql:`SELECT
|
|
62
101
|
tc.constraint_name as name,
|
|
63
102
|
kcu.column_name as column_name
|
|
64
103
|
FROM information_schema.table_constraints tc
|
|
65
104
|
JOIN information_schema.key_column_usage kcu
|
|
66
105
|
ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
|
|
67
106
|
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
|
|
68
|
-
ORDER BY kcu.ordinal_position`,bindings:[]}}},
|
|
107
|
+
ORDER BY kcu.ordinal_position`,bindings:[]}}},ad=new as;var ls=class{toSql(t){return {sql:`SELECT column_name,
|
|
69
108
|
data_type,
|
|
70
109
|
is_nullable,
|
|
71
110
|
column_default,
|
|
@@ -75,16 +114,20 @@ ${t}
|
|
|
75
114
|
FROM information_schema.columns
|
|
76
115
|
WHERE table_schema = current_schema()
|
|
77
116
|
AND table_name = '${t.table}'
|
|
78
|
-
ORDER BY ordinal_position`,bindings:[]}}},ga=new cn;var un=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new f(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new f(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},ba=new un;var mn=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new f(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Ta=new mn;var pn=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},wa=new pn;var yn=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new f(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let u=e.currParamIndex+d-n,m=e.values[d];return m instanceof de?(n++,`${r.formatStringColumn("postgres",l)} = ${m.rawValue}`):(s.push(m),`${r.formatStringColumn("postgres",l)} = $${u}${this.formatTypeCast(m)}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Sa=new yn;var fn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new f(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new f(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new f(this.model).formatStringColumn("postgres",t):t}},Ma=new fn;var hn=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Na=new hn;var gn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new f(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},qa=new gn;var bn=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 T(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Ca=new bn;var Tn=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},Ra=new Tn;var wn=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},_a=new wn;var Sn=class{toSql(t){return {sql:"",bindings:[]}}},Oa=new Sn;var Mn=class{toSql(t){return {sql:"",bindings:[]}}},Da=new Mn;var Nn=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new T(this.model,"sqlite"),s=[],a=[],l=false;for(let p of e.children){let{sql:y,bindings:h}=n.parse([p]);if(!(!y||!y.trim())){if(p.file==="add_column")s.push(y),l=true;else if(p.file==="add_constraint"&&l){let g=s.pop()??"",S=y.replace(/^\s*add\s+/i,"").trimStart();s.push(`${g} ${S}`);}else {if(p.file==="set_not_null"||p.file==="drop_not_null")continue;if(p.file==="set_default"||p.file==="drop_default")continue;s.push(y),l=false;}a.push(...h);}}let d=s.join(", "),u=e.ifExists?"if exists ":"";return d.trim()?{sql:`${u}${o} ${d}`,bindings:a}:{sql:"",bindings:[]}}},Aa=new Nn;var qn=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},xa=new qn;var Cn=class{toSql(t){return {sql:"",bindings:[]}}},Pa=new Cn;var Rn=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Ia=new Rn;var _n=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Ba=new _n;var On=class{toSql(t){return {sql:"",bindings:[]}}},Ea=new On;var Dn=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},va=new Dn;var An=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},$a=new An;var xn=class{toSql(t){let e=t,r=e.defaultValue;return r==="NULL"?r="null":r==="TRUE"||r==="FALSE"?r=r.toLowerCase():typeof r=="string"&&r!=="null"&&r!=="true"&&r!=="false"&&(r=`'${r}'`),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Ka=new xn;var Pn=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},ka=new Pn;var In=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new f(this.model).formatStringColumn("sqlite",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return {sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}return n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"?{sql:`${o} text`,bindings:[]}:n==="boolean"?{sql:`${o} integer`,bindings:[]}:n==="json"||n==="jsonb"?{sql:`${o} text`,bindings:[]}:n==="enum"?{sql:`${o} text`,bindings:[]}:n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob"?{sql:`${o} blob`,bindings:[]}:n==="integer"||n==="int"?e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]}:{sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Qa=new In;var Bn=class{toSql(t){return {sql:"",bindings:[]}}},Fa=new Bn;var En=class{toSql(t){let e=t,r=new f(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",w(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n==="NULL"?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:n===null?{sql:"default null",bindings:[]}:(typeof n=="string"&&(n=`'${n}'`),{sql:`default ${n}`,bindings:[]})}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(d=>r.formatStringColumn("sqlite",w(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",w(d))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},La=new En;var vn=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new T(this.model,"sqlite"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:y}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=p;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)||/primary key/i.test(g)){let S=`${h} ${g}`.trim();S=S.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(S),a.push(...y);continue}s.push(h),s.push(g),a.push(...y);continue}s.push(p),a.push(...y);}for(let m of e.namedConstraints){let{sql:p,bindings:y}=n.parse([m]);s.push(p),a.push(...y);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},ja=new vn;var $n=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new f(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},Wa=new $n;var Kn=class{toSql(t){return {sql:"distinct",bindings:[]}}},Ua=new Kn;var kn=class{toSql(t){return M.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Va=new kn;var Qn=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Ha=new Qn;var Fn=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new f(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new T(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Ja=new Fn;var Ln=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new f(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},za=new Ln;var jn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof b)&&!Array.isArray(e.value)&&(o=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Ya=new jn;var Wn=class{toSql(t){let e=t,o=new f(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Ga=new Wn;var Un=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},Za=new Un;var Vn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new f(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("sqlite",m)).join(", "),l=[],d=[];for(let m of e.records){let p=s.map(h=>m[h]);l.push(...p);let y=Array(s.length).fill("?").join(", ");d.push(`(${y})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Xa=new Vn;var Hn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n);return {sql:`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},el=new Hn;var Jn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},tl=new Jn;var zn=class{toSql(t){return {sql:"",bindings:[]}}},rl=new zn;var Yn=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},ol=new Yn;var Gn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new f(this.model),o=e.conflictColumns.map(s=>r.formatStringColumn("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumn("sqlite",s)} = EXCLUDED.${r.formatStringColumn("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},nl=new Gn;var Zn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new f(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},sl=new Zn;var Xn=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},il=new Xn;var es=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},al=new es;var ts=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},ll=new ts;var rs=class{toSql(t){return {sql:`SELECT
|
|
117
|
+
ORDER BY ordinal_position`,bindings:[]}}},ld=new ls;var ds=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},dd=new ds;var us=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},ud=new us;var ms=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},md=new ms;var cs=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("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((l,d)=>{let u=e.currParamIndex+d-n,m=e.values[d];return m instanceof v?(n++,`${r.formatStringColumn("postgres",l)} = ${m.rawValue}`):(s.push(m),`${r.formatStringColumn("postgres",l)} = $${u}${this.formatTypeCast(m)}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},cd=new cs;var ps=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new y(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new y(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("postgres",t):t}},pd=new ps;var fs=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},fd=new fs;var ys=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new y(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},yd=new ys;var hs=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},hd=new hs;var gs=class{toSql(t){let e=t,r=new b(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},gd=new gs;var bs=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},bd=new bs;var Ts=class{toSql(t){return {sql:"",bindings:[]}}},Td=new Ts;var ws=class{toSql(t){return {sql:"",bindings:[]}}},wd=new ws;var Ns=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[],l=false;for(let p of e.children){let{sql:f,bindings:g}=n.parse([p]);if(!(!f||!f.trim())){if(p.file==="add_column")s.push(f),l=true;else if(p.file==="add_constraint"&&l){let h=s.pop()??"",N=f.replace(/^\s*add\s+/i,"").trimStart();s.push(`${h} ${N}`);}else {if(p.file==="set_not_null"||p.file==="drop_not_null")continue;if(p.file==="set_default"||p.file==="drop_default")continue;s.push(f),l=false;}a.push(...g);}}let d=s.join(", "),u=e.ifExists?"if exists ":"";return d.trim()?{sql:`${u}${o} ${d}`,bindings:a}:{sql:"",bindings:[]}}},Nd=new Ns;var Ss=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Sd=new Ss;var Ms=class{toSql(t){return {sql:"",bindings:[]}}},Md=new Ms;var qs=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},qd=new qs;var Cs=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Cd=new Cs;var Rs=class{toSql(t){return {sql:"",bindings:[]}}},Rd=new Rs;var _s=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},_d=new _s;var Os=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Od=new Os;var As=class{toSql(t){let e=t,r;return e.defaultValue instanceof v?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Ad=new As;var Ds=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Dd=new Ds;var Is=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("sqlite",w(e.column)),n=e.dataType.toLowerCase();if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return {sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} numeric(${s}, ${a})`,bindings:[]}}return n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"?{sql:`${o} text`,bindings:[]}:n==="boolean"?{sql:`${o} integer`,bindings:[]}:n==="json"||n==="jsonb"?{sql:`${o} text`,bindings:[]}:n==="enum"?{sql:`${o} text`,bindings:[]}:n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob"?{sql:`${o} blob`,bindings:[]}:n==="integer"||n==="int"?e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]}:{sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Id=new Is;var Ps=class{toSql(t){return {sql:"",bindings:[]}}},Pd=new Ps;var xs=class{toSql(t){let e=t,r=new y(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",w(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof v?{sql:`default ${n.rawValue}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(d=>r.formatStringColumn("sqlite",w(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",w(d))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},xd=new xs;var Es=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"sqlite"),s=[],a=[];for(let m of e.children){let{sql:p,bindings:f}=n.parse([m]);if(m.folder==="constraint"){let g=s.pop()??"",h=p;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)||/primary key/i.test(h)){let N=`${g} ${h}`.trim();N=N.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(N),a.push(...f);continue}s.push(g),s.push(h),a.push(...f);continue}s.push(p),a.push(...f);}for(let m of e.namedConstraints){let{sql:p,bindings:f}=n.parse([m]);s.push(p),a.push(...f);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},Ed=new Es;var $s=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},$d=new $s;var Bs=class{toSql(t){return {sql:"distinct",bindings:[]}}},Bd=new Bs;var vs=class{toSql(t){return M.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},vd=new vs;var Ks=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Kd=new Ks;var Qs=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new y(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Qd=new Qs;var ks=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},kd=new ks;var Ls=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof T)&&!Array.isArray(e.value)&&(o=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Ld=new Ls;var Fs=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Fd=new Fs;var js=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},jd=new js;var Us=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("sqlite",m)).join(", "),l=[],d=[];for(let m of e.records){let p=s.map(g=>m[g]);l.push(...p);let f=Array(s.length).fill("?").join(", ");d.push(`(${f})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Ud=new Us;var Ws=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n);return {sql:`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},Wd=new Ws;var Vs=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},Vd=new Vs;var Hs=class{toSql(t){return {sql:"",bindings:[]}}},Hd=new Hs;var Js=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Jd=new Js;var zs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new y(this.model),o=e.conflictColumns.map(s=>r.formatStringColumn("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumn("sqlite",s)} = EXCLUDED.${r.formatStringColumn("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},zd=new zs;var Ys=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Yd=new Ys;var Gs=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Gd=new Gs;var Zs=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},Zd=new Zs;var Xs=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},Xd=new Xs;var ei=class{toSql(t){return {sql:`SELECT
|
|
79
118
|
'PRIMARY' as name,
|
|
80
119
|
name as column_name
|
|
81
120
|
FROM pragma_table_info('${t.table}')
|
|
82
121
|
WHERE pk > 0
|
|
83
|
-
ORDER BY pk`,bindings:[]}}},dl=new rs;var os=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},cl=new os;var ns=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new f(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 T(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 T(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 f(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},ul=new ns;var ss=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new f(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},ml=new ss;var is=class{toSql(t){let e=t,r=new T(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}}},pl=new is;var as=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new f(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 de?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},yl=new as;var ls=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 f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new f(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new f(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 f(this.model).formatStringColumn("sqlite",t):t}},fl=new ls;var ds=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},hl=new ds;var cs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new f(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}}},gl=new cs;var us=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 T(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 T(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},bl=new us;var ms=class{toSql(t){let e=t,r=new T(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}}},Tl=new ms;var wl={mysql:{alter_table:{add_column:ks,add_constraint:Qs,add_primary_key:Fs,alter_column_type:Ls,alter_table:js,drop_column:Ws,drop_constraint:Us,drop_default:Vs,drop_not_null:Hs,drop_primary_key:Js,rename_column:zs,rename_table:Ys,set_default:Gs,set_not_null:Zs},column:{column_type:Xs},constraint:{after:ei,constraint:ti},create_table:{create_table:ri},delete:{delete:oi},distinct:{distinct:ni,distinct_on:si},drop_table:{drop_table:ii},from:{from:ai},group_by:{group_by:li},having:{having:di},index_op:{create_index:ci,drop_index:ui},insert:{insert:mi},join:{join:pi},limit:{limit:yi},lock:{lock:fi},offset:{offset:hi},on_duplicate:{on_duplicate:gi},order_by:{order_by:bi},raw:{raw:Ti},schema:{foreign_key_info:wi,index_info:Si,primary_key_info:Mi,table_info:Ni},select:{select:qi},truncate:{truncate:Ci},union:{union:Ri},update:{update:_i},where:{where:Oi,where_group:Di,where_json:Ai,where_subquery:xi},with:{with:Pi}},postgres:{alter_table:{add_column:Ii,add_constraint:Bi,add_primary_key:Ei,alter_column_type:vi,alter_table:$i,drop_column:Ki,drop_constraint:ki,drop_default:Qi,drop_not_null:Fi,drop_primary_key:Li,rename_column:ji,rename_table:Wi,set_default:Ui,set_not_null:Vi},column:{column_type:Hi},constraint:{after:Ji,constraint:zi},create_table:{create_table:Yi},delete:{delete:Gi},distinct:{distinct:Zi,distinct_on:Xi},drop_table:{drop_table:ea},from:{from:ta},group_by:{group_by:ra},having:{having:oa},index_op:{create_index:na,drop_index:sa},insert:{insert:ia},join:{join:aa},limit:{limit:la},lock:{lock:da},offset:{offset:ca},on_duplicate:{on_duplicate:ua},order_by:{order_by:ma},raw:{raw:pa},schema:{foreign_key_info:ya,index_info:fa,primary_key_info:ha,table_info:ga},select:{select:ba},truncate:{truncate:Ta},union:{union:wa},update:{update:Sa},where:{where:Ma,where_group:Na,where_json:qa,where_subquery:Ca},with:{with:Ra}},sqlite:{alter_table:{add_column:_a,add_constraint:Oa,alter_column_type:Da,alter_table:Aa,drop_column:xa,drop_constraint:Pa,drop_default:Ia,drop_not_null:Ba,drop_primary_key:Ea,rename_column:va,rename_table:$a,set_default:Ka,set_not_null:ka},column:{column_type:Qa},constraint:{after:Fa,constraint:La},create_table:{create_table:ja},delete:{delete:Wa},distinct:{distinct:Ua,distinct_on:Va},drop_table:{drop_table:Ha},from:{from:Ja},group_by:{group_by:za},having:{having:Ya},index_op:{create_index:Ga,drop_index:Za},insert:{insert:Xa},join:{join:el},limit:{limit:tl},lock:{lock:rl},offset:{offset:ol},on_duplicate:{on_duplicate:nl},order_by:{order_by:sl},raw:{raw:il},schema:{foreign_key_info:al,index_info:ll,primary_key_info:dl,table_info:cl},select:{select:ul},truncate:{truncate:ml},union:{union:pl},update:{update:yl},where:{where:fl,where_group:hl,where_json:gl,where_subquery:bl},with:{with:Tl}}};var T=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(m=>!!m&&m.folder==="distinctOn"),n=!o&&t.find(m=>!!m&&m.folder==="distinct"),s=t.filter(m=>m!==null&&m.folder!=="distinct"&&m.folder!=="distinctOn"),a=[],l=[],d=null;for(let m=0;m<s.length;m++){let p=s[m];p.currParamIndex=e+l.length;let y=wl[this.mapCommonDbType(this.dbType)][p.folder][p.file];if(!y)throw new Error(`Interpreter not found for ${this.dbType} ${p.keyword}`);y.model=this.model;let h=y.toSql(p);if(!h.sql||!h.sql.trim().length)continue;let g=s[m+1],O=!g||g.keyword!==p.keyword?"":g.chainsWith;if(p.folder==="lock"||p.folder==="on_duplicate"||p.folder==="schema"){a.push(`${h.sql}${O}`),l.push(...h.bindings),d=p.keyword;continue}if(d!==p.keyword||p.canKeywordBeSeenMultipleTimes){if(r)a.push(`${h.sql}${O}`);else {let v=p.keyword;if(p.folder==="with"){let H=m,X=false;for(;H<s.length&&s[H].keyword===p.keyword;){let W=s[H];if(W.folder==="with"&&W.clause==="recursive"){X=true;break}H++;}X&&(v=`${v} recursive`);}if(v==="select")if(o){let H=Array.isArray(o.columns)?o.columns.join(", "):"";a.push(`select distinct on (${H}) ${h.sql}${O}`);}else n?a.push(`select distinct ${h.sql}${O}`):a.push(`select ${h.sql}${O}`);else a.push(`${v} ${h.sql}${O}`);}d=p.keyword;}else a.push(`${h.sql}${O}`);l.push(...h.bindings);}return {sql:a.join(" "),bindings:l}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}};var Tt=class extends b{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var wt=class extends b{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var St=class extends b{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Mt=class extends b{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Nt=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ce=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var Qe=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var qt=class extends b{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 be=class extends b{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 Ct=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var ue=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var Ye=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Rt=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var Fe=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var _t=class extends b{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Ot=class extends b{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var Dt=class extends b{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var At=class extends b{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var F=class extends b{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 xt=class extends b{constructor(e,r=[],o=[],n=false){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;}};var Pt=class extends b{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 It=class extends b{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 Bt=class extends b{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 me=class extends b{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Et=Symbol("columns"),vt=Symbol("primaryKey"),te=Symbol("relations"),$t=Symbol("indexes"),Kt=Symbol("uniques"),Me=i=>`${Nd__default.default.singular(i)}_id`,kt=(i,t)=>`idx_${i}_${t}`,ee=(i,t)=>`uq_${i}_${t}`,L=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,Ne=(i,t)=>`pk_${i}_${t}`;var A=class extends b{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.isRawValue=o.isRawValue??false;}};var Ge=class extends b{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 De=class extends b{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 Le=class extends b{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 qe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Qt=class extends b{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Ft=class extends qe{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=Ne(this.tableName,w(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new F("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new F("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??L(this.tableName??"",w(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new F("foreign_key",{columns:[w(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new F("foreign_key",{columns:[w(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 F("not_null",{columns:[w(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new F("null",{columns:[w(this.columnNode.column)]})),this}default(t){let e;return t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new F("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new F("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??ee(this.tableName??"",w(this.columnNode.column))})),this):(this.namedConstraints.push(new F("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName||ee(this.tableName??"",w(this.columnNode.column))})),this)}after(t){return this.nodes.push(new Qt(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new F("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ae=class extends qe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}build(e){return this.nodes.push(e),new Ft(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}char(e,r=1){let o=new A(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new A(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new A(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 A(e,"uuid");return this.build(r)}ulid(e){let r=new A(e,"ulid");return this.build(r)}integer(e,r=255){let o=new A(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new A(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new A(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new A(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new A(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new A(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new A(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new A(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new A(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new A(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 A(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new A(e,"time",{precision:r});return this.build(o)}year(e){let r=new A(e,"year");return this.build(r)}datetime(e,r){let o=new A(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new A(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new A(e,"boolean");return this.build(r)}binary(e){let r=new A(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new A(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new A(e,"blob");return this.build(r)}tinyblob(e){let r=new A(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new A(e,"mediumblob");return this.build(r)}longblob(e){let r=new A(e,"longblob");return this.build(r)}json(e){let r=new A(e,"json");return this.build(r)}jsonb(e){let r=new A(e,"jsonb");return this.build(r)}enum(e,r){let o=new A(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new A(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new A(e,"",{isRawValue:true});return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Lt=class extends qe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}addColumn(t){let e=[],r=new Ae(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 p=m;return p.constraintType==="not_null"||p.constraintType==="null"||p.constraintType==="default"}),d=new Nt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(m=>{let p=m;return p.constraintType==="unique"||p.constraintType==="foreign_key"||p.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new ce(m));});}alterColumn(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ae(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=w(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");this.nodes.push(new qt(w(a),s,{})),u&&(u.constraintType==="not_null"?this.nodes.push(new At(w(a))):u.constraintType==="null"&&this.nodes.push(new Rt(w(a)))),m&&(m.defaultValue===void 0||m.defaultValue===null?this.nodes.push(new Ye(w(a))):this.nodes.push(new Dt(w(a),m.defaultValue))),o.getNodes().forEach(p=>{let y=p;switch(y.constraintType){case "primary_key":this.addPrimaryKey(w(a));break;case "unique":this.unique(w(a),{constraintName:y.constraintName});break;case "foreign_key":this.foreignKey(w(a),y.references?.table??"",w(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ct(t));}renameColumn(t,e){this.nodes.push(new _t(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Ye(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Qe([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new F(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new F("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??L(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(new F("unique",{columns:[t],constraintName:e?.constraintName??ee(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=L(this.table,t,e);this.nodes.push(new ue(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new c("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ee(this.table,t);this.nodes.push(new ue(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new c("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new Fe(t));}};var re=class{constructor(t){if(this.sqlType=t||N.DB_TYPE,!this.sqlType)throw new c("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!Sl__default.default.existsSync(t))throw new c("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=ct__default.default.basename(t),r=ct__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new c("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=Sl__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 Ae(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new T({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new xt(t,n,o.getNamedConstraints(),r?.ifNotExists),l=s.parse([a]).sql,d=l.startsWith("create table")?l:`create table ${l}`;this.rawQuery(d);}alterTable(t,e){let r=[],o=new Lt(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 l=new be(t,s),d=n.parse([l]).sql;if(!d||!d.trim())return;let u=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(u),s=[];};for(let l of r)l.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(l);a();}dropTable(t,e=false){let r=new Pt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new be(t,[new Ot(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new me(t),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||kt(t,e.join("_")),n=new It(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Bt(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new Qe(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??ee(t,o.join("_")),s=new F("unique",{columns:o,constraintName:n}),a=new be(t,[new ce(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=L(t,e,r),n=new ue(o),s=new be(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)?ee(t,e.join("_")):ee(t,e),n=r?.constraintName??o,s=new ue(n),a=new be(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new Fe,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new F(...e),o=new be(t,[new ce(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new ue(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new T(t,this.sqlType)}};var jt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels);}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.alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}):[]}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,e=>{e.dropPrimaryKey();})}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);})}generateDropColumnSql(t){return this.sql.alterTable(t.table,e=>{e.dropColumn(t.column);})}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Wt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels),this.dropResolver=new jt(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.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);}});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.alterTable(o.table,s=>{s.dropConstraint(o.name);});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 re(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||Ne(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let u=a||Ne(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});});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.alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});});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=w(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=w(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,L(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=w(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||Ne(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.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});})}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.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});})}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 re(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=w(t.relation.manyToManyOptions.throughModel),r=w(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=w(r);if(t.relation.type==="belongsTo"){let p=t.relation.model(),y=p.primaryKey,g=p.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=p?.databaseCaseConvention||"preserve";n=P(y,S);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let p=t.relation.model();if(typeof n=="string"&&n){let y=p.getColumns(),h=y.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=p.primaryKey||"id",S=y.find(O=>O.columnName===g);if(S)n=S.databaseName;else {let O=p?.databaseCaseConvention||"preserve";n=P(n||g,O);}}}else {let y=p.primaryKey||"id",g=p.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=p?.databaseCaseConvention||"preserve";n=P(y,S);}}}let s=this.models.find(p=>p.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(p=>p.columnName===l);if(d)l=d.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=P(l,p);}if(t.relation.type==="belongsTo"){let p=a.find(y=>y.columnName===t.relation.foreignKey);if(p)l=p.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=P(t.relation.foreignKey,y);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let p=t.relation.manyToManyOptions.leftForeignKey,y=w(p),h=a.find(g=>g.columnName===y);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=P(y,g);}}let u=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,p=>{let y=o||L(t.table,l,e);p.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:y,onDelete:u,onUpdate:m});})}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 Rd(i){return i.replace(/\s+/g," ").trim()}function _d(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ce(i,t){let e=Rd(t.toLowerCase()),r=_d(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.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 "tinyint";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 "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 "character varying":return "varchar";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}}default:return r}}var Ut=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.registeredModels),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(d=>d?.type!==void 0&&d?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});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 d=r.getUniques?.()||[];for(let u of d)e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});for(let u of n.relations){if(u.type!=="belongsTo")continue;let m=w(u.constraintName);o.foreignKeys.find(y=>y.name===m)||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}return}for(let d of n.columns)o.columns.some(m=>m.name===d.databaseName||m.name===d.columnName)||e.data.columnsToAdd.push({table:r.table,column:d});for(let d of o.columns)n.columns.some(m=>m.databaseName===d.name||m.columnName===d.name)||e.data.columnsToDrop.push({table:r.table,column:d.name});for(let d of n.indexes)o.indexes.map(u=>u.name).includes(d.name)||e.data.indexesToAdd.push({table:r.table,index:d.name});let s=r.getUniques?.()||[];for(let d of s)o.indexes.some(m=>m.name===d.name&&m.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:d.name||"mandatory",columns:d.columns});for(let d of o.indexes)d.isUnique||n.indexes.map(m=>m.name).includes(d.name)||e.data.indexesToDrop.push({table:r.table,index:d.name});for(let d of o.indexes){if(!d.isUnique)continue;(r.getUniques?.()||[]).map(m=>m.name).includes(d.name)||e.data.uniquesToDrop.push({table:r.table,name:d.name});}for(let d of n.columns){let u=o.columns.find(y=>y.name===d.databaseName||y.name===d.columnName);if(!u)continue;let m=!e.areColumnsEqual(u,d,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:u,modelColumn:d});(m||p)&&e.data.columnsToModify.push({table:r.table,dbColumns:u,modelColumn:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;if(d.type==="manyToMany"&&d.manyToManyOptions){let p=w(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:w(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?w(d.constraintName):L(p,w(d.manyToManyOptions.leftForeignKey||Me(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let u=w(d.constraintName);if(u&&o.foreignKeys.some(p=>p.name===u))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,d,p))||e.data.relationsToAdd.push({table:r.table,relation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let a=new Set(n.relations.filter(d=>d.type==="belongsTo").map(d=>{let u=w(d.foreignKey)||d.columnName,p=r.getColumns().find(y=>y.columnName===u)?.databaseName||u;return w(d.constraintName)||L(r.table,p,d.model().table)}));for(let d of o.foreignKeys){if(d.name&&a.has(d.name))continue;n.relations.find(m=>m.type!=="belongsTo"&&m.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,m,d))||e.data.relationsToDrop.push({table:r.table,relation:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;let u=o.foreignKeys.find(m=>e.relationMatchesDbRelation(r,d,m));u&&!e.areRelationsEqual(u,d)&&e.data.relationsToModify.push({table:r.table,dbRelation:u,modelRelation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let l=r.primaryKey;if(l&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[l]}),o.primaryKey&&!l&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),l&&o.primaryKey){let d=r.getColumns().find(u=>u.columnName===l);d&&!e.arePrimaryKeysEqual(o.primaryKey,d)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:l});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat()}getSqlStatementsByPhase(){let t=new Wt(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=Ce(n,t.dataType),a=typeof e.type=="string"?Ce(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")&&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=w(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),p=d.table,y=m?.databaseName||u;o=o&&t.referencedTable===p&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===y;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=w(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?w(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=w(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),u=(n.type||"belongsTo")==="belongsTo"?w(n.foreignKey):n.columnName,m=l.find(g=>g.columnName===u);m&&(u=m.databaseName);let p=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===p)?.databaseName||p;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=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&n}getDefaultChange(t){let e=this.sql.getDbType(),r=Ce(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ce(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||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 n=t.modelColumn.constraints?.default!==void 0,s=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(n&&!s)return "set";if(!n&&s)return "drop";if(n&&s){let a=String(t.dbColumns.defaultValue),l=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,a),u=this.normalizeDefaultValue(e,o||r,l);return d!==u?"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=w(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(x=>x.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",u=s.getColumns().find(x=>x.columnName===l),m=a.getColumns().find(x=>x.columnName===d);if(!u||!m)continue;let p=w(o.manyToManyOptions.leftForeignKey)||l,y=w(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,p),this.clonePkAsColumn(m,y)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:p,rightFkName:y,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(u,p),S=this.clonePkAsColumn(m,y),O=h.columns.find(x=>x.name===p),v=h.columns.find(x=>x.name===y),H=O?this.areColumnsEqual(O,g,h.indexes):false,X=v?this.areColumnsEqual(v,S,h.indexes):false;for(let x of h.foreignKeys){let he=x.referencedTable===s.table,Tr=x.referencedTable===a.table;if(!he&&!Tr)continue;let Ul=he?p:y,Ve=x.columns[0];Ve&&Ve!==Ul&&(this.data.relationsToDrop.push({table:n,relation:x}),Ve!==p&&Ve!==y&&this.data.columnsToDrop.push({table:n,column:Ve}));}let W={};H||(W[g.databaseName]=g),X||(W[S.databaseName]=W[S.databaseName]||S);for(let x of Object.keys(W))this.data.columnsToAdd.push({table:n,column:W[x]});let ie=this.buildBelongsToRelation(n,()=>s,p,l,void 0,o.onDelete,o.onUpdate),C=this.buildBelongsToRelation(n,o.model,y,d,void 0,o.onDelete,o.onUpdate),ve=h.foreignKeys.find(x=>x.referencedTable===s.table&&x.columns.length===1&&x.columns[0]===p),ut=h.foreignKeys.find(x=>x.referencedTable===a.table&&x.columns.length===1&&x.columns[0]===y);if(!ve){let x=h.foreignKeys.find(he=>he.referencedTable===s.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(ie);}if(!ut){let x=h.foreignKeys.find(he=>he.referencedTable===a.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(C);}}}}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(p=>p.columnName===l)?.databaseName||l,m=w(a.constraintName)||L(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(S=>S.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(S=>S.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 S=g.primaryKey||"id";u=g.getColumns().find(v=>v.columnName===S)?.databaseName||S;}let m=new Set([l,o.relation.columnName].filter(Boolean)),p=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let S=m.has(g.columns[0]),O=g.referencedTable===d,v=g.referencedColumns[0]===u;return S&&O&&v}),y=w(o.relation.constraintName)||L(o.table,l,d),h=e.get(o.table)||new Set;if(p||y&&h.has(y))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=w(o.relation.manyToManyOptions.throughModel),S=w(o.relation.manyToManyOptions.leftForeignKey),O=w(o.relation.manyToManyOptions.rightForeignKey),v=o.table===g&&o.relation.columnName===S&&o.relation.model().table===s?.table,H=o.table===g&&o.relation.columnName===O&&o.relation.model().table!==s?.table,X=await this.sql.getTableSchema(g),W=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===S&&C.referencedTable===(s?.table||"")),ie=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===O&&C.referencedTable===o.relation.model().table);if(v&&W||H&&ie)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(S=>S.columnName===d.foreignKey)?.databaseName||d.foreignKey,p=d.model(),y=p.primaryKey||"id",g=p.getColumns().find(S=>S.columnName===y)?.databaseName||y;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===p.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){return {columnName:e,databaseName:e,isPrimary:false,type:t.type,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?w(n):L(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 pe=class extends b{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var $=class extends b{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var k=class extends b{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 oe=class extends b{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 z=class extends b{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 D=class extends b{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 Ze=class extends b{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var Y=class extends D{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 we=class extends b{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 Vt=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);});}},ql=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool("sqlite");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,p)=>{m&&u(m),(!p||!p.length)&&d([]),d(p);});});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,p)=>{n.run(i,t,function(y){if(y)return p(y);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 p(new c("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let S=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(S,[g],(O,v)=>{if(O)return p(O);m(v);});});});if(!Array.isArray(r.models))throw new c("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models,u=[];return new Promise(async(m,p)=>{try{let y=d.map(async h=>{let g=new f(s),{columns:S,values:O}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),v=Object.fromEntries(S.map((ie,C)=>[ie,O[C]])),H=new T(s,e.getDbType()),{sql:X,bindings:W}=H.parse([new k(new $(s.table),[v])]);return new Promise((ie,C)=>{n.run(X,W,function(ve){if(ve)return C(ve);let ut=h[a]||this.lastID;if(!a){ie(h);return}if(!ut)return C(new c("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let x=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(x,[ut],(he,Tr)=>{if(he)return C(he);ie(Tr);});});})});u=await Promise.all(y),m(u);}catch(y){p(y);}})}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="raw",o)=>{let n=e.type;switch(o?.shouldNotLog||Je(i,e.logs,t),n){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool("mysql"),[a]=await ps(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="affectedRows"?a.affectedRows:a;case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool("postgres"),d=await ps(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?d.rows:d.rowCount;case "sqlite":let u=await ps(()=>ql(i,t,e,{typeofModel:o?.sqlLiteOptions?.typeofModel,mode:o?.sqlLiteOptions?.mode||"fetch",models:o?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?Array.isArray(u)?u:[u]:u;default:throw new c("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${n}`)}},Ht=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool("mysql"),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,p=false,y=false,h=()=>{try{a.release();}catch{}};return u.on("data",g=>{if(o.onData){m++,Promise.resolve(o.onData(l,g)).then(()=>{m--,p&&m===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(),l.destroy(S);});return}l.write(g);}),u.on("end",()=>{p=true,m===0&&!y&&(h(),l.end());}),u.on("error",g=>{y=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),l}case "cockroachdb":case "postgres":{let s=e.sqlConnection??await e.getPool("postgres").connect(),a=await import('pg-query-stream').catch(()=>{throw new B("pg-query-stream")}),l=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=new a.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),u=s.query(d),m=0,p=false,y=false,h=g=>{try{s.release(g);}catch{}};return u.on("data",g=>{if(o.onData){m++,Promise.resolve(o.onData(l,g)).then(()=>{m--,p&&m===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(S),l.destroy(S);});return}l.write(g);}),u.on("end",()=>{p=true,m===0&&!y&&(h(),l.end());}),u.on("error",g=>{y=true,h(g),l.destroy(g);}),l}case "sqlite":{let s=e.sqlConnection??e.getPool("sqlite");return new Vt(s,i,t,{onData:o.onData})}default:throw new c("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function ps(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++,Es(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var E=(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 J=class extends b{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 Xe=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Jt(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 c("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function zt(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 Rl(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var je=i=>typeof i=="number"?i:parseFloat(i);var xe=class extends b{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 Yt=class extends b{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Gt=class extends b{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var G=class extends b{constructor(e,r,o,n="inner",s,a=false){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;}};var et=class extends b{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 Zt=class extends b{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Xt=class extends b{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var tt=class extends b{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 er=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 et(e));}),this}groupByRaw(t){return this.groupByNodes.push(new et(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 Zt(t),this}offset(t){return typeof t!="number"&&M.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Xt(t),this}};var tr=class extends er{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new G(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new G(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new G(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new G(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new G(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new G(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,n,s),this}join(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"inner",{operator:s||"="})),this}leftJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"left",{operator:s||"="})),this}rightJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"right",{operator:s||"="})),this}fullJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var rr=class extends tr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.modelAnnotatedColumns=[];this.dbType=r.getDbType(),this.fromNode=new $(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],e.map(o=>P(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new J(o));}),this}selectRaw(e){return this.selectNodes.push(new J(e,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new $(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes.push(new J(s,a,n)),this.modelAnnotatedColumns.push(a),this}from(e){return this.fromNode=new $(e),this}table(e){return this.fromNode=new $(e),this}distinct(){return this.distinctNode=new Yt,this}distinctOn(...e){return this.distinctOnNode=new Gt(e),this}};var or=class extends rr{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof R&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||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 R&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new D(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 R&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new D(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new D(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new D(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 R&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new D(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 D(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new D(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 D(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new D(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 D(e,"and",false,"in",r)),this):(this.whereNodes.push(new D("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new D(e,"or",false,"in",r)),this):(this.whereNodes.push(new D("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 D(e,"and",true,"in",r)),this):(this.whereNodes.push(new D("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new D(e,"or",true,"in",r)),this):(this.whereNodes.push(new D("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new D(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new D(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new D(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new D(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 D(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 D(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new D(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new D(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new D(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new D(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new D(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 xe(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 xe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new xe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new xe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof R)return e;let r=new R(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"or");return this.whereNodes.push(o),this}};var nr=class extends or{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new Y(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new Y(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new Y(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new Y(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new Y(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new Y(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new Y(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new Y(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new Y(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new Y(t,"or",false,"raw",e)),this}};var R=class i extends nr{constructor(e,r=ne.getInstance()){super(e,r);this.isNestedCondition=false;this.mustRemoveAnnotations=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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 T(this.model,this.dbType),this.interpreterUtils=new f(this.model);}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return j(e,r,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}})}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 first(){return this.one()}async oneOrFail(){let e=await this.one();if(!e)throw new c("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return await Ht(r,o,this.sqlDataSource,e,{onData:(s,a)=>{s.write(a);}})}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:Rl(e,a),data:s},{key:r.discriminator,value:d}]}selectSubQuery(e,r){if(typeof e=="function"){let o=new i(this.model,this.sqlDataSource);return e(o),this.selectNodes.push(new J(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new J(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new Ge("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Ge("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new De(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new De(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o,true)),this}async increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}async decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.annotate("count",e,"total");let r=await this.one();return r?je(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?je(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?je(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?je(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?je(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,s]=await Promise.all([this.limit(r).offset((e-1)*r).many(),o.getCount("*")]);return {paginationMetadata:zt(e,r,s),data:n}}from(e,r){if(typeof e=="function"){if(!r)throw new c("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new $(n,r),this}return this.fromNode=new $(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 Le("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 Le("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new c("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 Le("materialized",e,n)),this}async insert(e,r){let{columns:o,values:n}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),s=Object.fromEntries(o.map((u,m)=>[u,n[m]]));this.insertNode=new k(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(d)&&d.length?d[0]:d}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async a=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(a),Object.values(a),"insert");return Object.fromEntries(l.map((u,m)=>[u,d[m]]))}));this.insertNode=new k(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]);return j(n,s,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:o}})}async upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(a.map((y,h)=>[y,l[h]])),{sql:u,bindings:m}=this.astParser.parse([new k(new $(this.model.table),[d],void 0,true),new oe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await j(u,m,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(p)?p:[p]}async upsertMany(e,r,o,n={updateOnConflict:true}){let s=[];await Promise.all(o.map(async u=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(u),Object.values(u),"insert"),y=Object.fromEntries(m.map((h,g)=>[h,p[g]]));s.push(y);}));let{sql:a,bindings:l}=this.astParser.parse([new k(new $(this.model.table),s,void 0,true),new oe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(d)?d:[d]}async update(e){let r=Object.keys(e),o=Object.values(e),{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new me(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]);await j(e,r,this.sqlDataSource,"raw");}async delete(){this.deleteNode=new pe(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]);return j(e,r,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=ae()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ks(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new J("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=gt(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=K(this.modelSelectedColumns),e.modelAnnotatedColumns=K(this.modelAnnotatedColumns),e.distinctNode=K(this.distinctNode),e.distinctOnNode=K(this.distinctOnNode),e.selectNodes=K(this.selectNodes),e.withQuery=K(this.withQuery),e.joinNodes=K(this.joinNodes),e.whereNodes=K(this.whereNodes),e.groupByNodes=K(this.groupByNodes),e.havingNodes=K(this.havingNodes),e.orderByNodes=K(this.orderByNodes),e.lockQueryNodes=K(this.lockQueryNodes),e.unionNodes=K(this.unionNodes),e.withNodes=K(this.withNodes),e.fromNode=K(this.fromNode),e.limitNode=K(this.limitNode),e.offsetNode=K(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e.mustRemoveAnnotations=this.mustRemoveAnnotations,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 J("*")]),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 E(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await E(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstWithPerformance(e="millis"){return this.oneWithPerformance(e)}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await E(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await E(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await E(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await E(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await E(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var We=class i extends R{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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 Xe(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 first(e){return this.one(e)}async oneOrFail(e){let r=await this.one(e);if(!r)throw new c(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async firstOrFail(e){return this.oneOrFail(e)}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 le(o,this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);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}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();return await Ht(r,o,this.sqlDataSource,e,{onData:async(s,a)=>{let l=this.addAdditionalColumnsToModel(a,this.model),d=await le([l],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),s.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new c(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}async insert(...e){return this.model.insert(...e)}async insertMany(...e){return this.model.insertMany(...e)}async update(e,r={}){return r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),super.update(e)}async softDelete(e={}){let{ignoreBeforeUpdateHook:r=false}=e||{};return !r&&await this.model.beforeUpdate?.(this),super.softDelete(e)}async delete(e={}){return e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),super.delete()}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("count",e,"total");let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("max",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("min",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("avg",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("sum",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),[s,a]=await Promise.all([this.limit(r).offset((e-1)*r).many({ignoreHooks:o.ignoreHooks?["beforeFetch","afterFetch"]:[]}),n.getCount("*",{ignoreHooks:o.ignoreHooks})]);return {paginationMetadata:zt(e,r,a),data:s}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new J(r))),this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes=this.selectNodes.concat(new J(s,a,n)),this.modelAnnotatedColumns.push(a),this}removeAnnotations(){return this.mustRemoveAnnotations=true,this.modelAnnotatedColumns=[],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=K(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 c(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(p=>{let y=p[e.foreignKey];y&&n.set(String(y),p);}),r.forEach(p=>{let y=p[this.model.primaryKey];if(!y){p[e.columnName]=null;return}let h=n.get(String(y));p[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(p=>{if(!e.model.primaryKey)throw new c(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let y=p[e.model.primaryKey];y&&s.set(String(y),p);}),r.forEach(p=>{let y=p[e.foreignKey];if(!y){p[e.columnName]=null;return}let h=s.get(String(y));p[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new c(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(p=>{let y=p[e.foreignKey];if(!y)return;let h=String(y);a.has(h)||a.set(h,[]),a.get(h).push(p);}),r.forEach(p=>{let y=p[this.model.primaryKey];if(!y){p[e.columnName]=[];return}let h=a.get(String(y))||[];p[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new c(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)||P(u,this.model.modelCaseConvention);o.forEach(p=>{let y=p.$annotations||{},h=y[m];if(h==null)return;let g=String(h);d.has(g)||d.set(g,[]),this.modelAnnotatedColumns.includes(m)||(delete y[m],Object.keys(y).length||delete p.$annotations),d.get(g).push(p);}),r.forEach(p=>{let y=p[this.model.primaryKey];if(!y){p[e.columnName]=[];return}let h=d.get(String(y))||[];p[e.columnName]=h;});break;default:throw new c(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=ge__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,u=e.orderByNodes.map(C=>C.isRawValue?C.column:`${this.interpreterUtils.formatStringColumn(this.dbType,C.column)} ${C.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(d,C=>C.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 p=e.modelSelectedColumns.map(C=>Cr(C,d,e.model.table));return m.select(...p).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new c(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let y=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,S=e.modelSelectedColumns.length?e.modelSelectedColumns.map(C=>C.includes(".")?C:`${r.model.table}.${C}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,y.leftForeignKey).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n);let O=ge__default.default.randomBytes(6).toString("hex"),v=`${r.model.table}_cte_${O}`,H=e.orderByNodes.map(C=>{if(C.isRawValue)return C.column;let ve=C.column.includes(".")?C.column:`${r.model.table}.${C.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,ve)} ${C.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let X=`${ge__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,W=e.with(v,C=>C.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,X).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${y.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,y.leftForeignKey)} ORDER BY ${H}) as rn_${O}`).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n));h&&W.whereRaw(`rn_${O} <= ${h+(g||0)}`),g&&W.whereRaw(`rn_${O} > ${g}`);let ie=S.map(C=>Cr(C,v,e.model.table));return W.select(...ie).annotate(`${v}.${X}`,y.leftForeignKey).from(v);default:throw new c(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new c(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 c(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new c(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new f(r.model),a=new f(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new c(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 c(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 c(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(y=>!y.isRawValue&&y.table===d.throughModel&&y.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let m=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),p=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${p}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new c(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={},n={};return Object.entries(e).forEach(([s,a])=>{if(s==="$annotations"||this.modelColumnsDatabaseNames.get(s)){o[s]=a;return}n[P(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await E(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await E(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await E(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async firstWithPerformance(e={},r="millis"){return this.oneWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await E(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 E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await E(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var sr=class extends We{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new k(this.fromNode,[o],r?.returning),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new k(this.fromNode,o,r?.returning),this}update(...t){let[e]=t;return this.updateNode=new z(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=ae()}=e||{};return this.updateNode=new z(this.fromNode,[r],[o]),this}};function _l(i){let t=i.name,e=P(t,"snake");return Nd__default.default(e)}function Ol(){return {}}var rt=class{constructor(t,e){this.model=t,this.modelInstance=Ol(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new T(this.model,this.sqlType),this.interpreterUtils=new f(this.model);}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&&Object.entries(t.where).forEach(([r,o])=>{if(Array.isArray(o)){e.whereIn(r,o);return}e.where(r,o);}),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 c(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new c(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}async insert(t,e={}){!e.ignoreHooks&&await this.model.beforeInsert?.(t);let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),n={};r.forEach((m,p)=>{let y=o[p];n[m]=y,t[m]??(t[m]=y);});let{sql:s,bindings:a}=this.astParser.parse([new k(new $(this.model.table),[n],e.returning)]),l=await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(l,[t],"one",e.returning);let d=l[0];return d?(await this.model.afterFetch?.([d]),await le([d],this.model)):t}async insertMany(t,e={}){let r=[];await this.model.beforeInsertMany?.(t);for(let d of t){let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),p={};u.forEach((y,h)=>{let g=m[h];p[y]=g,d[y]??(d[y]=g);}),r.push(p);}let{sql:o,bindings:n}=this.astParser.parse([new k(new $(this.model.table),r,e.returning)]),s=await j(o,n,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(s,t,"many",e.returning)||[];let a=s;return a.length?(await this.model.afterFetch?.(a),await le(a,this.model)||[]):[]}async upsertMany(t,e,r,o={updateOnConflict:true}){let n=[];await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async d=>{let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),p=Object.fromEntries(u.map((y,h)=>[y,m[h]]));n.push(p);}));let{sql:s,bindings:a}=this.astParser.parse([new k(new $(this.model.table),n,void 0,true),new oe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})}async updateRecord(t,e){let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"update"),{primaryKey:n}=this.model;if(!n)throw new c(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");r=r.filter(d=>d!==n),o=o.filter(d=>d!==t[n]);let{sql:s,bindings:a}=this.astParser.parse([new z(new $(this.model.table),r,o),new D(n,"and",false,"=",t[n])]);await j(s,a,this.sqlDataSource,"raw");let l=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!l)throw new c(this.model.name+"::updateRecord","ROW_NOT_FOUND");return l}async deleteRecord(t){if(!this.model.primaryKey)throw new c(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new D(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new pe(new $(this.model.table)),e]);await j(r,o,this.sqlDataSource,"raw");}query(){return new We(this.model,this.sqlDataSource)}dryQuery(){return new sr(this.model,this.sqlDataSource)}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await le([a],this.model):null}return await le(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}};var ot=class extends R{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new k(this.fromNode,[o],r),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new k(this.fromNode,o,r),this}upsert(...t){let[e,r,o]=t,n=Object.keys(e),s=Object.keys(r);return this.insertNode=new k(new $(this.model.table),[e],void 0,true),this.onDuplicateNode=new oe(this.model.table,s,n,o?.updateOnConflict??true?"update":"ignore",o?.returning),this}upsertMany(...t){let[e,r,o,n]=t,s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new k(new $(this.model.table),s,void 0,true),this.onDuplicateNode=new oe(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new z(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=ae()}=t||{};return this.updateNode=new z(this.fromNode,[e],[r]),this}};var nt=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??ae()});var ye=class{constructor(t){this.options=t;}static async createDriver(t){throw new c("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var ir=class i extends ye{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){let e=await import('mongodb').catch(()=>{throw new B("mongodb")});if(!e)throw new B("mongodb");return new i(e)}};var ar=class i extends ye{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){let e=await import('mysql2/promise').catch(()=>{throw new B("mysql2")});if(!e)throw new B("mysql");return new i(e.default)}};var lr=class i extends ye{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){let e=await import('pg').catch(()=>{throw new B("pg")});if(!e)throw new B("pg");return new i(e.default)}};var dr=class i extends ye{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){let e=await import('sqlite3').catch(()=>{throw new B("sqlite3")});if(!e)throw new B("sqlite3");return new i(e.default)}};var Pe=class{static async getDriver(t){switch(t){case "mysql":case "mariadb":return ar.createDriver();case "postgres":case "cockroachdb":return lr.createDriver();case "sqlite":return dr.createDriver();case "mongo":return ir.createDriver();default:throw new c(`DriverFactory::getDriver Driver ${t} not found, il likely not installed, try running npm install ${t}`,"DRIVER_NOT_FOUND")}}};var Ad=async i=>(await Pe.getDriver(i)).client,st=async(i,t)=>{let e=await Ad(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,y=>{if(y)throw new c("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});default:throw new c("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var it=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=ge__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.startTransaction(),t)try{await t(e),await e.commit();}catch(r){throw await e.rollback(),r}return e}async startTransaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mysql":case "mariadb":case "postgres":case "cockroachdb":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 "mysql":case "mariadb":t&&await this.sql.rawQuery(t),await this.sql.sqlConnection.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}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new c("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 "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 "mysql":case "mariadb":await this.sql.sqlConnection.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("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 c("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 "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new c("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mysql":case "mariadb":await this.sql.sqlConnection.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;default:throw new c("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 "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;default:throw new c("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){M.error(t);}await this.sql.closeConnection(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel)return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new c("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==="sqlite")return "";throw new c("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var se=class se extends $e{constructor(e){super(e);this.globalTransaction=null;this.models={};this.ownsPool=false;this.sqlConnection=null;this.cacheAdapter=new ft;this.cacheKeys={};this.sqlType=this.type,this.inputDetails=e||{connectionPolicies:{retry:{maxRetries:0,delay:0}},queryFormatOptions:{language:ht(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"}},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:ht(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs;}static async connect(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e?.models||{});Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async connectToSecondarySource(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async useConnection(e,r){let o=new se(e);if(e.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}o.models=e.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:e.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1");try{await r(o).then(async()=>{o.isConnected&&await o.closeConnection();});}catch(n){throw o.isConnected&&await o.closeConnection(),n}}static getInstance(){if(!se.instance)throw new c("SqlDataSource::getInstance","CONNECTION_NOT_ESTABLISHED");return se.instance}static query(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new R(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static dryQuery(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new ot(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static createTable(...e){return this.getInstance().createTable(...e)}static alterTable(...e){return this.getInstance().alterTable(...e)}static async startGlobalTransaction(e){return this.getInstance().startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.getInstance().commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.getInstance().rollbackGlobalTransaction();}static async startTransaction(e,r){return this.getInstance().startTransaction(e,r)}static async transaction(e,r){let o=typeof e=="function"?r:e;return this.getInstance().startTransaction(e,o)}static async getTableSchema(e){return this.getInstance().getTableSchema(e)}static async closeConnection(){if(!this.instance){M.warn("Connection already closed");return}await this.instance.closeConnection(),this.instance=null;}static async disconnect(){return this.closeConnection()}static async rawQuery(e,r=[]){let o=this.getInstance();return (o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o).rawQuery(e,r)}static rawStatement(e){return this.getInstance().rawStatement(e)}static async initializeAdminJs(){return this.getInstance().initializeAdminJs()}static async initializeAdminJsExpress(){return this.getInstance().initializeAdminJsExpress()}static getAdminJs(){return this.instance?.getAdminJs()}static isAdminJsEnabled(){return this.instance?.isAdminJsEnabled()??false}async useCache(e,r,...o){if(!this.cacheAdapter)throw new c("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new c("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),a||(l=void 0,d=r!==void 0?[r,...o]:o);let u=Or(JSON.stringify(d)),m=u?`${e}:${u}`:e,p=await this.cacheAdapter.get(m);if(p!==void 0)return p;let y=await n(...d);return await this.cacheAdapter.set(m,y,l),y}async invalidCache(e,...r){if(!this.cacheAdapter)throw new c("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=Or(JSON.stringify(r)),n=o?`${e}:${o}`:e;await this.cacheAdapter.invalidate(n);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async clone(e){let r=new se(this.inputDetails);if(r.sqlType==="sqlite"||!!e?.shouldRecreatePool){if(r.sqlPool=await st(r.sqlType,{type:r.sqlType,host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,connectionPolicies:r.inputDetails.connectionPolicies,queryFormatOptions:r.inputDetails.queryFormatOptions,driverOptions:r.inputDetails.driverOptions,logs:r.logs,models:r.models}),r.ownsPool=true,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}if(r.sqlPool=this.sqlPool,r.ownsPool=false,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}getDbType(){return this.type}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new R(nt(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new ot(nt(e,r),this)}alterTable(...e){let r=new re(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new re(this.getDbType());return r.createTable(...e),r.queryStatements[0]||""}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new it(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new c("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 startTransaction(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 it(n,o?.isolationLevel);if(await s.startTransaction(),typeof e=="function")try{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}async transaction(e,r){return this.startTransaction(e,r)}getModelManager(e){if(!this.isConnected)throw new c("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new rt(e,this.globalTransaction.sql):new rt(e,this)}getPool(e=this.sqlType){if(!this.sqlPool)throw new c("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(e=this.sqlType){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new c("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;default:throw new c("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){Je("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::closeConnection - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),Je("Closing connection",this.logs),this.type){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;default:throw new c("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}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 disconnect(){return this.closeConnection()}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 Ut.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`);}async rawQuery(e,r=[]){if(!this.isConnected)throw new c("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let o=gt(this,e);return j(o,r,this,"raw")}rawStatement(e){return new de(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 Bs(Object.values(this.models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new c("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Rr(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new c("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await Is(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Mt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(ze(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=Ce(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=Ce(s,d),m=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,p=typeof m=="string"?m.toLowerCase()!=="no":typeof m=="boolean"?m:a.notnull!==void 0?a.notnull===0:true,y=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,S=a.numeric_scale!=null?Number(a.numeric_scale):null,O=a.timezone!=null?!!a.timezone:typeof a.datetime_precision=="number"?/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase()):/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase());return {name:l,dataType:u,isNullable:p,defaultValue:y,length:h,precision:g,scale:S,withTimezone:O}})}async getIndexInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new wt(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(ze(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,p=l.get(u)||{name:u,columns:[],isUnique:m};p.columns.push(d.Column_name),l.set(u,p);}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,p=l.get(u)||{name:u,columns:[],isUnique:m};p.columns.push(d.column_name),l.set(u,p);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,p=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(y=>y.name);a.push({name:d,columns:p,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Tt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(ze(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 T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new St(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(ze(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 testConnectionQuery(e){await j(e,[],this,"raw",{shouldNotLog:true});}sanitizeModelKeys(e){let r=Object.getOwnPropertyNames(this),o=Object.getOwnPropertyNames(this.constructor),n=[...r,...o];if(Object.keys(e).some(s=>n.includes(s)))throw new c("SqlDataSource::sanitizeModelKeys","DUPLICATE_MODEL_KEYS_WHILE_INSTANTIATING_MODELS",new Error(`Duplicate model keys while instantiating models inside the connection: ${Object.keys(e).filter(s=>n.includes(s)).map(s=>`"${s}"`).join(", ")}`));return e}static get isInGlobalTransaction(){return !!this.instance?.globalTransaction}get isInGlobalTransaction(){return !!this.globalTransaction}get registeredModels(){return this.models}};se.instance=null;var ne=se;var Dl=["postgres","cockroachdb"];var at=class at extends Se{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:_l(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return El(this)}constructor(){super();}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static dryQuery(t){return this.dispatchModelManager(t).dryQuery()}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);return a||null}static async insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async insertMany(t,e={}){return t.length?this.dispatchModelManager(e).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=Jt(s).find(h=>h.columnName===t);if(!l)throw new c(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new c(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=P(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),u=P(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 p extends at{static get table(){return l.throughModel}}p.databaseCaseConvention="preserve",p.modelCaseConvention="preserve",await p.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 c&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new c(`${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);return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),a=Object.keys(t).length>0?await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t}):null;return a?(e[o.primaryKey]=a[o.primaryKey],r.updateOnConflict?await n.updateRecord(e,{returning:r.returning}):a):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);if(!e.every(m=>{let p=new Set(Object.keys(m));return t.every(y=>p.has(y))}))throw new c("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let s=Object.keys(e[0]),a=await n.upsertMany(t,s,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true}),l=o.sqlInstance.getDbType();if(Dl.includes(l))return await le(a,o,r.returning);let d=n.query();r.returning?.length&&d.select(...r.returning);let u=new Map;return t.forEach(m=>{e.forEach(p=>{u.set(m,[...u.get(m)||[],p[m]]);});}),d.where(m=>{t.forEach(p=>{m.orWhereIn(p,u.get(p)||[]);});}),d.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(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 Bl(this)}static getIndexes(){return vl(this)}static getUniques(){return $l(this)}static column(t,...e){_(...e)(this.prototype,t);}static hasOne(t,...e){xl(...e)(this.prototype,t);}static hasMany(t,...e){Pl(...e)(this.prototype,t);}static belongsTo(t,...e){Al(...e)(this.prototype,t);}static manyToMany(t,...e){Il(...e)(this.prototype,t);}static establishConnection(){let t=ne.getInstance();if(!t)throw new c("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){if(t?.connection)return t.connection.getModelManager(this);if(t?.trx)return t.trx.sql.getModelManager(this);let e=this;return e.establishConnection(),e.sqlInstance.getModelManager(e)}mergeProps(t){this.constructor.combineProps(this,t);}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{},a=e,l=await r.upsert(s,a,{updateOnConflict:true,...t});return r.combineProps(this,l),this}async update(t,e={}){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new c(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new c(o.name+"::update","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.updateRecord(r,t,e);}async softDelete(t,e){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new c(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new c(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.softDelete(r,t,e);}async delete(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new c(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await r.deleteRecord(this,t);}async refresh(t){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new c(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};at.softDeleteColumn="deletedAt",at.softDeleteValue=ae();var Z=at;var fe=class{constructor(t,e){this.model=Z;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var cr=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var ur=class extends fe{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var mr=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var pr=class extends fe{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 xR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=I.getMetadata($t,e.prototype)||[];o.push({columns:r,name:t??kt(e.table,r.join("_"))}),I.defineMetadata($t,o,e.prototype);}}function PR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=I.getMetadata(Kt,e.prototype)||[];o.push({columns:r,name:t??ee(e.table,r.join("_"))}),I.defineMetadata(Kt,o,e.prototype);}}function IR(i){return t=>{let e=t,r=e.query;e.query=function(...o){let n=r.bind(this).call(this,...o);return i(n),n};}}function _(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(I.getMetadata(vt,e))throw new c("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");I.defineMetadata(vt,r,e);}let n=i.databaseName??P(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??Ne(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=I.getMetadata(Et,e)||[];a.push(s),I.defineMetadata(Et,a,e);}}_.primary=Id;_.date=jd;_.boolean=Ld;_.json=Wd;_.uuid=Kd;_.ulid=kd;_.integer=Ed;_.float=Bd;_.increment=vd;_.bigIncrement=$d;_.encryption={symmetric:Qd,asymmetric:Fd};function Id(i={}){return _({...i,primaryKey:true})}function Bd(i={}){return _({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)}})}function Ed(i={}){return _({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function vd(i={}){return _({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function $d(i={}){return _({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function Kd(i={}){return _({type:"uuid",...i,prepare:t=>t||ge__default.default.randomUUID()})}function kd(i={}){return _({type:"ulid",...i,prepare:t=>t||As()})}function Qd(i){return _({...i,prepare:t=>t&&Rs(i.key,t),serialize:t=>t&&_s(i.key,t)})}function Fd(i){return _({...i,prepare:t=>t&&Os(i.publicKey,t),serialize:t=>t&&Ds(i.privateKey,t)})}function Ld(i={}){return _({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function jd(i={}){let{format:t="ISO",timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i;return _({type:"datetime",...n,autoUpdate:r,prepare:s=>s?r?mt(new Date,t,e):typeof s=="string"?s:mt(s,t,e):o?mt(new Date,t,e):null,serialize:s=>{if(s!==void 0)return s===null?null:Cs(s,t,e)}})}function Wd(i={}){return _({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function bt(i){try{return I.getMetadata(Et,i.prototype)||[]}catch{return []}}function Al(i,t,e){return (r,o)=>{let n=()=>Me(i().table),s=()=>{let d=r.constructor.table,u=t||n();return L(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=I.getMetadata(te,r)||[];l.push(a),I.defineMetadata(te,l,r);}}function xl(i,t){return (e,r)=>{let o=()=>Me(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=I.getMetadata(te,e)||[];s.push(n),I.defineMetadata(te,s,e);}}function Pl(i,t){return (e,r)=>{let o=()=>Me(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=I.getMetadata(te,e)||[];s.push(n),I.defineMetadata(te,s,e);}}function Il(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=()=>Me(u),p=()=>Me(i().table),y=()=>L(w(d),s?String(s):m()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??y,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):p,wasModelProvided:l}},g=I.getMetadata(te,o)||[];g.push(h),I.defineMetadata(te,g,o);}}function Bl(i){return I.getMetadata(te,i.prototype)||[]}function Jt(i){return (I.getMetadata(te,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=w(s),l=o();switch(r){case "belongsTo":return new cr(l,n,a);case "hasOne":return new mr(l,n,a);case "hasMany":return new ur(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new c("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new pr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:w(e.manyToManyOptions.throughModel),leftForeignKey:w(e.manyToManyOptions.leftForeignKey),rightForeignKey:w(e.manyToManyOptions.rightForeignKey)});default:throw new c("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function El(i){return I.getMetadata(vt,i.prototype)}function vl(i){return I.getMetadata($t,i.prototype)||[]}function $l(i){return I.getMetadata(Kt,i.prototype)||[]}var fs=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){let e=this.typeofModel;if(t===1)return e.insert(this.modelData);let r=Array.from({length:t});return e.insertMany(r.map(()=>({...this.modelData})))}},Ud=(i,t)=>new fs(i,t);var lt=class extends Z{};U([_.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"createdAt"),U([_.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"updatedAt"),U([_.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"deletedAt");var hs=class extends Z{};U([_.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],hs.prototype,"id");var gs=class extends Z{};U([_.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],gs.prototype,"id");var Ie=class extends Z{};U([_.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Ie.prototype,"id"),U([_({type:"varchar",length:255,openApi:{type:"string",required:true}})],Ie.prototype,"email"),U([_.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ie.prototype,"createdAt"),U([_.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ie.prototype,"updatedAt"),U([_.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ie.prototype,"deletedAt");var Kl=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 B("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);}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:Hd}=Nd__default.default;function kl(i){let t=i.name,e=P(t,"snake");return Hd(e)}function Ql(){return {$annotations:{}}}var Ue=class extends Se{static get collection(){return this._collection||kl(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=dt.getInstance();if(!t)throw new c("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){Sr()(this.prototype,t);}static async afterFetch(t){return t}};U([Sr()],Ue.prototype,"id");async function Re(i,t,e){if(!t)return null;let r=Ql(),o=qs(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=P(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=P(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=P(n,i.modelCaseConvention);r[s]=null;}})),r}async function yr(i,t,e){return (await Promise.all(t.map(async o=>await Re(i,o,e)))).filter(o=>o!==null)}var fr=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,limit:1,session:this.session}),o=await Re(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 c("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 yr(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 Re(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 yr(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 yr(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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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=V("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 hr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=Ue,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 c("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new fr(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 Re(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 Re(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new c("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 c("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Re(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new c("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 Be=class Be extends $e{constructor(t,e){super({type:"mongo"}),this.url=t,this.isConnected=false,this.mongoClient=e;}getCurrentConnection(){return this.mongoClient}static async connect(t,e,r){if(!t&&(t=N.MONGO_URL,!t))throw new c("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 o=(await Pe.getDriver("mongo")).client,n=new o.MongoClient(t,e);return await n.connect(),this.instance=new Be(t,n),this.instance.isConnected=true,this.instance.logs=e?.logs||N.MONGO_LOGS||false,await r?.(this.instance),this.instance}static getInstance(){if(!Be.instance)throw new c("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Be.instance}startSession(){let t=this.mongoClient.startSession();return t.startTransaction(),t}static async disconnect(){if(!this.instance)throw new c("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(t,e){let r=(await Pe.getDriver("mongo")).client,o=new r.MongoClient(t.url,t.options);await o.connect();let n=new Be(t.url,o);await e(n),await o.close();}static query(t){return this.getInstance().query(t)}query(t){if(!this.isConnected)throw new c("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:t},this).query()}getModelManager(t,e,r){return new hr(t,e,r,this.logs)}};Be.instance=null;var dt=Be;var Q=class Q{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||+N.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new B("ioredis")});this.redisDataSourceInstance=new Q(new r.default({host:t?.host||N.REDIS_HOST,username:t?.username||N.REDIS_USERNAME,port:e,password:t?.password||N.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new c("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new B("ioredis")}),r=new e.default({host:t?.host||N.REDIS_HOST,username:t?.username||N.REDIS_USERNAME,port:t?.port||+N.REDIS_PORT||6379,password:t?.password||N.REDIS_PASSWORD,...t}),o=new Q(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 c("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new c("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new c("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 c("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new c("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new c("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new c("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 c("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Q.getValue(e)}catch{throw new c("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new c("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Q.getValue(e)}catch{throw new c("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new c("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new c("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new c("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 c("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 c("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new c("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new c("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 c("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new c("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 c("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 c("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Q.getValue(e)}catch{throw new c("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Q.getValue(e)}catch{throw new c("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Q.getValue(n)).filter(n=>n!==null)}catch{throw new c("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new c("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 c("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 c("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 c("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 c("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 c("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new c("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new c("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new c("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new c("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 c("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 c("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Q.getValue(r)}catch{throw new c("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]=Q.getValue(n);return r}catch{throw new c("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Q.getValue(o))}catch{throw new c("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new c("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new c("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new c("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new c("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 c("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 c("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 c("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 c("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new c("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 c("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 c("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 c("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 c("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new c("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 c("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 c("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new c("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new c("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new c("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new c("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 c("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 c("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 c("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 c("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 c("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new c("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 c("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=Q.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=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new c("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=Q.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=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new c("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 c("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 c("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new c("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 c("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new c("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 c("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 c("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new c("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new c("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new c("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 c("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 c("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new c("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new c("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new c("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new c("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new c("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new c("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new c("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new c("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new c("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new c("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new c("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new c("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new c("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new c("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new c("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new c("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new c("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new c("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new c("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new c("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new c("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)}};Q.OK="OK";var bs=Q;var Ts=class{constructor(t){this.dbType=t,this.migrationName=ct__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 re(this.dbType);}};async function Ll(i,t){let e=ct__default.default.isAbsolute(i)?i:ct__default.default.resolve(process.cwd(),i),{mod:r}=await bundleRequire.bundleRequire({filepath:e,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","reflect-metadata","pluralize","dayjs","async-mutex","commander"]});return r}var ws=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return Object.values(r).map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.map(n=>n.table_name);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
|
|
122
|
+
ORDER BY pk`,bindings:[]}}},eu=new ei;var ti=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},tu=new ti;var ri=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new 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}"`:""}},ru=new ri;var oi=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:[]}}},ou=new oi;var ni=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}}},nu=new ni;var si=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 v?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},su=new si;var ii=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}},iu=new ii;var ai=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}}},au=new ai;var li=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}}},lu=new li;var di=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}}},du=new di;var ui=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}}},uu=new ui;var mu={mssql:{alter_table:{add_column:Bi,add_constraint:vi,add_primary_key:Ki,alter_column_type:Qi,alter_table:ki,drop_column:Li,drop_constraint:Fi,drop_default:ji,drop_not_null:Ui,drop_primary_key:Wi,rename_column:Vi,rename_table:Hi,set_default:Ji,set_not_null:zi},column:{column_type:Yi},constraint:{after:Gi,constraint:Zi},create_table:{create_table:Xi},delete:{delete:ea},distinct:{distinct:ta,distinct_on:ra},drop_table:{drop_table:oa},from:{from:na},group_by:{group_by:sa},having:{having:ia},index_op:{create_index:aa,drop_index:la},insert:{insert:da},join:{join:ua},limit:{limit:ma},lock:{lock:ca},offset:{offset:pa},on_duplicate:{on_duplicate:fa},order_by:{order_by:ya},raw:{raw:ha},schema:{foreign_key_info:ga,index_info:ba,primary_key_info:Ta,table_info:wa},select:{select:Na},truncate:{truncate:Sa},union:{union:Ma},update:{update:qa},where:{where:Ca,where_group:Ra,where_json:_a,where_subquery:Oa},with:{with:Aa}},mysql:{alter_table:{add_column:Da,add_constraint:Ia,add_primary_key:Pa,alter_column_type:xa,alter_table:Ea,drop_column:$a,drop_constraint:Ba,drop_default:va,drop_not_null:Ka,drop_primary_key:Qa,rename_column:ka,rename_table:La,set_default:Fa,set_not_null:ja},column:{column_type:Ua},constraint:{after:Wa,constraint:Va},create_table:{create_table:Ha},delete:{delete:Ja},distinct:{distinct:za,distinct_on:Ya},drop_table:{drop_table:Ga},from:{from:Za},group_by:{group_by:Xa},having:{having:el},index_op:{create_index:tl,drop_index:rl},insert:{insert:ol},join:{join:nl},limit:{limit:sl},lock:{lock:il},offset:{offset:al},on_duplicate:{on_duplicate:ll},order_by:{order_by:dl},raw:{raw:ul},schema:{foreign_key_info:ml,index_info:cl,primary_key_info:pl,table_info:fl},select:{select:yl},truncate:{truncate:hl},union:{union:gl},update:{update:bl},where:{where:Tl,where_group:wl,where_json:Nl,where_subquery:Sl},with:{with:Ml}},postgres:{alter_table:{add_column:ql,add_constraint:Cl,add_primary_key:Rl,alter_column_type:_l,alter_table:Ol,drop_column:Al,drop_constraint:Dl,drop_default:Il,drop_not_null:Pl,drop_primary_key:xl,rename_column:El,rename_table:$l,set_default:Bl,set_not_null:vl},column:{column_type:Kl},constraint:{after:Ql,constraint:kl},create_table:{create_table:Ll},delete:{delete:Fl},distinct:{distinct:jl,distinct_on:Ul},drop_table:{drop_table:Wl},from:{from:Vl},group_by:{group_by:Hl},having:{having:Jl},index_op:{create_index:zl,drop_index:Yl},insert:{insert:Gl},join:{join:Zl},limit:{limit:Xl},lock:{lock:ed},offset:{offset:td},on_duplicate:{on_duplicate:rd},order_by:{order_by:od},raw:{raw:nd},schema:{foreign_key_info:sd,index_info:id,primary_key_info:ad,table_info:ld},select:{select:dd},truncate:{truncate:ud},union:{union:md},update:{update:cd},where:{where:pd,where_group:fd,where_json:yd,where_subquery:hd},with:{with:gd}},sqlite:{alter_table:{add_column:bd,add_constraint:Td,alter_column_type:wd,alter_table:Nd,drop_column:Sd,drop_constraint:Md,drop_default:qd,drop_not_null:Cd,drop_primary_key:Rd,rename_column:_d,rename_table:Od,set_default:Ad,set_not_null:Dd},column:{column_type:Id},constraint:{after:Pd,constraint:xd},create_table:{create_table:Ed},delete:{delete:$d},distinct:{distinct:Bd,distinct_on:vd},drop_table:{drop_table:Kd},from:{from:Qd},group_by:{group_by:kd},having:{having:Ld},index_op:{create_index:Fd,drop_index:jd},insert:{insert:Ud},join:{join:Wd},limit:{limit:Vd},lock:{lock:Hd},offset:{offset:Jd},on_duplicate:{on_duplicate:zd},order_by:{order_by:Yd},raw:{raw:Gd},schema:{foreign_key_info:Zd,index_info:Xd,primary_key_info:eu,table_info:tu},select:{select:ru},truncate:{truncate:ou},union:{union:nu},update:{update:su},where:{where:iu,where_group:au,where_json:lu,where_subquery:du},with:{with:uu}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(_=>!!_&&_.folder==="distinctOn"),n=!o&&t.find(_=>!!_&&_.folder==="distinct"),s=this.dbType==="mssql"?t.find(_=>!!_&&_.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(_=>_!==null&&_.folder!=="distinct"&&_.folder!=="distinctOn"),d=l.some(_=>_.folder==="offset"),u=l.some(_=>_.folder==="order_by"),m=l.find(_=>_.folder==="limit"),p=l.find(_=>_.folder==="offset"),f=this.dbType==="mssql"&&m&&!d&&!u,g=this.dbType==="mssql"&&!f&&(m||p),h=[],N=[],I=null;f&&m&&N.push(m.limit);for(let _=0;_<l.length;_++){let E=l[_];if(f&&E.folder==="limit"||g&&(E.folder==="limit"||E.folder==="offset"))continue;E.currParamIndex=e+N.length;let L=mu[this.mapCommonDbType(this.dbType)][E.folder][E.file];if(!L)throw new Error(`Interpreter not found for ${this.dbType} ${E.keyword}`);L.model=this.model;let C=L.toSql(E);if(!C.sql||!C.sql.trim().length)continue;let S=l[_+1],G=!S||S.keyword!==E.keyword?"":S.chainsWith;if(E.folder==="lock"||E.folder==="on_duplicate"||E.folder==="schema"){h.push(`${C.sql}${G}`),N.push(...C.bindings),I=E.keyword;continue}if(I!==E.keyword||E.canKeywordBeSeenMultipleTimes){if(r)h.push(`${C.sql}${G}`);else {let O=E.keyword;if(E.folder==="with"&&this.dbType!=="mssql"){let z=_,Ce=false;for(;z<l.length&&l[z].keyword===E.keyword;){let ft=l[z];if(ft.folder==="with"&&ft.clause==="recursive"){Ce=true;break}z++;}Ce&&(O=`${O} recursive`);}if(O==="select"){let z=f?`top (@${e}) `:"";if(o){let Ce=Array.isArray(o.columns)?o.columns.join(", "):"";h.push(`select ${z}distinct on (${Ce}) ${C.sql}${G}`);}else n?h.push(`select ${z}distinct ${C.sql}${G}`):h.push(`select ${z}${C.sql}${G}`);}else O==="from"&&a?h.push(`${O} ${C.sql}${a}${G}`):h.push(`${O} ${C.sql}${G}`);}I=E.keyword;}else h.push(`${C.sql}${G}`);N.push(...C.bindings);}if(g){u||h.push("order by (select null)");let _=p?.offset??0;N.push(_);let L=`offset @${e+N.length-1} rows`;if(m){N.push(m.limit);let C=e+N.length-1;L+=` fetch next @${C} rows only`;}h.push(L);}return {sql:h.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 St=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Mt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var qt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Ct=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Rt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ye=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var Ue=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var _t=class extends T{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 Ne=class extends T{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 Ot=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var he=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var Xe=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var At=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var We=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Dt=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var It=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Pt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var H=class extends T{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 xt=class extends T{constructor(e,r=[],o=[],n=false){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;}};var Et=class extends T{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 $t=class extends T{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 Bt=class extends T{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 ge=class extends T{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var vt=Symbol("columns"),Kt=Symbol("primaryKey"),ae=Symbol("relations"),Qt=Symbol("indexes"),kt=Symbol("uniques"),_e=i=>`${cm__default.default.singular(i)}_id`,Lt=(i,t)=>`idx_${i}_${t}`,se=(i,t)=>`uq_${i}_${t}`,J=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,Oe=(i,t)=>`pk_${i}_${t}`;var x=class extends T{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.isRawValue=o.isRawValue??false;}};var et=class extends T{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 Ee=class extends T{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 Ve=class extends T{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 Ae=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Ft=class extends T{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var jt=class extends Ae{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=Oe(this.tableName,w(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new H("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new H("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??J(this.tableName??"",w(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new H("foreign_key",{columns:[w(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new H("foreign_key",{columns:[w(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 H("not_null",{columns:[w(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new H("null",{columns:[w(this.columnNode.column)]})),this}default(t){let e;return t instanceof v?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new H("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new H("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??se(this.tableName??"",w(this.columnNode.column))})),this):(this.namedConstraints.push(new H("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName||se(this.tableName??"",w(this.columnNode.column))})),this)}after(t){return this.nodes.push(new Ft(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new H("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var $e=class extends Ae{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}build(e){return this.nodes.push(e),new jt(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}char(e,r=1){let o=new x(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new x(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new x(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 x(e,"uuid");return this.build(r)}ulid(e){let r=new x(e,"ulid");return this.build(r)}integer(e,r=255){let o=new x(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new x(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new x(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new x(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new x(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new x(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new x(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new x(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new x(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new x(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 x(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new x(e,"time",{precision:r});return this.build(o)}year(e){let r=new x(e,"year");return this.build(r)}datetime(e,r){let o=new x(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new x(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new x(e,"boolean");return this.build(r)}binary(e){let r=new x(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new x(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new x(e,"blob");return this.build(r)}tinyblob(e){let r=new x(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new x(e,"mediumblob");return this.build(r)}longblob(e){let r=new x(e,"longblob");return this.build(r)}json(e){let r=new x(e,"json");return this.build(r)}jsonb(e){let r=new x(e,"jsonb");return this.build(r)}enum(e,r){let o=new x(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new x(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new x(e,"",{isRawValue:true});return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Ut=class extends Ae{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}addColumn(t){let e=[],r=new $e(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 p=m;return p.constraintType==="not_null"||p.constraintType==="null"||p.constraintType==="default"}),d=new Rt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(m=>{let p=m;return p.constraintType==="unique"||p.constraintType==="foreign_key"||p.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new ye(m));});}alterColumn(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new $e(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=w(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");this.nodes.push(new _t(w(a),s,{})),u&&(u.constraintType==="not_null"?this.nodes.push(new Pt(w(a))):u.constraintType==="null"&&this.nodes.push(new At(w(a)))),m&&(m.defaultValue===void 0||m.defaultValue===null?this.nodes.push(new Xe(w(a))):this.nodes.push(new It(w(a),m.defaultValue))),o.getNodes().forEach(p=>{let f=p;switch(f.constraintType){case "primary_key":this.addPrimaryKey(w(a));break;case "unique":this.unique(w(a),{constraintName:f.constraintName});break;case "foreign_key":this.foreignKey(w(a),f.references?.table??"",w(f.references?.columns?.[0]??""),{constraintName:f.constraintName,onDelete:f.onDelete,onUpdate:f.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ot(t));}renameColumn(t,e){this.nodes.push(new Dt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Xe(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Ue([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ye(new H(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ye(new H("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??J(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ye(new H("unique",{columns:[t],constraintName:e?.constraintName??se(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=J(this.table,t,e);this.nodes.push(new he(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new c("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??se(this.table,t);this.nodes.push(new he(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new he(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new c("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new c("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new We(t));}};var le=class{constructor(t){if(this.sqlType=t||q.DB_TYPE,!this.sqlType)throw new c("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!cu__default.default.existsSync(t))throw new c("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=pt__default.default.basename(t),r=pt__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new c("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=cu__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 $e(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new xt(t,n,o.getNamedConstraints(),r?.ifNotExists),l=s.parse([a]).sql,d=l.startsWith("create table")?l:`create table ${l}`;this.rawQuery(d);}alterTable(t,e){let r=[],o=new Ut(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 l=new Ne(t,s),d=n.parse([l]).sql;if(!d||!d.trim())return;let u=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(u),s=[];};for(let l of r)l.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(l);a();}dropTable(t,e=false){let r=new Et(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new Ne(t,[new je(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new ge(t),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||Lt(t,e.join("_")),n=new $t(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Bt(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new Ue(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??se(t,o.join("_")),s=new H("unique",{columns:o,constraintName:n}),a=new Ne(t,[new ye(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=J(t,e,r),n=new he(o),s=new Ne(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)?se(t,e.join("_")):se(t,e),n=r?.constraintName??o,s=new he(n),a=new Ne(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new We,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new H(...e),o=new Ne(t,[new ye(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new he(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new b(t,this.sqlType)}};var Wt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels);}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.alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}):[]}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,e=>{e.dropPrimaryKey();})}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);})}generateDropColumnSql(t){return this.sql.alterTable(t.table,e=>{e.dropColumn(t.column);})}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Vt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels),this.dropResolver=new Wt(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.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);}});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.alterTable(o.table,s=>{s.dropConstraint(o.name);});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 le(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||Oe(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let u=a||Oe(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});});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.alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});});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=w(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=w(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,J(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=w(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||Oe(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.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});})}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.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});})}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 le(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=w(t.relation.manyToManyOptions.throughModel),r=w(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=w(r);if(t.relation.type==="belongsTo"){let p=t.relation.model(),f=p.primaryKey,h=p.getColumns().find(N=>N.columnName===f);if(h)n=h.databaseName;else {let N=p?.databaseCaseConvention||"preserve";n=$(f,N);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let p=t.relation.model();if(typeof n=="string"&&n){let f=p.getColumns(),g=f.find(h=>h.columnName===n);if(g)n=g.databaseName;else {let h=p.primaryKey||"id",N=f.find(I=>I.columnName===h);if(N)n=N.databaseName;else {let I=p?.databaseCaseConvention||"preserve";n=$(n||h,I);}}}else {let f=p.primaryKey||"id",h=p.getColumns().find(N=>N.columnName===f);if(h)n=h.databaseName;else {let N=p?.databaseCaseConvention||"preserve";n=$(f,N);}}}let s=this.models.find(p=>p.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(p=>p.columnName===l);if(d)l=d.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=$(l,p);}if(t.relation.type==="belongsTo"){let p=a.find(f=>f.columnName===t.relation.foreignKey);if(p)l=p.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=$(t.relation.foreignKey,f);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let p=t.relation.manyToManyOptions.leftForeignKey,f=w(p),g=a.find(h=>h.columnName===f);if(g)l=g.databaseName;else {let h=s?.databaseCaseConvention||"preserve";l=$(f,h);}}let u=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,p=>{let f=o||J(t.table,l,e);p.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:f,onDelete:u,onUpdate:m});})}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 ym(i){return i.replace(/\s+/g," ").trim()}function hm(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function De(i,t){let e=ym(t.toLowerCase()),r=hm(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.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 "tinyint";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 "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 "character varying":return "varchar";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 "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}}default:return r}}var Ht=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.registeredModels),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(d=>d?.type!==void 0&&d?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});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 d=r.getUniques?.()||[];for(let u of d)e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});for(let u of n.relations){if(u.type!=="belongsTo")continue;let m=w(u.constraintName);o.foreignKeys.find(f=>f.name===m)||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}return}for(let d of n.columns)o.columns.some(m=>m.name===d.databaseName||m.name===d.columnName)||e.data.columnsToAdd.push({table:r.table,column:d});for(let d of o.columns)n.columns.some(m=>m.databaseName===d.name||m.columnName===d.name)||e.data.columnsToDrop.push({table:r.table,column:d.name});for(let d of n.indexes)o.indexes.map(u=>u.name).includes(d.name)||e.data.indexesToAdd.push({table:r.table,index:d.name});let s=r.getUniques?.()||[];for(let d of s)o.indexes.some(m=>m.name===d.name&&m.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:d.name||"mandatory",columns:d.columns});for(let d of o.indexes)d.isUnique||n.indexes.map(m=>m.name).includes(d.name)||e.data.indexesToDrop.push({table:r.table,index:d.name});for(let d of o.indexes){if(!d.isUnique)continue;(r.getUniques?.()||[]).map(m=>m.name).includes(d.name)||e.data.uniquesToDrop.push({table:r.table,name:d.name});}for(let d of n.columns){let u=o.columns.find(f=>f.name===d.databaseName||f.name===d.columnName);if(!u)continue;let m=!e.areColumnsEqual(u,d,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:u,modelColumn:d});(m||p)&&e.data.columnsToModify.push({table:r.table,dbColumns:u,modelColumn:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;if(d.type==="manyToMany"&&d.manyToManyOptions){let p=w(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:w(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?w(d.constraintName):J(p,w(d.manyToManyOptions.leftForeignKey||_e(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let u=w(d.constraintName);if(u&&o.foreignKeys.some(p=>p.name===u))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,d,p))||e.data.relationsToAdd.push({table:r.table,relation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let a=new Set(n.relations.filter(d=>d.type==="belongsTo").map(d=>{let u=w(d.foreignKey)||d.columnName,p=r.getColumns().find(f=>f.columnName===u)?.databaseName||u;return w(d.constraintName)||J(r.table,p,d.model().table)}));for(let d of o.foreignKeys){if(d.name&&a.has(d.name))continue;n.relations.find(m=>m.type!=="belongsTo"&&m.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,m,d))||e.data.relationsToDrop.push({table:r.table,relation:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;let u=o.foreignKeys.find(m=>e.relationMatchesDbRelation(r,d,m));u&&!e.areRelationsEqual(u,d)&&e.data.relationsToModify.push({table:r.table,dbRelation:u,modelRelation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let l=r.primaryKey;if(l&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[l]}),o.primaryKey&&!l&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),l&&o.primaryKey){let d=r.getColumns().find(u=>u.columnName===l);d&&!e.arePrimaryKeysEqual(o.primaryKey,d)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:l});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat()}getSqlStatementsByPhase(){let t=new Vt(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=De(n,t.dataType),a=typeof e.type=="string"?De(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")&&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=w(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",m=d.getColumns().find(g=>g.columnName===u),p=d.table,f=m?.databaseName||u;o=o&&t.referencedTable===p&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===f;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=w(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 h=n.model();h&&h.table&&(o=h);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?w(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=w(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),u=(n.type||"belongsTo")==="belongsTo"?w(n.foreignKey):n.columnName,m=l.find(h=>h.columnName===u);m&&(u=m.databaseName);let p=o.primaryKey||"id",g=o.getColumns().find(h=>h.columnName===p)?.databaseName||p;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===g}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&n}getDefaultChange(t){let e=this.sql.getDbType(),r=De(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?De(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||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 n=t.modelColumn.constraints?.default!==void 0,s=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(n&&!s)return "set";if(!n&&s)return "drop";if(n&&s){let a=String(t.dbColumns.defaultValue),l=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,a),u=this.normalizeDefaultValue(e,o||r,l);return d!==u?"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=w(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(O=>O.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",u=s.getColumns().find(O=>O.columnName===l),m=a.getColumns().find(O=>O.columnName===d);if(!u||!m)continue;let p=w(o.manyToManyOptions.leftForeignKey)||l,f=w(o.manyToManyOptions.rightForeignKey)||d,g=await this.sql.getTableSchema(n);if(!g.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,p),this.clonePkAsColumn(m,f)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:p,rightFkName:f,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let h=this.clonePkAsColumn(u,p),N=this.clonePkAsColumn(m,f),I=g.columns.find(O=>O.name===p),Q=g.columns.find(O=>O.name===f),_=I?this.areColumnsEqual(I,h,g.indexes):false,E=Q?this.areColumnsEqual(Q,N,g.indexes):false;for(let O of g.foreignKeys){let z=O.referencedTable===s.table,Ce=O.referencedTable===a.table;if(!z&&!Ce)continue;let ft=z?p:f,Ye=O.columns[0];Ye&&Ye!==ft&&(this.data.relationsToDrop.push({table:n,relation:O}),Ye!==p&&Ye!==f&&this.data.columnsToDrop.push({table:n,column:Ye}));}let L={};_||(L[h.databaseName]=h),E||(L[N.databaseName]=L[N.databaseName]||N);for(let O of Object.keys(L))this.data.columnsToAdd.push({table:n,column:L[O]});let C=this.buildBelongsToRelation(n,()=>s,p,l,void 0,o.onDelete,o.onUpdate),S=this.buildBelongsToRelation(n,o.model,f,d,void 0,o.onDelete,o.onUpdate),ce=g.foreignKeys.find(O=>O.referencedTable===s.table&&O.columns.length===1&&O.columns[0]===p),G=g.foreignKeys.find(O=>O.referencedTable===a.table&&O.columns.length===1&&O.columns[0]===f);if(!ce){let O=g.foreignKeys.find(z=>z.referencedTable===s.table);O&&this.data.relationsToDrop.push({table:n,relation:O}),this.data.relationsToAdd.push(C);}if(!G){let O=g.foreignKeys.find(z=>z.referencedTable===a.table);O&&this.data.relationsToDrop.push({table:n,relation:O}),this.data.relationsToAdd.push(S);}}}}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(p=>p.columnName===l)?.databaseName||l,m=w(a.constraintName)||J(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(h=>h.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(N=>N.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(N=>N.columnName===l)?.databaseName||l;let d=o.table,u=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let h=o.relation.model();d=h.table;let N=h.primaryKey||"id";u=h.getColumns().find(Q=>Q.columnName===N)?.databaseName||N;}let m=new Set([l,o.relation.columnName].filter(Boolean)),p=n.foreignKeys.some(h=>{if(h.columns.length!==1||h.referencedColumns.length!==1)return false;let N=m.has(h.columns[0]),I=h.referencedTable===d,Q=h.referencedColumns[0]===u;return N&&I&&Q}),f=w(o.relation.constraintName)||J(o.table,l,d),g=e.get(o.table)||new Set;if(p||f&&g.has(f))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let h=w(o.relation.manyToManyOptions.throughModel),N=w(o.relation.manyToManyOptions.leftForeignKey),I=w(o.relation.manyToManyOptions.rightForeignKey),Q=o.table===h&&o.relation.columnName===N&&o.relation.model().table===s?.table,_=o.table===h&&o.relation.columnName===I&&o.relation.model().table!==s?.table,E=await this.sql.getTableSchema(h),L=E.foreignKeys.some(S=>S.columns.length===1&&S.columns[0]===N&&S.referencedTable===(s?.table||"")),C=E.foreignKeys.some(S=>S.columns.length===1&&S.columns[0]===I&&S.referencedTable===o.relation.model().table);if(Q&&L||_&&C)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(N=>N.columnName===d.foreignKey)?.databaseName||d.foreignKey,p=d.model(),f=p.primaryKey||"id",h=p.getColumns().find(N=>N.columnName===f)?.databaseName||f;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===p.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===h})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){return {columnName:e,databaseName:e,isPrimary:false,type:t.type,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?w(n):J(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 be=class extends T{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 T{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var U=class extends T{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 de=class extends T{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 ee=class extends T{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 P=class extends T{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 tt=class extends T{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var te=class extends P{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 Me=class extends T{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 Jt=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);});}},yu=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool("sqlite");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,p)=>{m&&u(m),(!p||!p.length)&&d([]),d(p);});});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,p)=>{n.run(i,t,function(f){if(f)return p(f);let g=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m(g);return}let h=g?.[a]||this.lastID;if(!h)return p(new c("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let N=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(N,[h],(I,Q)=>{if(I)return p(I);m(Q);});});});if(!Array.isArray(r.models))throw new c("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models,u=[];return new Promise(async(m,p)=>{try{let f=d.map(async g=>{let h=new y(s),{columns:N,values:I}=await h.prepareColumns(Object.keys(g),Object.values(g),"insert"),Q=Object.fromEntries(N.map((C,S)=>[C,I[S]])),_=new b(s,e.getDbType()),{sql:E,bindings:L}=_.parse([new U(new F(s.table),[Q])]);return new Promise((C,S)=>{n.run(E,L,function(ce){if(ce)return S(ce);let G=g[a]||this.lastID;if(!a){C(g);return}if(!G)return S(new c("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let O=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(O,[G],(z,Ce)=>{if(z)return S(z);C(Ce);});});})});u=await Promise.all(f),m(u);}catch(f){p(f);}})}return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.message)):d(this.changes);});})};var W=async(i,t,e,r="raw",o)=>{let n=e.type;switch(o?.shouldNotLog||ne(i,e.logs,t),n){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool("mysql"),[a]=await zt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="affectedRows"?a.affectedRows:a;case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool("postgres"),d=await zt(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?d.rows:d.rowCount;case "sqlite":let u=await zt(()=>yu(i,t,e,{typeofModel:o?.sqlLiteOptions?.typeofModel,mode:o?.sqlLiteOptions?.mode||"fetch",models:o?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?Array.isArray(u)?u:[u]:u;case "mssql":let m=e.sqlConnection?e.sqlConnection.request():e.getPool("mssql").request();t.forEach((h,N)=>{m.input(`p${N}`,h);});let p=0,f=i.replace(/\?|@(\d+)/g,()=>`@p${p++}`),g=await zt(()=>m.query(f),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="affectedRows"?g.rowsAffected[0]:g.recordset;default:throw new c("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${n}`)}},Yt=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool("mysql"),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,p=false,f=false,g=()=>{try{a.release();}catch{}};return u.on("data",h=>{if(o.onData){m++,Promise.resolve(o.onData(l,h)).then(()=>{m--,p&&m===0&&!f&&(g(),l.end());}).catch(N=>{f=true,g(),l.destroy(N);});return}l.write(h);}),u.on("end",()=>{p=true,m===0&&!f&&(g(),l.end());}),u.on("error",h=>{f=true,g(),l.destroy(h);}),l.on("close",()=>{g();}),l}case "cockroachdb":case "postgres":{let s=e.sqlConnection??await e.getPool("postgres").connect(),a=await import('pg-query-stream').catch(()=>{throw new B("pg-query-stream")}),l=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=new a.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),u=s.query(d),m=0,p=false,f=false,g=h=>{try{s.release(h);}catch{}};return u.on("data",h=>{if(o.onData){m++,Promise.resolve(o.onData(l,h)).then(()=>{m--,p&&m===0&&!f&&(g(),l.end());}).catch(N=>{f=true,g(N),l.destroy(N);});return}l.write(h);}),u.on("end",()=>{p=true,m===0&&!f&&(g(),l.end());}),u.on("error",h=>{f=true,g(h),l.destroy(h);}),l}case "sqlite":{let s=e.sqlConnection??e.getPool("sqlite");return new Jt(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool("mssql"),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((g,h)=>{l.input(`p${h}`,g);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),m=0,p=false,f=false;return l.on("row",g=>{if(!f){if(o.onData){m++,Promise.resolve(o.onData(a,g)).then(()=>{m--,p&&m===0&&!f&&a.end();}).catch(h=>{f=true,a.destroy(h);});return}a.write(g);}}),l.on("error",g=>{f=true,a.destroy(g);}),l.on("done",()=>{p=true,m===0&&!f&&a.end();}),l.query(u),a}default:throw new c("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function zt(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++,xi(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var k=(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 X=class extends T{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 rt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Gt(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 c("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Zt(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 hu(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var He=i=>typeof i=="number"?i:parseFloat(i);var Be=class extends T{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 Xt=class extends T{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var er=class extends T{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var re=class extends T{constructor(e,r,o,n="inner",s,a=false){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;}};var ot=class extends T{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 tr=class extends T{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var rr=class extends T{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var nt=class extends T{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 or=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 ot(e));}),this}groupByRaw(t){return this.groupByNodes.push(new ot(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new nt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new nt(t,"asc",true)),this}limit(t){return typeof t!="number"&&M.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new tr(t),this}offset(t){return typeof t!="number"&&M.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new rr(t),this}};var nr=class extends or{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new re(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new re(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new re(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new re(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new re(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new re(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,n,s),this}join(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new re(typeof t=="string"?t:t.table,e,n,"inner",{operator:s||"="})),this}leftJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new re(typeof t=="string"?t:t.table,e,n,"left",{operator:s||"="})),this}rightJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new re(typeof t=="string"?t:t.table,e,n,"right",{operator:s||"="})),this}fullJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new c("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new re(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var sr=class extends nr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.modelAnnotatedColumns=[];this.dbType=r.getDbType(),this.fromNode=new F(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],e.map(o=>$(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new X(o));}),this}selectRaw(e){return this.selectNodes.push(new X(e,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}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes.push(new X(s,a,n)),this.modelAnnotatedColumns.push(a),this}from(e){return this.fromNode=new F(e),this}table(e){return this.fromNode=new F(e),this}distinct(){return this.distinctNode=new Xt,this}distinctOn(...e){return this.distinctOnNode=new er(e),this}};var ir=class extends sr{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 A&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof A||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 A&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof A||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof A)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new P(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 A&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof A||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof A)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new P(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 A&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof A||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof A)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new P(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 A&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof A||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof A)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new P(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 A&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof A||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof A)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new P(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 P(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new P(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 P(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new P(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 P(e,"and",false,"in",r)),this):(this.whereNodes.push(new P("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new P(e,"or",false,"in",r)),this):(this.whereNodes.push(new P("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 P(e,"and",true,"in",r)),this):(this.whereNodes.push(new P("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new P(e,"or",true,"in",r)),this):(this.whereNodes.push(new P("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new P(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new P(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new P(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new P(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 P(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 P(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new P(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new P(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new P(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof A?e:new A(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Me("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof A?e:new A(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Me("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof A?e:new A(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Me("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof A?e:new A(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Me("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new P(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new P(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 Be(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 Be(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Be(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Be(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof A)return e;let r=new A(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Me(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Me(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new A(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new tt(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new A(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new tt(r.whereNodes,"or");return this.whereNodes.push(o),this}};var ar=class extends ir{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new te(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new te(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new te(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new te(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new te(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new te(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new te(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new te(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new te(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new te(t,"or",false,"raw",e)),this}};var A=class i extends ar{constructor(e,r=ue.getInstance()){super(e,r);this.isNestedCondition=false;this.mustRemoveAnnotations=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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);}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return W(e,r,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}})}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 first(){return this.one()}async oneOrFail(){let e=await this.one();if(!e)throw new c("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return await Yt(r,o,this.sqlDataSource,e,{onData:(s,a)=>{s.write(a);}})}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:hu(e,a),data:s},{key:r.discriminator,value:d}]}selectSubQuery(e,r){if(typeof e=="function"){let o=new i(this.model,this.sqlDataSource);return e(o),this.selectNodes.push(new X(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new X(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new et("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new et("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Ee(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ee(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ee(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ee(o,true)),this}async increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}async decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.annotate("count",e,"total");let r=await this.one();return r?He(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?He(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?He(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?He(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?He(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:Zt(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new c("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 Ve("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 Ve("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new c("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 Ve("materialized",e,n)),this}async insert(e,r){let{columns:o,values:n}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),s=Object.fromEntries(o.map((u,m)=>[u,n[m]]));this.insertNode=new U(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await W(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(d)&&d.length?d[0]:d}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async a=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(a),Object.values(a),"insert");return Object.fromEntries(l.map((u,m)=>[u,d[m]]))}));this.insertNode=new U(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]);return W(n,s,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:o}})}async upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(a.map((f,g)=>[f,l[g]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:u,bindings:m}=this.astParser.parse([new U(new F(this.model.table),[d],void 0,true),new de(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await W(u,m,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(p)?p:[p]}async upsertMany(e,r,o,n={updateOnConflict:true}){let s=[];if(await Promise.all(o.map(async u=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(u),Object.values(u),"insert"),f=Object.fromEntries(m.map((g,h)=>[g,p[h]]));s.push(f);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(s,e,r,n,o);let{sql:a,bindings:l}=this.astParser.parse([new U(new F(this.model.table),s,void 0,true),new de(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await W(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(d)?d:[d]}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=S=>this.interpreterUtils.formatStringColumn("mssql",S),u=[],m=e.map(S=>`select ${a.map(G=>(u.push(S[G]),`@${u.length}`)).join(", ")}`),p=a.map(d).join(", "),f=m.join(" union all "),g=r.map(S=>`target.${d(S)} = source.${d(S)}`).join(" and "),h=o.filter(S=>!r.includes(S)).map(S=>`target.${d(S)} = source.${d(S)}`).join(", "),N=a.map(d).join(", "),I=a.map(S=>`source.${d(S)}`).join(", "),Q=n.returning&&n.returning.length?n.returning.map(S=>`inserted.${d(S)}`).join(", "):a.map(S=>`inserted.${d(S)}`).join(", "),E=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",L=`merge into ${l} as target using (${f}) as source (${p}) on ${g} ${E} when not matched then insert (${N}) values (${I}) output ${Q};`,C=await W(L,u,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(C)?C:[C]}async update(e){let r=Object.keys(e),o=Object.values(e),{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new ee(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return W(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new ge(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]);await W(e,r,this.sqlDataSource,"raw");}async delete(){this.deleteNode=new be(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]);return W(e,r,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=pe()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new ee(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return W(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return $i(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new X("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=wt(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.modelAnnotatedColumns=j(this.modelAnnotatedColumns),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.mustRemoveAnnotations=this.mustRemoveAnnotations,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 X("*")]),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 k(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await k(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstWithPerformance(e="millis"){return this.oneWithPerformance(e)}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await k(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await k(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await k(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await k(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await k(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await k(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await k(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await k(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await k(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await k(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await k(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()])}};var Je=class i extends A{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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 rt(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 first(e){return this.one(e)}async oneOrFail(e){let r=await this.one(e);if(!r)throw new c(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async firstOrFail(e){return this.oneOrFail(e)}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 fe(o,this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);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}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();return await Yt(r,o,this.sqlDataSource,e,{onData:async(s,a)=>{let l=this.addAdditionalColumnsToModel(a,this.model),d=await fe([l],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),s.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new c(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}async insert(...e){return this.model.insert(...e)}async insertMany(...e){return this.model.insertMany(...e)}async update(e,r={}){return r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),super.update(e)}async softDelete(e={}){let{ignoreBeforeUpdateHook:r=false}=e||{};return !r&&await this.model.beforeUpdate?.(this),super.softDelete(e)}async delete(e={}){return e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),super.delete()}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("count",e,"total");let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("max",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("min",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("avg",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("sum",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.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:Zt(e,r,d),data:l}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new X(r))),this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes=this.selectNodes.concat(new X(s,a,n)),this.modelAnnotatedColumns.push(a),this}removeAnnotations(){return this.mustRemoveAnnotations=true,this.modelAnnotatedColumns=[],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 c(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(p=>{let f=p[e.foreignKey];f&&n.set(String(f),p);}),r.forEach(p=>{let f=p[this.model.primaryKey];if(!f){p[e.columnName]=null;return}let g=n.get(String(f));p[e.columnName]=g||null;});break;case "belongsTo":let s=new Map;o.forEach(p=>{if(!e.model.primaryKey)throw new c(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let f=p[e.model.primaryKey];f&&s.set(String(f),p);}),r.forEach(p=>{let f=p[e.foreignKey];if(!f){p[e.columnName]=null;return}let g=s.get(String(f));p[e.columnName]=g||null;});break;case "hasMany":if(!this.model.primaryKey)throw new c(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(p=>{let f=p[e.foreignKey];if(!f)return;let g=String(f);a.has(g)||a.set(g,[]),a.get(g).push(p);}),r.forEach(p=>{let f=p[this.model.primaryKey];if(!f){p[e.columnName]=[];return}let g=a.get(String(f))||[];p[e.columnName]=g;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new c(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)||$(u,this.model.modelCaseConvention);o.forEach(p=>{let f=p.$annotations||{},g=f[m];if(g==null)return;let h=String(g);d.has(h)||d.set(h,[]),this.modelAnnotatedColumns.includes(m)||(delete f[m],Object.keys(f).length||delete p.$annotations),d.get(h).push(p);}),r.forEach(p=>{let f=p[this.model.primaryKey];if(!f){p[e.columnName]=[];return}let g=d.get(String(f))||[];p[e.columnName]=g;});break;default:throw new c(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=we__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,u=e.orderByNodes.map(S=>S.isRawValue?S.column:`${this.interpreterUtils.formatStringColumn(this.dbType,S.column)} ${S.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(d,S=>S.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 p=e.modelSelectedColumns.map(S=>Or(S,d,e.model.table));return m.select(...p).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new c(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let f=r;if(!o.length)return e;let g=e.limitNode?.limit,h=e.offsetNode?.offset,N=e.modelSelectedColumns.length?e.modelSelectedColumns.map(S=>S.includes(".")?S:`${r.model.table}.${S}`):[`${r.model.table}.*`];if(!g&&!h)return e.select(...N).annotate(`${f.throughModel}.${f.leftForeignKey}`,f.leftForeignKey).leftJoin(f.throughModel,`${f.relatedModel}.${f.model.primaryKey}`,`${f.throughModel}.${f.rightForeignKey}`).whereIn(`${f.throughModel}.${f.leftForeignKey}`,n);let I=we__default.default.randomBytes(6).toString("hex"),Q=`${r.model.table}_cte_${I}`,_=e.orderByNodes.map(S=>{if(S.isRawValue)return S.column;let ce=S.column.includes(".")?S.column:`${r.model.table}.${S.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,ce)} ${S.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let E=`${we__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,L=e.with(Q,S=>S.select(...N).annotate(`${f.throughModel}.${f.leftForeignKey}`,E).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${f.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,f.leftForeignKey)} ORDER BY ${_}) as rn_${I}`).leftJoin(f.throughModel,`${f.relatedModel}.${f.model.primaryKey}`,`${f.throughModel}.${f.rightForeignKey}`).whereIn(`${f.throughModel}.${f.leftForeignKey}`,n));g&&L.whereRaw(`rn_${I} <= ${g+(h||0)}`),h&&L.whereRaw(`rn_${I} > ${h}`);let C=N.map(S=>Or(S,Q,e.model.table));return L.select(...C).annotate(`${Q}.${E}`,f.leftForeignKey).from(Q);default:throw new c(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new c(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 c(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new c(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 c(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 c(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 c(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(f=>!f.isRawValue&&f.table===d.throughModel&&f.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let m=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),p=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${p}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new c(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={},n={};return Object.entries(e).forEach(([s,a])=>{if(s==="$annotations"||this.modelColumnsDatabaseNames.get(s)){o[s]=a;return}n[$(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await k(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await k(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await k(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async firstWithPerformance(e={},r="millis"){return this.oneWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await k(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 k(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await k(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await k(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await k(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await k(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await k(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await k(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var lr=class extends Je{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new U(this.fromNode,[o],r?.returning),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new U(this.fromNode,o,r?.returning),this}update(...t){let[e]=t;return this.updateNode=new ee(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new be(this.fromNode),this}truncate(){return this.truncateNode=new ge(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=pe()}=e||{};return this.updateNode=new ee(this.fromNode,[r],[o]),this}};function gu(i){let t=i.name,e=$(t,"snake");return cm__default.default(e)}function bu(){return {}}var st=class{constructor(t,e){this.model=t,this.modelInstance=bu(),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);}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&&Object.entries(t.where).forEach(([r,o])=>{if(Array.isArray(o)){e.whereIn(r,o);return}e.where(r,o);}),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 c(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new c(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}async insert(t,e={}){!e.ignoreHooks&&await this.model.beforeInsert?.(t);let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),n={};r.forEach((m,p)=>{let f=o[p];n[m]=f,t[m]??(t[m]=f);});let{sql:s,bindings:a}=this.astParser.parse([new U(new F(this.model.table),[n],e.returning)]),l=await W(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(l,[t],"one",e.returning);let d=l[0];return d?(await this.model.afterFetch?.([d]),await fe([d],this.model)):t}async insertMany(t,e={}){let r=[];await this.model.beforeInsertMany?.(t);for(let d of t){let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),p={};u.forEach((f,g)=>{let h=m[g];p[f]=h,d[f]??(d[f]=h);}),r.push(p);}let{sql:o,bindings:n}=this.astParser.parse([new U(new F(this.model.table),r,e.returning)]),s=await W(o,n,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(s,t,"many",e.returning)||[];let a=s;return a.length?(await this.model.afterFetch?.(a),await fe(a,this.model)||[]):[]}async upsertMany(t,e,r,o={updateOnConflict:true}){let n=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async d=>{let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),p=Object.fromEntries(u.map((f,g)=>[f,m[g]]));n.push(p);})),this.sqlType==="mssql")return this.executeMssqlMerge(n,t,e,o,r);let{sql:s,bindings:a}=this.astParser.parse([new U(new F(this.model.table),n,void 0,true),new de(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await W(s,a,this.sqlDataSource,"raw",{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=C=>this.interpreterUtils.formatStringColumn("mssql",C),d=[],u=t.map(C=>`select ${s.map(ce=>(d.push(C[ce]),`@${d.length}`)).join(", ")}`),m=s.map(l).join(", "),p=u.join(" union all "),f=e.map(C=>`target.${l(C)} = source.${l(C)}`).join(" and "),g=r.filter(C=>!e.includes(C)).map(C=>`target.${l(C)} = source.${l(C)}`).join(", "),h=s.map(l).join(", "),N=s.map(C=>`source.${l(C)}`).join(", "),I=o.returning&&o.returning.length?o.returning.map(C=>`inserted.${l(C)}`).join(", "):s.map(C=>`inserted.${l(C)}`).join(", "),_=(o.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",E=`merge into ${a} as target using (${p}) as source (${m}) on ${f} ${_} when not matched then insert (${h}) values (${N}) output ${I};`;return await W(E,d,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}})}async updateRecord(t,e){let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"update"),{primaryKey:n}=this.model;if(!n)throw new c(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");r=r.filter(d=>d!==n),o=o.filter(d=>d!==t[n]);let{sql:s,bindings:a}=this.astParser.parse([new ee(new F(this.model.table),r,o),new P(n,"and",false,"=",t[n])]);await W(s,a,this.sqlDataSource,"raw");let l=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!l)throw new c(this.model.name+"::updateRecord","ROW_NOT_FOUND");return l}async deleteRecord(t){if(!this.model.primaryKey)throw new c(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new P(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new be(new F(this.model.table)),e]);await W(r,o,this.sqlDataSource,"raw");}query(){return new Je(this.model,this.sqlDataSource)}dryQuery(){return new lr(this.model,this.sqlDataSource)}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await fe([a],this.model):null}return await fe(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}};var it=class extends A{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new U(this.fromNode,[o],r),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new U(this.fromNode,o,r),this}upsert(...t){let[e,r,o]=t,n=Object.keys(e),s=Object.keys(r);return this.insertNode=new U(new F(this.model.table),[e],void 0,true),this.onDuplicateNode=new de(this.model.table,s,n,o?.updateOnConflict??true?"update":"ignore",o?.returning),this}upsertMany(...t){let[e,r,o,n]=t,s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new U(new F(this.model.table),s,void 0,true),this.onDuplicateNode=new de(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new ee(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new be(this.fromNode),this}truncate(){return this.truncateNode=new ge(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=pe()}=t||{};return this.updateNode=new ee(this.fromNode,[e],[r]),this}};var at=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??pe()});var ie=class{constructor(t){this.options=t;}static async createDriver(t){throw new c("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var dr=class i extends ie{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){let e=await import('mongodb').catch(()=>{throw new B("mongodb")});if(!e)throw new B("mongodb");return new i(e)}};var ur=class i extends ie{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){let{default:e}=await import('mssql').catch(()=>{throw new B("mssql")});if(!e)throw new B("mssql");return new i(e)}};var mr=class i extends ie{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){let e=await import('mysql2/promise').catch(()=>{throw new B("mysql2")});if(!e)throw new B("mysql");return new i(e.default)}};var cr=class i extends ie{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){let e=await import('pg').catch(()=>{throw new B("pg")});if(!e)throw new B("pg");return new i(e.default)}};var pr=class i extends ie{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){let e=await import('sqlite3').catch(()=>{throw new B("sqlite3")});if(!e)throw new B("sqlite3");return new i(e.default)}};var ve=class{static async getDriver(t){switch(t){case "mysql":case "mariadb":return mr.createDriver();case "postgres":case "cockroachdb":return cr.createDriver();case "sqlite":return pr.createDriver();case "mongo":return dr.createDriver();case "mssql":return ur.createDriver();default:throw new c(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}};var Tm=async i=>(await ve.getDriver(i)).client,lt=async(i,t)=>{let e=await Tm(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,Q=>{if(Q)throw new c("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let f=e,g=t,{options:h,...N}=g.driverOptions??{};return await f.connect({server:g.host??"localhost",port:g.port,database:g.database,user:g.username,password:g.password,...N,options:{trustServerCertificate:q.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...h,abortTransactionOnError:false,enableImplicitTransactions:false}});default:throw new c("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var dt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=we__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.startTransaction(),t)try{await t(e),await e.commit();}catch(r){throw await e.rollback(),r}return e}async startTransaction(){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":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),ne("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;ne("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}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new c("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":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":ne("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ne("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}}catch(e){throw M.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new c("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":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new c("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":ne("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ne("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;default:throw new c("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;default:throw new c("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){M.error(t);}await this.sql.closeConnection(),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 c("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==="sqlite")return "";throw new c("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 B("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 c("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var me=class me extends ke{constructor(e){super(e);this.globalTransaction=null;this.models={};this.ownsPool=false;this.sqlConnection=null;this.cacheAdapter=new bt;this.cacheKeys={};this.migrationsPath=q.MIGRATION_PATH||"database/migrations";this.sqlType=this.type,this.inputDetails=e||{connectionPolicies:{retry:{maxRetries:0,delay:0}},queryFormatOptions:{language:Tt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"}},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:Tt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,this.migrationsPath=e?.migrationsPath||this.migrationsPath;}static async connect(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new me(e);if(e?.models){let n=o.sanitizeModelKeys(e?.models||{});Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await lt(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),me.instance=o,await r?.(o),o}static async connectToSecondarySource(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new me(e);if(e?.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await lt(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),me.instance=o,await r?.(o),o}static async useConnection(e,r){let o=new me(e);if(e.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}o.models=e.models||{},o.sqlPool=await lt(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:e.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1");try{await r(o).then(async()=>{o.isConnected&&await o.closeConnection();});}catch(n){throw o.isConnected&&await o.closeConnection(),n}}static getInstance(){if(!me.instance)throw new c("SqlDataSource::getInstance","CONNECTION_NOT_ESTABLISHED");return me.instance}static query(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new A(at(e,r),n);return r?.alias&&s.from(e,r.alias),s}static dryQuery(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new it(at(e,r),n);return r?.alias&&s.from(e,r.alias),s}static createTable(...e){return this.getInstance().createTable(...e)}static alterTable(...e){return this.getInstance().alterTable(...e)}static async startGlobalTransaction(e){return this.getInstance().startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.getInstance().commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.getInstance().rollbackGlobalTransaction();}static async startTransaction(e,r){return this.getInstance().startTransaction(e,r)}static async transaction(e,r){let o=typeof e=="function"?r:e;return this.getInstance().startTransaction(e,o)}static async getTableSchema(e){return this.getInstance().getTableSchema(e)}static async closeConnection(){if(!this.instance){M.warn("Connection already closed");return}await this.instance.closeConnection(),this.instance=null;}static async disconnect(){return this.closeConnection()}static async rawQuery(e,r=[]){let o=this.getInstance();return (o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o).rawQuery(e,r)}static rawStatement(e){return this.getInstance().rawStatement(e)}static async initializeAdminJs(){return this.getInstance().initializeAdminJs()}static async initializeAdminJsExpress(){return this.getInstance().initializeAdminJsExpress()}static getAdminJs(){return this.instance?.getAdminJs()}static isAdminJsEnabled(){return this.instance?.isAdminJsEnabled()??false}async useCache(e,r,...o){if(!this.cacheAdapter)throw new c("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new c("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),a||(l=void 0,d=r!==void 0?[r,...o]:o);let u=Ir(JSON.stringify(d)),m=u?`${e}:${u}`:e,p=await this.cacheAdapter.get(m);if(p!==void 0)return p;let f=await n(...d);return await this.cacheAdapter.set(m,f,l),f}async invalidCache(e,...r){if(!this.cacheAdapter)throw new c("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=Ir(JSON.stringify(r)),n=o?`${e}:${o}`:e;await this.cacheAdapter.invalidate(n);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async clone(e){let r=new me(this.inputDetails);if(r.sqlType==="sqlite"||!!e?.shouldRecreatePool){if(r.sqlPool=await lt(r.sqlType,{type:r.sqlType,host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,connectionPolicies:r.inputDetails.connectionPolicies,queryFormatOptions:r.inputDetails.queryFormatOptions,driverOptions:r.inputDetails.driverOptions,logs:r.logs,models:r.models}),r.ownsPool=true,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}if(r.sqlPool=this.sqlPool,r.ownsPool=false,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}getDbType(){return this.type}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new A(at(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new it(at(e,r),this)}alterTable(...e){let r=new le(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new le(this.getDbType());return r.createTable(...e),r.queryStatements[0]||""}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new dt(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new c("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 startTransaction(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 dt(n,o?.isolationLevel);if(await s.startTransaction(),typeof e=="function")try{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}async transaction(e,r){return this.startTransaction(e,r)}getModelManager(e){if(!this.isConnected)throw new c("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new st(e,this.globalTransaction.sql):new st(e,this)}getPool(e=this.sqlType){if(!this.sqlPool)throw new c("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(e=this.sqlType){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new c("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();default:throw new c("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){ne("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::closeConnection - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),ne("Closing connection",this.logs),this.type){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;default:throw new c("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}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 disconnect(){return this.closeConnection()}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 Ht.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`);}async rawQuery(e,r=[]){if(!this.isConnected)throw new c("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let o=wt(this,e);return W(o,r,this,"raw")}rawStatement(e){return new v(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 Pi(Object.values(this.models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new c("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Ar(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new c("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await Ii(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 Ct(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(Ze(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=De(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=De(s,d),m=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,p=typeof m=="string"?m.toLowerCase()!=="no":typeof m=="boolean"?m:a.notnull!==void 0?a.notnull===0:true,f=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,g=a.char_length!=null?Number(a.char_length):null,h=a.numeric_precision!=null?Number(a.numeric_precision):null,N=a.numeric_scale!=null?Number(a.numeric_scale):null,I=a.timezone!=null?!!a.timezone:typeof a.datetime_precision=="number"?/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase()):/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase());return {name:l,dataType:u,isNullable:p,defaultValue:f,length:g,precision:h,scale:N,withTimezone:I}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Mt(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(Ze(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,p=l.get(u)||{name:u,columns:[],isUnique:m};p.columns.push(d.Column_name),l.set(u,p);}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,p=l.get(u)||{name:u,columns:[],isUnique:m};p.columns.push(d.column_name),l.set(u,p);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,p=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(f=>f.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 St(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ze(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 qt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ze(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 testConnectionQuery(e){await W(e,[],this,"raw",{shouldNotLog:true});}sanitizeModelKeys(e){let r=Object.getOwnPropertyNames(this),o=Object.getOwnPropertyNames(this.constructor),n=[...r,...o];if(Object.keys(e).some(s=>n.includes(s)))throw new c("SqlDataSource::sanitizeModelKeys","DUPLICATE_MODEL_KEYS_WHILE_INSTANTIATING_MODELS",new Error(`Duplicate model keys while instantiating models inside the connection: ${Object.keys(e).filter(s=>n.includes(s)).map(s=>`"${s}"`).join(", ")}`));return e}static get isInGlobalTransaction(){return !!this.instance?.globalTransaction}get isInGlobalTransaction(){return !!this.globalTransaction}get registeredModels(){return this.models}};me.instance=null;var ue=me;var Tu=["postgres","cockroachdb"];var ut=class ut extends Re{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:gu(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Cu(this)}constructor(){super();}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static dryQuery(t){return this.dispatchModelManager(t).dryQuery()}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);return a||null}static async insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async insertMany(t,e={}){return t.length?this.dispatchModelManager(e).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=Gt(s).find(g=>g.columnName===t);if(!l)throw new c(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new c(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=$(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),u=$(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),m=r.map((g,h)=>({[d]:e[s.primaryKey],[u]:g[l.model.primaryKey],...o?o(g,h):{}}));class p extends ut{static get table(){return l.throughModel}}p.databaseCaseConvention="preserve",p.modelCaseConvention="preserve",await p.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 c&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new c(`${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);return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),a=Object.keys(t).length>0?await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t}):null;return a?(e[o.primaryKey]=a[o.primaryKey],r.updateOnConflict?await n.updateRecord(e,{returning:r.returning}):a):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);if(!e.every(m=>{let p=new Set(Object.keys(m));return t.every(f=>p.has(f))}))throw new c("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let s=Object.keys(e[0]),a=await n.upsertMany(t,s,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true}),l=o.sqlInstance.getDbType();if(Tu.includes(l))return await fe(a,o,r.returning);let d=n.query();r.returning?.length&&d.select(...r.returning);let u=new Map;return t.forEach(m=>{e.forEach(p=>{u.set(m,[...u.get(m)||[],p[m]]);});}),d.where(m=>{t.forEach(p=>{m.orWhereIn(p,u.get(p)||[]);});}),d.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(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 Nt(this)}static getRelations(){return qu(this)}static getIndexes(){return Ru(this)}static getUniques(){return _u(this)}static column(t,...e){D(...e)(this.prototype,t);}static hasOne(t,...e){Nu(...e)(this.prototype,t);}static hasMany(t,...e){Su(...e)(this.prototype,t);}static belongsTo(t,...e){wu(...e)(this.prototype,t);}static manyToMany(t,...e){Mu(...e)(this.prototype,t);}static establishConnection(){let t=ue.getInstance();if(!t)throw new c("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){if(t?.connection)return t.connection.getModelManager(this);if(t?.trx)return t.trx.sql.getModelManager(this);let e=this;return e.establishConnection(),e.sqlInstance.getModelManager(e)}mergeProps(t){this.constructor.combineProps(this,t);}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{},a=e,l=await r.upsert(s,a,{updateOnConflict:true,...t});return r.combineProps(this,l),this}async update(t,e={}){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new c(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new c(o.name+"::update","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.updateRecord(r,t,e);}async softDelete(t,e){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new c(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new c(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.softDelete(r,t,e);}async delete(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new c(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await r.deleteRecord(this,t);}async refresh(t){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new c(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new c(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};ut.softDeleteColumn="deletedAt",ut.softDeleteValue=pe();var oe=ut;var Te=class{constructor(t,e){this.model=oe;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var fr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var yr=class extends Te{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var hr=class extends Te{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var gr=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 dI(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(Qt,e.prototype)||[];o.push({columns:r,name:t??Lt(e.table,r.join("_"))}),K.defineMetadata(Qt,o,e.prototype);}}function uI(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(kt,e.prototype)||[];o.push({columns:r,name:t??se(e.table,r.join("_"))}),K.defineMetadata(kt,o,e.prototype);}}function mI(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 D(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(K.getMetadata(Kt,e))throw new c("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");K.defineMetadata(Kt,r,e);}let n=i.databaseName??$(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??Oe(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(vt,e)||[];a.push(s),K.defineMetadata(vt,a,e);}}D.primary=Sm;D.date=Pm;D.boolean=Im;D.json=xm;D.uuid=_m;D.ulid=Om;D.integer=qm;D.float=Mm;D.increment=Cm;D.bigIncrement=Rm;D.encryption={symmetric:Am,asymmetric:Dm};function Sm(i={}){return D({...i,primaryKey:true})}function Mm(i={}){return D({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)}})}function qm(i={}){return D({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function Cm(i={}){return D({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)}})}function Rm(i={}){return D({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)}})}function _m(i={}){return D({type:"uuid",...i,prepare:t=>t||we__default.default.randomUUID()})}function Om(i={}){return D({type:"ulid",...i,prepare:t=>t||Oi()})}function Am(i){return D({...i,prepare:t=>t&&qi(i.key,t),serialize:t=>t&&Ci(i.key,t)})}function Dm(i){return D({...i,prepare:t=>t&&Ri(i.publicKey,t),serialize:t=>t&&_i(i.privateKey,t)})}function Im(i={}){return D({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function Pm(i={}){let{format:t="ISO",timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i;return D({type:"datetime",...n,autoUpdate:r,prepare:s=>s?r?yt(new Date,t,e):typeof s=="string"?s:yt(s,t,e):o?yt(new Date,t,e):null,serialize:s=>{if(s!==void 0)return s===null?null:Mi(s,t,e)}})}function xm(i={}){return D({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function Nt(i){try{return K.getMetadata(vt,i.prototype)||[]}catch{return []}}function wu(i,t,e){return (r,o)=>{let n=()=>_e(i().table),s=()=>{let d=r.constructor.table,u=t||n();return J(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(ae,r)||[];l.push(a),K.defineMetadata(ae,l,r);}}function Nu(i,t){return (e,r)=>{let o=()=>_e(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=K.getMetadata(ae,e)||[];s.push(n),K.defineMetadata(ae,s,e);}}function Su(i,t){return (e,r)=>{let o=()=>_e(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=K.getMetadata(ae,e)||[];s.push(n),K.defineMetadata(ae,s,e);}}function Mu(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=()=>_e(u),p=()=>_e(i().table),f=()=>J(w(d),s?String(s):m()),g={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??f,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):p,wasModelProvided:l}},h=K.getMetadata(ae,o)||[];h.push(g),K.defineMetadata(ae,h,o);}}function qu(i){return K.getMetadata(ae,i.prototype)||[]}function Gt(i){return (K.getMetadata(ae,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=w(s),l=o();switch(r){case "belongsTo":return new fr(l,n,a);case "hasOne":return new hr(l,n,a);case "hasMany":return new yr(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new c("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new gr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:w(e.manyToManyOptions.throughModel),leftForeignKey:w(e.manyToManyOptions.leftForeignKey),rightForeignKey:w(e.manyToManyOptions.rightForeignKey)});default:throw new c("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Cu(i){return K.getMetadata(Kt,i.prototype)}function Ru(i){return K.getMetadata(Qt,i.prototype)||[]}function _u(i){return K.getMetadata(kt,i.prototype)||[]}var pi=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){let e=this.typeofModel;if(t===1)return e.insert(this.modelData);let r=Array.from({length:t});return e.insertMany(r.map(()=>({...this.modelData})))}},Em=(i,t)=>new pi(i,t);var mt=class extends oe{};Y([D.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],mt.prototype,"createdAt"),Y([D.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],mt.prototype,"updatedAt"),Y([D.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],mt.prototype,"deletedAt");var fi=class extends oe{};Y([D.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],fi.prototype,"id");var yi=class extends oe{};Y([D.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],yi.prototype,"id");var Ke=class extends oe{};Y([D.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Ke.prototype,"id"),Y([D({type:"varchar",length:255,openApi:{type:"string",required:true}})],Ke.prototype,"email"),Y([D.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ke.prototype,"createdAt"),Y([D.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ke.prototype,"updatedAt"),Y([D.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Ke.prototype,"deletedAt");var Ou=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 B("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);}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:Bm}=cm__default.default;function Au(i){let t=i.name,e=$(t,"snake");return Bm(e)}function Du(){return {$annotations:{}}}var ze=class extends Re{static get collection(){return this._collection||Au(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=ct.getInstance();if(!t)throw new c("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){qr()(this.prototype,t);}static async afterFetch(t){return t}};Y([qr()],ze.prototype,"id");async function Ie(i,t,e){if(!t)return null;let r=Du(),o=Si(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=$(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=$(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=$(n,i.modelCaseConvention);r[s]=null;}})),r}async function br(i,t,e){return (await Promise.all(t.map(async o=>await Ie(i,o,e)))).filter(o=>o!==null)}var Tr=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,limit:1,session:this.session}),o=await Ie(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 c("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 br(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 Ie(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 br(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 br(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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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=Z("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 wr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=ze,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 c("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Tr(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 Ie(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 Ie(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new c("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 c("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Ie(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new c("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 ke{constructor(t,e){super({type:"mongo"}),this.url=t,this.isConnected=false,this.mongoClient=e;}getCurrentConnection(){return this.mongoClient}static async connect(t,e,r){if(!t&&(t=q.MONGO_URL,!t))throw new c("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 o=(await ve.getDriver("mongo")).client,n=new o.MongoClient(t,e);return await n.connect(),this.instance=new Qe(t,n),this.instance.isConnected=true,this.instance.logs=e?.logs||q.MONGO_LOGS||false,await r?.(this.instance),this.instance}static getInstance(){if(!Qe.instance)throw new c("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Qe.instance}startSession(){let t=this.mongoClient.startSession();return t.startTransaction(),t}static async disconnect(){if(!this.instance)throw new c("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(t,e){let r=(await ve.getDriver("mongo")).client,o=new r.MongoClient(t.url,t.options);await o.connect();let n=new Qe(t.url,o);await e(n),await o.close();}static query(t){return this.getInstance().query(t)}query(t){if(!this.isConnected)throw new c("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:t},this).query()}getModelManager(t,e,r){return new wr(t,e,r,this.logs)}};Qe.instance=null;var ct=Qe;var V=class V{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||+q.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new B("ioredis")});this.redisDataSourceInstance=new V(new r.default({host:t?.host||q.REDIS_HOST,username:t?.username||q.REDIS_USERNAME,port:e,password:t?.password||q.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new c("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new B("ioredis")}),r=new e.default({host:t?.host||q.REDIS_HOST,username:t?.username||q.REDIS_USERNAME,port:t?.port||+q.REDIS_PORT||6379,password:t?.password||q.REDIS_PASSWORD,...t}),o=new V(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 c("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new c("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new c("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 c("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new c("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new c("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new c("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 c("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return V.getValue(e)}catch{throw new c("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new c("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),V.getValue(e)}catch{throw new c("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new c("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new c("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new c("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 c("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 c("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new c("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new c("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 c("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new c("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 c("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 c("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return V.getValue(e)}catch{throw new c("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return V.getValue(e)}catch{throw new c("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>V.getValue(n)).filter(n=>n!==null)}catch{throw new c("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new c("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 c("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 c("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 c("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 c("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 c("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new c("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new c("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new c("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new c("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 c("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 c("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return V.getValue(r)}catch{throw new c("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]=V.getValue(n);return r}catch{throw new c("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>V.getValue(o))}catch{throw new c("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new c("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new c("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new c("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new c("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 c("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 c("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 c("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 c("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new c("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 c("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 c("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 c("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 c("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>V.getValue(r)).filter(r=>r!==null)}catch{throw new c("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 c("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 c("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new c("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>V.getValue(r)).filter(r=>r!==null)}catch{throw new c("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>V.getValue(r)).filter(r=>r!==null)}catch{throw new c("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>V.getValue(r)).filter(r=>r!==null)}catch{throw new c("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 c("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 c("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 c("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 c("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 c("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new c("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 c("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=V.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=>V.getValue(s)).filter(s=>s!==null)}catch{throw new c("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=V.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=>V.getValue(s)).filter(s=>s!==null)}catch{throw new c("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 c("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 c("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new c("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 c("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new c("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 c("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 c("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new c("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new c("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new c("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 c("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 c("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new c("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new c("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new c("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new c("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new c("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new c("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new c("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new c("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new c("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new c("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new c("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new c("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new c("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new c("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new c("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new c("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new c("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new c("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new c("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new c("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new c("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)}};V.OK="OK";var hi=V;var gi=class{constructor(t){this.dbType=t,this.migrationName=pt__default.default.basename(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))),this.schema=new le(this.dbType);}};async function Pu(i,t){let e=pt__default.default.isAbsolute(i)?i:pt__default.default.resolve(process.cwd(),i),{mod:r}=await bundleRequire.bundleRequire({filepath:e,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","reflect-metadata","pluralize","dayjs","async-mutex","commander"]});return r}var bi=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return Object.values(r).map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.map(n=>n.table_name);case "mssql":return r.map(n=>n.TABLE_NAME);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
|
|
84
123
|
FROM information_schema.tables
|
|
85
124
|
WHERE table_catalog = '${e}'
|
|
86
125
|
AND table_schema = 'public'
|
|
87
|
-
AND table_type = 'BASE TABLE';`;
|
|
126
|
+
AND table_type = 'BASE TABLE';`;case "mssql":return `SELECT TABLE_NAME
|
|
127
|
+
FROM INFORMATION_SCHEMA.TABLES
|
|
128
|
+
WHERE TABLE_CATALOG = '${e}'
|
|
129
|
+
AND TABLE_TYPE = 'BASE TABLE';`;default:throw new Error(`Unsupported database type: ${t}`)}}dropAllTablesTemplate(t,e){if(!e.length)return "SELECT 1;";switch(t){case "mysql":case "mariadb":case "cockroachdb":case "postgres":return `DROP TABLE IF EXISTS ${e.join(", ")} CASCADE;`;case "mssql":return e.map(r=>`DROP TABLE IF EXISTS [${r}];`).join(`
|
|
130
|
+
`);default:throw new Error(`Unsupported database type: ${t}`)}}basicMigrationTemplate(t=false){return t?`import { Migration } from 'hysteria-orm';
|
|
88
131
|
|
|
89
132
|
export default class extends Migration {
|
|
90
133
|
async up() {
|
|
@@ -179,5 +222,11 @@ export default class extends Migration {
|
|
|
179
222
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
180
223
|
name TEXT NOT NULL,
|
|
181
224
|
timestamp TEXT NOT NULL DEFAULT '${new Date().toISOString()}'
|
|
182
|
-
);`}
|
|
225
|
+
);`}migrationTableTemplateMssql(){return `IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='migrations' AND xtype='U')
|
|
226
|
+
CREATE TABLE [migrations] (
|
|
227
|
+
[id] INT NOT NULL IDENTITY(1,1),
|
|
228
|
+
[name] NVARCHAR(255) NOT NULL,
|
|
229
|
+
[timestamp] DATETIME NOT NULL DEFAULT GETDATE(),
|
|
230
|
+
PRIMARY KEY ([id])
|
|
231
|
+
);`}},qe=new bi;var jm=async(i,t)=>{if(i.endsWith(".ts"))return await import('typescript').catch(()=>{throw new c("MigrationUtils::importMigrationFile In order to use TypeScript migrations, you must have `typeScript` installed in your project. Please install it with `npm install typescript --save-dev`, if you're in a production environment, it's recommended to transpile your migrations to JavaScript before running the application.","MIGRATION_MODULE_NOT_FOUND")}),await import('esbuild').catch(()=>{throw new c("MigrationUtils::importMigrationFile In order to use TypeScript migrations, you must have `esbuild` installed in your project. Please install it with `npm install esbuild --save-dev`, if you're in a production environment, it's recommended to transpile your migrations to JavaScript before running the application.","MIGRATION_MODULE_NOT_FOUND")}),await import('bundle-require').catch(()=>{throw new c("MigrationUtils::importMigrationFile In order to use TypeScript migrations, you must have `bundle-require` installed in your project. Please install it with `npm install bundle-require --save-dev`, if you're in a production environment, it's recommended to transpile your migrations to JavaScript before running the application.","MIGRATION_MODULE_NOT_FOUND")}),Pu(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 c(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function Nr(i,t){switch(i){case "mariadb":case "mysql":let e=t;return await e.query(qe.migrationTableTemplateMysql()),(await e.query(qe.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":let o=t;return await o.query(qe.migrationTableTemplatePg()),(await o.query(qe.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await Eu(qe.migrationTableTemplateSQLite(),[],t),await Eu(qe.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(qe.migrationTableTemplateMssql()),(await s.request().query(qe.selectAllFromMigrationsTemplate())).recordset;default:throw new c("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Sr(i,t,e){let r=Vm(t),o=[];for(let n of r){let s=await Wm(n,t),a=new s(i||q.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function Um(i,t){let e=await jm(i);if(!e.default)throw new c("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}async function Wm(i,t=q.MIGRATION_PATH||"database/migrations",e){t=pt.join(t,i);let r=pt__default.default.resolve(process.cwd(),t),o=await Um(r);if(!o)throw new c("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function Vm(i){let t=process.cwd(),e=pt__default.default.resolve(i||q.MIGRATION_PATH||"database/migrations"),r=pt__default.default.resolve(t,e);try{let o=cu__default.default.readdirSync(r).filter(n=>{let s=pt__default.default.extname(n),a=pt__default.default.join(r,n);return cu__default.default.statSync(a).isFile()&&(s===".ts"||s===".js")});if(o.length)return o;throw new c("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}catch{throw new c("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}}async function Eu(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function Ti(i,t,e,r,o){let n=i.getDbType(),s=o,a=null;M.info("Rolling back migrations for database type: "+n);try{let l=await Nr(n,i.getPool()),d=await Sr(n,e,r),u=l.map(f=>f.name),m=d.filter(f=>u.includes(f.migrationName));if(m.length===0){M.info("No pending migrations.");return}if(t);let p=new Pe(i);s&&(a=await i.startTransaction(),i=a.sql),await p.downMigrations(m),s&&await a?.commit();}catch(l){throw l}M.info("Migrations rolled back successfully");}async function wi(i,t,e,r,o){let n=i.getDbType(),s=o,a=null;M.info("Running migrations for database type: "+n);try{let l=await Nr(n,i.getPool()),u=(await Sr(n,e,r)).filter(p=>!l.map(f=>f.name).includes(p.migrationName));if(!u.length){M.info("No pending migrations.");return}if(t);let m=new Pe(i);s&&(a=await i.startTransaction(),i=a.sql),await m.upMigrations(u),s&&await a?.commit();}catch(l){throw l}M.info("Migrations ran successfully");}var Pe=class{constructor(t){this.migrationTable="migrations";this.sql=t||ue.getInstance();}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 r=new Date().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();}},Ni=class{constructor(t=q.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){q.MIGRATION_PATH=this.migrationPath;let e=this.sqlDataSourceInput instanceof ue?this.sqlDataSourceInput:await ue.connect({...this.sqlDataSourceInput});return t==="up"?wi(e,void 0,this.migrationPath):Ti(e,void 0,this.migrationPath)}},Hm=(i,t)=>new Ni(i,t);exports.AutogeneratedModel=yi;exports.Collection=ze;exports.HysteriaError=c;exports.InMemoryAdapter=bt;exports.Migration=gi;exports.Model=oe;exports.ModelQueryBuilder=Je;exports.MongoDataSource=ct;exports.RawNode=v;exports.RedisCacheAdapter=Ou;exports.TimestampedModel=mt;exports.UserMixin=Ke;exports.UuidModel=fi;exports.belongsTo=wu;exports.column=D;exports.createModelFactory=Em;exports.defineMigrator=Hm;exports.generateOpenApiModel=Ac;exports.generateOpenApiModelSchema=Dc;exports.generateOpenApiModelWithMetadata=Pi;exports.getCollectionProperties=Si;exports.getIndexes=Ru;exports.getModelColumns=Nt;exports.getPrimaryKey=Cu;exports.getRelations=Gt;exports.getRelationsMetadata=qu;exports.getUniques=_u;exports.hasMany=Su;exports.hasOne=Nu;exports.index=dI;exports.logger=M;exports.manyToMany=Mu;exports.mongo=ct;exports.property=qr;exports.redis=hi;exports.sql=ue;exports.unique=uI;exports.view=mI;exports.withPerformance=k;//# sourceMappingURL=index.cjs.map
|
|
183
232
|
//# sourceMappingURL=index.cjs.map
|