hysteria-orm 10.4.3 → 10.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,14 +1,14 @@
1
- 'use strict';var Me=require('crypto'),Ke=require('dayjs'),tp=require('dayjs/plugin/customParseFormat.js'),rp=require('dayjs/plugin/timezone.js'),op=require('dayjs/plugin/utc.js'),Rc=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),_t=require('path'),Ap=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Me__default=/*#__PURE__*/_interopDefault(Me);var Ke__default=/*#__PURE__*/_interopDefault(Ke);var tp__default=/*#__PURE__*/_interopDefault(tp);var rp__default=/*#__PURE__*/_interopDefault(rp);var op__default=/*#__PURE__*/_interopDefault(op);var Rc__default=/*#__PURE__*/_interopDefault(Rc);var _t__default=/*#__PURE__*/_interopDefault(_t);var Ap__default=/*#__PURE__*/_interopDefault(Ap);var Gc=Object.defineProperty;var va=i=>{throw TypeError(i)};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 G=(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&&Gc(t,e,o),o};var Ba=(i,t,e)=>t.has(i)||va("Cannot "+e);var ke=(i,t,e)=>(Ba(i,t,"read from private field"),e?e.call(i):t.get(i)),Qa=(i,t,e)=>t.has(i)?va("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Er=(i,t,e,r)=>(Ba(i,t,"write to private field"),t.set(i,e),e);var K=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};K.store=new WeakMap;var vr=Symbol("mongoProperties");function Br(){return (i,t)=>{let e=K.getMetadata(vr,i)||[];e.push(t),K.defineMetadata(vr,e,i);}}function ka(i){return K.getMetadata(vr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function Xc(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 ep(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function k(i,t){return t==="preserve"?i:t==="snake"?Xc(i):t==="camel"?ep(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}Ke__default.default.extend(op__default.default);Ke__default.default.extend(rp__default.default);Ke__default.default.extend(tp__default.default);var re=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=Ke__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()}},ot=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new f("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?Ke__default.default(i,t):Ke__default.default(i);if(!r.isValid())throw new f("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new f("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},ye=(i=new Date)=>Ke__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var Ka=(i,t)=>{try{let e=Me__default.default.createHash("sha256").update(i).digest(),r=Me__default.default.randomBytes(16),o=Me__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},La=(i,t)=>{try{let e=Me__default.default.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=Me__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),d=l.update(a,"hex","utf8");return d+=l.final("utf8"),d}catch(e){throw new f("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Fa=(i,t)=>{try{let e=Me__default.default.randomBytes(32),r=Me__default.default.randomBytes(16),o=Me__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=Me.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},ja=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=Me.privateDecrypt(i,Buffer.from(o,"hex")),a=Me__default.default.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new f("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var kr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Qr=kr.length,ap=10,lp=16,dp=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Qr;e=kr.charAt(o)+e,i=(i-o)/Qr;}return e},mp=i=>{let t=Me.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=kr.charAt(o%Qr);}return e},Ua=()=>{let i=Math.floor(Date.now()/1e3),t=dp(i,ap),e=mp(lp);return t+e};function Kr(i){return i.replace(/^[`"]|[`"]$/g,"")}function Lr(i,t,e){if(!i.includes(".")){let n=Kr(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=Kr(r),o=Kr(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function N(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 De=class{};De.modelCaseConvention="camel",De.databaseCaseConvention="snake";var up=async(i,t,e,r,o=[],n=[],s=false)=>{let a=new t,l=new Set(e.filter(u=>u.hidden).map(u=>u.columnName)),d=new Map(e.map(u=>[u.databaseName,u])),m=o.length?new Set(o):null;if(await Promise.all(Object.keys(i).map(async u=>{let c=i[u],p=d.get(u)?.columnName??k(u,t.modelCaseConvention);if(p==="$annotations"&&!s){cp(i,u,a,t,n);return}if(!r.has(p)||l.has(p)||m&&!m.has(p))return;if(c===null){a[p]=null;return}let h=r.get(p);if(h&&h.serialize){a[p]=await h.serialize(c);return}a[p]=c;})),m)for(let u of m)u in a||(a[u]=null);return a},cp=(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[k(l,r.modelCaseConvention)]=n[l]);Object.keys(a).length>0&&(e[t]=a);},he=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 m=d;if(m.includes(".")&&(m=m.split(".").pop()),m==="*")continue;let u=s.get(m)?.columnName??k(m,t.modelCaseConvention);a.push(u);}e=a;let l=await Promise.all(i.map(async d=>await up(d,t,n,s,e,r,o)));return l.length===1?l[0]:l};var v=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Ct={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 Va=null;function Wa(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(u=>u.columnName===n||u.databaseName===n);if(!l)continue;let d=typeof l.type=="string"?l.type:"string",m=Ct[d]||"string";if(m==="string"||m==="textarea"){i.whereLike(n,`%${a}%`);continue}if(m==="boolean"){i.where(n,a==="true"||a===true);continue}if(m==="date"||m==="datetime"){if(typeof a=="object"&&a!==null){let u=a;u.from&&i.where(n,">=",u.from),u.to&&i.where(n,"<=",u.to);continue}i.where(n,a);continue}i.where(n,a);}}function nt(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 pp(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Va;}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=Ct[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(m=>m.columnName===n||m.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",d=Ct[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 Wa(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return Wa(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(nt(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(nt(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(nt(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db});return nt(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 nt(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 fp(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function yp(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),t=await pp(),e=await fp();i.default.registerAdapter({Database:e,Resource:t});}async function Fr(i,t){Va=i;let e=await import('adminjs').catch(()=>{throw new v("adminjs")});await yp();let r=t.resources||Object.values(i.models);if(!r.length)throw new Error("No models provided for AdminJS. Please provide models in the resources option or register them in SqlDataSource.");let o=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),n={rootPath:t.rootPath||"/admin",resources:o};if(t.branding&&(n.branding=t.branding),t.locale?.language&&(n.locale=t.locale),t.assets&&(n.assets=t.assets),t.settings&&(n.settings=t.settings),t.pages){let a={};for(let[l,d]of Object.entries(t.pages))d.component&&(a[l]=d);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function Ha(i,t){let{admin:e}=await Fr(i,t),r;try{r=await import('@adminjs/express');}catch{throw new v("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var Ve=new Map,Ie=new Map,Rt=class{async get(t){return Ve.get(t)}async set(t,e,r){let o=Ie.get(t);if(o&&(clearTimeout(o),Ie.delete(t)),Ve.set(t,e),r){let n=setTimeout(()=>{Ve.delete(t),Ie.delete(t);},r);Ie.set(t,n);}}async invalidate(t){let e=Ie.get(t);e&&(clearTimeout(e),Ie.delete(t)),Ve.delete(t);}async invalidateAll(t){let e=Ve.keys();for(let r of e)if(r.startsWith(t)){let o=Ie.get(r);o&&(clearTimeout(o),Ie.delete(r)),Ve.delete(r);}}};var I={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},gp=()=>{try{Rc__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":I.DB_TYPE||(I.DB_TYPE=s);break;case "DB_HOST":I.DB_HOST||(I.DB_HOST=s);break;case "DB_PORT":I.DB_PORT||(I.DB_PORT=s);break;case "DB_USER":I.DB_USER||(I.DB_USER=s);break;case "DB_PASSWORD":I.DB_PASSWORD||(I.DB_PASSWORD=s);break;case "DB_DATABASE":I.DB_DATABASE||(I.DB_DATABASE=s);break;case "MIGRATION_PATH":I.MIGRATION_PATH||(I.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":I.REDIS_HOST||(I.REDIS_HOST=s);break;case "REDIS_PORT":I.REDIS_PORT||(I.REDIS_PORT=s);break;case "REDIS_USERNAME":I.REDIS_USERNAME||(I.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":I.REDIS_PASSWORD||(I.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":I.REDIS_DATABASE||(I.REDIS_DATABASE=s);break;case "MONGO_URL":I.MONGO_URL||(I.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":I.MSSQL_TRUST_SERVER_CERTIFICATE||(I.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return I}},M=gp();var He=class{constructor(t){switch(this.type=t?.type||M.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;case "oracledb":this.handleOracleDBSource(t);break;default:throw new f(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
3
- Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}}handleCockroachdbSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||M.DB_DATABASE||":memory:",this.logs=t?.logs||M.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||M.MONGO_URL,this.logs=t?.logs||M.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=1521);}};var bp=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},Tp=i=>i.openApi?.required??false,wp=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=bp(r));return e},Np=i=>{let t=i.getColumns(),e=[];for(let r of t)Tp(r)&&e.push(r.columnName);return e||[]},jr=i=>{let t=wp(i),e=Np(i);return {type:"object",properties:t,required:e.length?e:[]}},Zf=i=>i.map(t=>jr(t)),Xf=i=>jr(i),Ja=i=>i.map(t=>({...jr(t),modelName:t.name,$id:t.name}));var Ur=(i,t)=>{let e=Me__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var Je={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function Mp(){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 Wr(i,t){let e=Mp(),r=i.toUpperCase();return i==="error"?`${Je.error}[${r}] ${e}
4
- ${t}${Je.reset}
5
- `:i==="warn"?`${Je.warn}[${r}] ${e}
6
- ${t}${Je.reset}
7
- `:i==="info"?`${Je.info}[${r}] ${e}
8
- ${t}${Je.reset}
1
+ 'use strict';var _e=require('crypto'),je=require('dayjs'),pp=require('dayjs/plugin/customParseFormat.js'),fp=require('dayjs/plugin/timezone.js'),yp=require('dayjs/plugin/utc.js'),Kc=require('fs'),sqlHighlight=require('sql-highlight'),sqlFormatter=require('sql-formatter'),Rt=require('path'),Lp=require('pluralize'),stream=require('stream'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var _e__default=/*#__PURE__*/_interopDefault(_e);var je__default=/*#__PURE__*/_interopDefault(je);var pp__default=/*#__PURE__*/_interopDefault(pp);var fp__default=/*#__PURE__*/_interopDefault(fp);var yp__default=/*#__PURE__*/_interopDefault(yp);var Kc__default=/*#__PURE__*/_interopDefault(Kc);var Rt__default=/*#__PURE__*/_interopDefault(Rt);var Lp__default=/*#__PURE__*/_interopDefault(Lp);var dp=Object.defineProperty;var Fa=i=>{throw TypeError(i)};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 G=(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&&dp(t,e,o),o};var Ua=(i,t,e)=>t.has(i)||Fa("Cannot "+e);var Le=(i,t,e)=>(Ua(i,t,"read from private field"),e?e.call(i):t.get(i)),Wa=(i,t,e)=>t.has(i)?Fa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Br=(i,t,e,r)=>(Ua(i,t,"write to private field"),t.set(i,e),e);var k=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};k.store=new WeakMap;var Qr=Symbol("mongoProperties");function Kr(){return (i,t)=>{let e=k.getMetadata(Qr,i)||[];e.push(t),k.defineMetadata(Qr,e,i);}}function Va(i){return k.getMetadata(Qr,i.prototype)||[]}var f=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function mp(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 cp(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function K(i,t){return t==="preserve"?i:t==="snake"?mp(i):t==="camel"?cp(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}je__default.default.extend(yp__default.default);je__default.default.extend(fp__default.default);je__default.default.extend(pp__default.default);var re=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=je__default.default(i);if(e==="LOCAL"){let n=r.local();switch(t){case "ISO":return n.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return n.format("YYYY-MM-DD");case "TIME_ONLY":return n.format("HH:mm:ss");default:return n.unix().toString()}}let o=r.utc();switch(t){case "ISO":return o.format("YYYY-MM-DD HH:mm:ss");case "DATE_ONLY":return o.format("YYYY-MM-DD");case "TIME_ONLY":return o.format("HH:mm:ss");default:return o.unix().toString()}},st=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new f("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?je__default.default(i,t):je__default.default(i);if(!r.isValid())throw new f("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new f("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},he=(i=new Date)=>je__default.default(i).utc().format("YYYY-MM-DD HH:mm:ss");var Ja=(i,t)=>{try{let e=_e__default.default.createHash("sha256").update(i).digest(),r=_e__default.default.randomBytes(16),o=_e__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Ha=(i,t)=>{try{let e=_e__default.default.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=_e__default.default.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),d=l.update(a,"hex","utf8");return d+=l.final("utf8"),d}catch(e){throw new f("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Ya=(i,t)=>{try{let e=_e__default.default.randomBytes(32),r=_e__default.default.randomBytes(16),o=_e__default.default.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=_e.publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new f("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},za=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=_e.privateDecrypt(i,Buffer.from(o,"hex")),a=_e__default.default.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new f("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var Lr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",kr=Lr.length,Tp=10,wp=16,Np=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%kr;e=Lr.charAt(o)+e,i=(i-o)/kr;}return e},Sp=i=>{let t=_e.randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Lr.charAt(o%kr);}return e},Ga=()=>{let i=Math.floor(Date.now()/1e3),t=Np(i,Tp),e=Sp(wp);return t+e};function jr(i){return i.replace(/^[`"]|[`"]$/g,"")}function Fr(i,t,e){if(!i.includes(".")){let n=jr(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=jr(r),o=jr(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function N(i){return typeof i=="function"?i():i}var F=(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]=F(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]=F(o,t);}return e};var xe=class{};xe.modelCaseConvention="camel",xe.databaseCaseConvention="snake";var qp=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 c=i[m],p=d.get(m)?.columnName??K(m,t.modelCaseConvention);if(p==="$annotations"&&!s){Mp(i,m,a,t,n);return}if(!r.has(p)||l.has(p)||u&&!u.has(p))return;if(c===null){a[p]=null;return}let h=r.get(p);if(h&&h.serialize){a[p]=await h.serialize(c);return}a[p]=c;})),u)for(let m of u)m in a||(a[m]=null);return a},Mp=(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[K(l,r.modelCaseConvention)]=n[l]);Object.keys(a).length>0&&(e[t]=a);},ge=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??K(u,t.modelCaseConvention);a.push(m);}e=a;let l=await Promise.all(i.map(async d=>await qp(d,t,n,s,e,r,o)));return l.length===1?l[0]:l};var v=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var At={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 Xa=null;function Za(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=At[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 it(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 _p(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Xa;}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=At[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=At[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 Za(s,n,this._model),s.getCount()}async find(n,s={}){let a=this._model.query({connection:this._db});return Za(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(it(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(it(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(it(l,this._model),this)):[]}async create(n){let s=await this._model.insert(n,{connection:this._db});return it(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 it(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 Cp(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function Rp(){let i=await import('adminjs').catch(()=>{throw new v("adminjs")}),t=await _p(),e=await Cp();i.default.registerAdapter({Database:e,Resource:t});}async function Ur(i,t){Xa=i;let e=await import('adminjs').catch(()=>{throw new v("adminjs")});await Rp();let r=t.resources||Object.values(i.models);if(!r.length)throw new Error("No models provided for AdminJS. Please provide models in the resources option or register them in SqlDataSource.");let o=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),n={rootPath:t.rootPath||"/admin",resources:o};if(t.branding&&(n.branding=t.branding),t.locale?.language&&(n.locale=t.locale),t.assets&&(n.assets=t.assets),t.settings&&(n.settings=t.settings),t.pages){let a={};for(let[l,d]of Object.entries(t.pages))d.component&&(a[l]=d);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function el(i,t){let{admin:e}=await Ur(i,t),r;try{r=await import('@adminjs/express');}catch{throw new v("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var He=new Map,Ie=new Map,Ot=class{async get(t){return He.get(t)}async set(t,e,r){let o=Ie.get(t);if(o&&(clearTimeout(o),Ie.delete(t)),He.set(t,e),r){let n=setTimeout(()=>{He.delete(t),Ie.delete(t);},r);Ie.set(t,n);}}async invalidate(t){let e=Ie.get(t);e&&(clearTimeout(e),Ie.delete(t)),He.delete(t);}async invalidateAll(t){let e=He.keys();for(let r of e)if(r.startsWith(t)){let o=Ie.get(r);o&&(clearTimeout(o),Ie.delete(r)),He.delete(r);}}};var x={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},Op=()=>{try{Kc__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":x.DB_TYPE||(x.DB_TYPE=s);break;case "DB_HOST":x.DB_HOST||(x.DB_HOST=s);break;case "DB_PORT":x.DB_PORT||(x.DB_PORT=s);break;case "DB_USER":x.DB_USER||(x.DB_USER=s);break;case "DB_PASSWORD":x.DB_PASSWORD||(x.DB_PASSWORD=s);break;case "DB_DATABASE":x.DB_DATABASE||(x.DB_DATABASE=s);break;case "MIGRATION_PATH":x.MIGRATION_PATH||(x.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":x.REDIS_HOST||(x.REDIS_HOST=s);break;case "REDIS_PORT":x.REDIS_PORT||(x.REDIS_PORT=s);break;case "REDIS_USERNAME":x.REDIS_USERNAME||(x.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":x.REDIS_PASSWORD||(x.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":x.REDIS_DATABASE||(x.REDIS_DATABASE=s);break;case "MONGO_URL":x.MONGO_URL||(x.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":x.MSSQL_TRUST_SERVER_CERTIFICATE||(x.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return x}},M=Op();var Ye=class{constructor(t){switch(this.type=t?.type||M.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;case "oracledb":this.handleOracleDBSource(t);break;default:throw new f(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
3
+ Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}}handleCockroachdbSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||M.DB_DATABASE||":memory:",this.logs=t?.logs||M.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||M.MONGO_URL,this.logs=t?.logs||M.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||M.DB_HOST,this.port=+t?.port||+M.DB_PORT,this.username=t?.username||M.DB_USER,this.password=t?.password||M.DB_PASSWORD,this.database=t?.database||M.DB_DATABASE,this.logs=t?.logs||M.DB_LOGS||false,this.port||(this.port=1521);}};var Dp=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},xp=i=>i.openApi?.required??false,Ip=i=>{let t=i.getColumns(),e={};for(let r of t)r.hidden||(e[r.columnName]=Dp(r));return e},Pp=i=>{let t=i.getColumns(),e=[];for(let r of t)xp(r)&&e.push(r.columnName);return e||[]},Wr=i=>{let t=Ip(i),e=Pp(i);return {type:"object",properties:t,required:e.length?e:[]}},uy=i=>i.map(t=>Wr(t)),my=i=>Wr(i),tl=i=>i.map(t=>({...Wr(t),modelName:t.name,$id:t.name}));var Vr=(i,t)=>{let e=_e__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var ze={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function vp(){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 Jr(i,t){let e=vp(),r=i.toUpperCase();return i==="error"?`${ze.error}[${r}] ${e}
4
+ ${t}${ze.reset}
5
+ `:i==="warn"?`${ze.warn}[${r}] ${e}
6
+ ${t}${ze.reset}
7
+ `:i==="info"?`${ze.info}[${r}] ${e}
8
+ ${t}${ze.reset}
9
9
  `:`[${r}] ${e}
10
10
  ${t}
11
- `}var ze=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);}};ze.loggerInstance={info(t){console.log(Wr("info",t));},error(t){console.error(Wr("error",t));},warn(t){console.warn(Wr("warn",t));}};function _p(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 X(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} [${_p(e||[])}]`;ze.loggerInstance.info(r);}function za(i,t,e=false){e&&ze.loggerInstance[t](i);}var S=ze;var Vr=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},Ot=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)},Ga=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,Ot(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,Ot(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,Ot(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,Ot(t[r]));}return e},st=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,At=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:Vr(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var Hr=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:[]}}},Za=new Hr;var Jr=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Xa=new Jr;var zr=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},el=new zr;var Yr=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:[]}}},tl=new Yr;var w=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var Ye=class extends w{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var y=class{constructor(t){this.model=t;let e=Dt(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??k(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??k(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a==="*"||a==="$annotations"||(o.push(a),n.push(l));}await Promise.all(o.map(async(s,a)=>{let l=o[a],d=n[a],m=this.modelColumnsMap.get(l),u=d;m&&(r==="insert"&&m.prepare?u=await m.prepare(d):r==="update"&&(u=await m.prepare?.(d)??d)),n[a]=u;}));for(let s of this.modelColumnsMap.keys())if(!o.includes(s)){let a=this.modelColumnsMap.get(s);if(!a||r==="insert"&&s===this.model.primaryKey&&!a.prepare)continue;if(r==="insert"||a.autoUpdate){o.push(s);let l=a.prepare?await a.prepare(void 0):void 0;n.push(l??void 0);}}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var Gr=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 Ye){let m=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${m.newName}'`,bindings:[]}}let n=new b(this.model,"mssql"),s=[],a=[];for(let m of e.children){let{sql:u,bindings:c}=n.parse([m]);s.push(u.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},rl=new Gr;var Zr=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},ol=new Zr;var Xr=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},nl=new Xr;var eo=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},sl=new eo;var to=class{toSql(t){let e=t;return S.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},il=new to;var ro=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},al=new ro;var oo=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},ll=new oo;var no=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},dl=new no;var C=class extends w{constructor(e){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e;}};var so=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},ml=new so;var io=class{toSql(t){let e=t;return S.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},ul=new io;var ao=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mssql",N(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:[]}:n==="geometry"?{sql:`${o} geometry`,bindings:[]}:n==="point"?{sql:`${o} geometry`,bindings:[]}:n==="linestring"?{sql:`${o} geometry`,bindings:[]}:n==="polygon"?{sql:`${o} geometry`,bindings:[]}:n==="multipoint"?{sql:`${o} geometry`,bindings:[]}:{sql:`${o} ${n}${e.length?`(${e.length})`:""}`,bindings:[]}}},cl=new ao;var lo=class{toSql(t){return {sql:"",bindings:[]}}},pl=new lo;var mo=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",N(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",N(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 C?{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",N(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",N(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:[]}}},fl=new mo;var uo=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 m of e.children){let{sql:u,bindings:c}=n.parse([m]);if(m.folder==="constraint"){let p=s.pop()??"",h=u;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let g=`${p} ${h}`.trim();g=g.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(g),a.push(...c);continue}s.push(p),s.push(h),a.push(...c);continue}s.push(u),a.push(...c);}for(let m of e.namedConstraints){let{sql:u,bindings:c}=n.parse([m]);s.push(u),a.push(...c);}let l=s.join(", ");return {sql:`${o} (${l})`,bindings:a}}},yl=new uo;var co=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:[]}}},hl=new co;var po=class{toSql(t){return {sql:"",bindings:[]}}},gl=new po;var fo=class{toSql(t){return S.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},bl=new fo;var yo=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Tl=new yo;var ho=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},wl=new ho;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("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}}},Nl=new go;var bo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},Sl=new bo;var To=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new 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}}},ql=new To;var wo=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:[]}}},Ml=new wo;var No=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},_l=new No;var So=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(c=>n[c]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("mssql",c)).join(", "),l=[],d=[],m=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g of p)g instanceof C?h.push(g.rawValue):(l.push(g),h.push(`@${m++}`));d.push(`(${h.join(", ")})`);}let u=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>`inserted.${r.formatStringColumn("mssql",p)}`).join(", ");u=u.replace(") values",`) output ${c} values`);}else {let c=this.getOutputColumns(s,r);u=u.replace(") values",`) output ${c} values`);}return {sql:u,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(", ")}},Cl=new So;var qo=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:[]}}},Rl=new qo;var Mo=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},Ol=new Mo;var _o=class{toSql(t){return {sql:"",bindings:[]}}},Al=new _o;var Co=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},Dl=new Co;var Ro=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(S.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:[]})}},Il=new Ro;var Oo=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:[]}}},xl=new Oo;var Ao=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Pl=new Ao;var Do=class{toSql(t){return {sql:`SELECT
11
+ `}var Ge=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){if(t instanceof Error){this.loggerInstance.error(String(t));return}this.loggerInstance.error(t);}static warn(t){this.loggerInstance.warn(t);}};Ge.loggerInstance={info(t){console.log(Jr("info",t));},error(t){console.error(Jr("error",t));},warn(t){console.warn(Jr("warn",t));}};function Bp(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 X(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} [${Bp(e||[])}]`;Ge.loggerInstance.info(r);}function rl(i,t,e=false){e&&Ge.loggerInstance[t](i);}var S=Ge;var Hr=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},Dt=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)},nl=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,Dt(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,Dt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,Dt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,Dt(t[r]));}return e},at=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,xt=(i,t)=>{let e=i.getDbType(),r;try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions,language:Hr(e)});}catch{try{r=sqlFormatter.format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var Yr=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:[]}}},sl=new Yr;var zr=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},il=new zr;var Gr=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},al=new Gr;var Zr=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:[]}}},ll=new Zr;var T=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var Ze=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=It(t);this.modelColumnsMap=new Map(e.map(r=>[r.columnName,r]));}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??K(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??K(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s];a==="*"||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;if(r==="insert"||a.autoUpdate){o.push(s);let l=a.prepare?await a.prepare(void 0):void 0;n.push(l??void 0);}}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var Xr=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 Ze){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:c}=n.parse([u]);s.push(m.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},dl=new Xr;var eo=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},ul=new eo;var to=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},ml=new to;var ro=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},cl=new ro;var oo=class{toSql(t){let e=t;return S.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},pl=new oo;var no=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},fl=new no;var so=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},yl=new so;var io=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},hl=new io;var C=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 ao=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},gl=new ao;var lo=class{toSql(t){let e=t;return S.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},bl=new lo;var uo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mssql",N(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:[]}:n==="geometry"?{sql:`${o} geometry`,bindings:[]}:n==="point"?{sql:`${o} geometry`,bindings:[]}:n==="linestring"?{sql:`${o} geometry`,bindings:[]}:n==="polygon"?{sql:`${o} geometry`,bindings:[]}:n==="multipoint"?{sql:`${o} geometry`,bindings:[]}:{sql:`${o} ${n}${e.length?`(${e.length})`:""}`,bindings:[]}}},Tl=new uo;var mo=class{toSql(t){return {sql:"",bindings:[]}}},wl=new mo;var co=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",N(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",N(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 C?{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",N(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",N(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:[]}}},Nl=new co;var po=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:c}=n.parse([u]);if(u.folder==="constraint"){let p=s.pop()??"",h=m;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let g=`${p} ${h}`.trim();g=g.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(g),a.push(...c);continue}s.push(p),s.push(h),a.push(...c);continue}s.push(m),a.push(...c);}for(let u of e.namedConstraints){let{sql:m,bindings:c}=n.parse([u]);s.push(m),a.push(...c);}let l=s.join(", ");return {sql:`${o} (${l})`,bindings:a}}},Sl=new po;var fo=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:[]}}},ql=new fo;var yo=class{toSql(t){return {sql:"",bindings:[]}}},Ml=new yo;var ho=class{toSql(t){return S.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},_l=new ho;var go=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Cl=new go;var bo=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Rl=new bo;var To=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}}},Al=new To;var wo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},Ol=new wo;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}}},Dl=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:[]}}},xl=new So;var qo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},Il=new qo;var Mo=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(c=>n[c]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("mssql",c)).join(", "),l=[],d=[],u=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g of p)g instanceof C?h.push(g.rawValue):(l.push(g),h.push(`@${u++}`));d.push(`(${h.join(", ")})`);}let m=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>`inserted.${r.formatStringColumn("mssql",p)}`).join(", ");m=m.replace(") values",`) output ${c} values`);}else {let c=this.getOutputColumns(s,r);m=m.replace(") values",`) output ${c} 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(", ")}},Pl=new Mo;var _o=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:[]}}},$l=new _o;var Co=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},El=new Co;var Ro=class{toSql(t){return {sql:"",bindings:[]}}},vl=new Ro;var Ao=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},Bl=new Ao;var Oo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(S.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:[]})}},Ql=new Oo;var Do=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:[]}}},Kl=new Do;var xo=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},kl=new xo;var Io=class{toSql(t){return {sql:`SELECT
12
12
  fk.name as name,
13
13
  c.name as column_name,
14
14
  rt.name as referenced_table,
@@ -20,7 +20,7 @@ INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_i
20
20
  INNER JOIN sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
21
21
  INNER JOIN sys.tables rt ON fkc.referenced_object_id = rt.object_id
22
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:[]}}},$l=new Do;var Io=class{toSql(t){return {sql:`SELECT
23
+ WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},Ll=new Io;var Po=class{toSql(t){return {sql:`SELECT
24
24
  i.name as index_name,
25
25
  c.name as column_name,
26
26
  i.is_unique as is_unique
@@ -29,7 +29,7 @@ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = i
29
29
  INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
30
30
  WHERE i.object_id = OBJECT_ID('${t.table}')
31
31
  AND i.is_primary_key = 0
32
- AND i.type > 0`,bindings:[]}}},El=new Io;var xo=class{toSql(t){return {sql:`SELECT
32
+ AND i.type > 0`,bindings:[]}}},jl=new Po;var $o=class{toSql(t){return {sql:`SELECT
33
33
  tc.CONSTRAINT_NAME as name,
34
34
  kcu.COLUMN_NAME as column_name
35
35
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
@@ -37,7 +37,7 @@ JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
37
37
  ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
38
38
  WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
39
39
  AND tc.TABLE_NAME = '${t.table}'
40
- ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},vl=new xo;var Po=class{toSql(t){return {sql:`SELECT
40
+ ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},Fl=new $o;var Eo=class{toSql(t){return {sql:`SELECT
41
41
  c.COLUMN_NAME as column_name,
42
42
  c.DATA_TYPE as data_type,
43
43
  c.IS_NULLABLE as is_nullable,
@@ -47,7 +47,7 @@ ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},vl=new xo;var Po=class{toSql(t){re
47
47
  c.NUMERIC_SCALE as numeric_scale
48
48
  FROM INFORMATION_SCHEMA.COLUMNS c
49
49
  WHERE c.TABLE_NAME = '${t.table}'
50
- ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},Bl=new Po;var $o=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}]`:""}},Ql=new $o;var Eo=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:[]}}},kl=new Eo;var vo=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}}},Kl=new vo;var Bo=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 m=e.currParamIndex+d-n,u=e.values[d];return u instanceof C?(n++,`${r.formatStringColumn("mssql",l)} = ${u.rawValue}`):(s.push(u),`${r.formatStringColumn("mssql",l)} = @${m}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Ll=new Bo;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 m=`@${o} AND @${o+1}`,u=`${a} between ${m}`;return e.isNegated&&(u=`not (${u})`),{sql:u.trim(),bindings:r}}let l=r.map((m,u)=>`@${o+u}`).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}},Fl=new Qo;var ko=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}}},jl=new ko;var Ko=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}}},Ul=new Ko;var Lo=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}}},Wl=new Lo;var Fo=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"&&S.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},Vl=new Fo;var jo=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:[]}}},Hl=new jo;var Uo=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Jl=new Uo;var Wo=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},zl=new Wo;var Vo=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:[]}}},Yl=new Vo;var Ho=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 c of e.children){let{sql:p,bindings:h}=n.parse([c]);if(c.file==="add_column")s.push(p);else if(c.file==="add_constraint"||c.folder==="constraint"){let g=s[s.length-1]??"",T=/^\s*add\s+column\b/i.test(g),_=/^\s*add\s+constraint\b/i.test(p);if(T&&!_){let $=p.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${g} ${$}`;}else {let $=/^\s*add\b/i.test(p)?p:`add ${p}`;s.push($);}}else c.file==="set_default"||c.file==="drop_default"||c.file==="set_not_null"||c.file,s.push(p);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}}},Gl=new Ho;var Jo=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Zl=new Jo;var zo=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},Xl=new zo;var Yo=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},ed=new Yo;var Go=class{toSql(t){return {sql:"",bindings:[]}}},td=new Go;var Zo=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},rd=new Zo;var Xo=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},od=new Xo;var en=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},nd=new en;var tn=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},sd=new tn;var rn=class{toSql(t){return {sql:"",bindings:[]}}},id=new rn;var on=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mysql",N(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:[]}}else {if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},ad=new on;var nn=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},ld=new nn;var sn=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",N(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",N(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 C?{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",N(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",N(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:[]}}},dd=new sn;var an=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 u of e.children){let{sql:c,bindings:p}=n.parse([u]);if(u.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let T=`${h} ${g}`.trim();T=T.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(T),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let u of e.namedConstraints){let{sql:c,bindings:p}=n.parse([u]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},md=new an;var ln=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:[]}}},ud=new ln;var dn=class{toSql(t){return {sql:"distinct",bindings:[]}}},cd=new dn;var mn=class{toSql(t){return S.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},pd=new mn;var un=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},fd=new un;var cn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},yd=new cn;var pn=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}}},hd=new pn;var fn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},gd=new fn;var yn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new 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}}},bd=new yn;var hn=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:[]}}},Td=new hn;var gn=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:[]}}},wd=new gn;var bn=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(u=>r.formatStringColumn("mysql",u)).join(", "),l=[],d=[];for(let u of e.records){let c=s.map(h=>u[h]),p=[];for(let h of c)h instanceof C?p.push(h.rawValue):(l.push(h),p.push("?"));d.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Nd=new bn;var Tn=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:[]}}},Sd=new Tn;var wn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},qd=new wn;var Cp={for_update:"for update",for_share:"lock in share mode"},Nn=class{toSql(t){let e=t,r=Cp[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},Md=new Nn;var Sn=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},_d=new Sn;var qn=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:[]}}},Cd=new qn;var Mn=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:[]}}},Rd=new Mn;var _n=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Od=new _n;var Cn=class{toSql(t){return {sql:`SELECT
50
+ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},Ul=new Eo;var vo=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}]`:""}},Wl=new vo;var de=class i{constructor(t){this.segments=this.normalize(t);}normalize(t){if(Array.isArray(t))return t;if(typeof t=="string"){if(!t||t==="$")return [];let e=t.trim();return e=e.startsWith("$.")?e.slice(2):e,e=e.startsWith("$")?e.slice(1):e,e=e.startsWith(".")?e.slice(1):e,e?e.split(".").map(r=>{let o=Number(r);return isNaN(o)?r:o}):[]}return []}getSegments(){return [...this.segments]}isEmpty(){return this.segments.length===0}toPostgres(t=false){if(this.isEmpty())return "";let e=[];for(let r=0;r<this.segments.length;r++){let o=this.segments[r],n=r===this.segments.length-1,s=typeof o=="number";n&&t?e.push(s?`->>${o}`:`->>'${o}'`):e.push(s?`->${o}`:`->'${o}'`);}return e.join("")}toStandardJsonPath(){return this.isEmpty()?"$":`$.${this.segments.join(".")}`}toMysql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments){if(typeof e=="number"){t.push(`[${e}]`);continue}t.push(`.${e}`);}return t.join("")}toSqlite(){return this.toStandardJsonPath()}toMssql(){if(this.isEmpty())return "$";let t=["$"];for(let e of this.segments)typeof e=="number"?t.push(`[${e}]`):t.push(`.${e}`);return t.join("")}toOracle(){return this.toStandardJsonPath()}toDbSyntax(t,e=false){switch(t){case "postgres":case "cockroachdb":return this.toPostgres(e);case "mysql":case "mariadb":return this.toMysql();case "sqlite":return this.toSqlite();case "mssql":return this.toMssql();case "oracledb":return this.toOracle();default:return this.toStandardJsonPath()}}static from(t){return new i(t)}static root(){return new i("")}};var Bo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("mssql",e.column),o=de.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMssql();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toMssql();return `(SELECT COUNT(*) FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}buildObjectKeysSql(t,e){let r=e.toMssql();return `(SELECT [key] FROM OPENJSON(${r==="$"?t:`JSON_QUERY(${t}, '${r}')`}))`}formatWithAlias(t,e){return e&&e.length>0?`${t} as [${e}]`:t}},Vl=new Bo;var Qo=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:[]}}},Jl=new Qo;var Ko=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}}},Hl=new Ko;var ko=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 C?(n++,`${r.formatStringColumn("mssql",l)} = ${m.rawValue}`):(s.push(m),`${r.formatStringColumn("mssql",l)} = @${u}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Yl=new ko;var Lo=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}},zl=new Lo;var jo=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}}},Gl=new jo;var Fo=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}}},Zl=new Fo;var Uo=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}}},Xl=new Uo;var Wo=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"&&S.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},ed=new Wo;var Vo=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:[]}}},td=new Vo;var Jo=class{toSql(t){let e=t,r=new b(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},rd=new Jo;var Ho=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},od=new Ho;var Yo=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:[]}}},nd=new Yo;var zo=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 c of e.children){let{sql:p,bindings:h}=n.parse([c]);if(c.file==="add_column")s.push(p);else if(c.file==="add_constraint"||c.folder==="constraint"){let g=s[s.length-1]??"",w=/^\s*add\s+column\b/i.test(g),_=/^\s*add\s+constraint\b/i.test(p);if(w&&!_){let $=p.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${g} ${$}`;}else {let $=/^\s*add\b/i.test(p)?p:`add ${p}`;s.push($);}}else c.file==="set_default"||c.file==="drop_default"||c.file==="set_not_null"||c.file,s.push(p);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}}},sd=new zo;var Go=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},id=new Go;var Zo=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},ad=new Zo;var Xo=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},ld=new Xo;var en=class{toSql(t){return {sql:"",bindings:[]}}},dd=new en;var tn=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},ud=new tn;var rn=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},md=new rn;var on=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},cd=new on;var nn=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},pd=new nn;var sn=class{toSql(t){return {sql:"",bindings:[]}}},fd=new sn;var an=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mysql",N(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:[]}}else {if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},yd=new an;var ln=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},hd=new ln;var dn=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",N(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",N(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 C?{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",N(d))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("mysql",N(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:[]}}},gd=new dn;var un=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:c,bindings:p}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let w=`${h} ${g}`.trim();w=w.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(w),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let m of e.namedConstraints){let{sql:c,bindings:p}=n.parse([m]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},bd=new un;var mn=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:[]}}},Td=new mn;var cn=class{toSql(t){return {sql:"distinct",bindings:[]}}},wd=new cn;var pn=class{toSql(t){return S.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},Nd=new pn;var fn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Sd=new fn;var yn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},qd=new yn;var hn=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}}},Md=new hn;var gn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},_d=new gn;var bn=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}}},Cd=new bn;var Tn=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:[]}}},Rd=new Tn;var wn=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:[]}}},Ad=new wn;var Nn=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 c=s.map(h=>m[h]),p=[];for(let h of c)h instanceof C?p.push(h.rawValue):(l.push(h),p.push("?"));d.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},Od=new Nn;var Sn=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:[]}}},Dd=new Sn;var qn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},xd=new qn;var Qp={for_update:"for update",for_share:"lock in share mode"},Mn=class{toSql(t){let e=t,r=Qp[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},Id=new Mn;var _n=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Pd=new _n;var Cn=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:[]}}},$d=new Cn;var Rn=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:[]}}},Ed=new Rn;var An=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},vd=new An;var On=class{toSql(t){return {sql:`SELECT
51
51
  k.CONSTRAINT_NAME AS name,
52
52
  k.COLUMN_NAME AS column_name,
53
53
  k.REFERENCED_TABLE_NAME AS referenced_table,
@@ -58,12 +58,12 @@ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},Bl=new Po;var $o=class{toSql(t){let
58
58
  JOIN information_schema.REFERENTIAL_CONSTRAINTS r
59
59
  ON k.CONSTRAINT_NAME = r.CONSTRAINT_NAME AND k.CONSTRAINT_SCHEMA = r.CONSTRAINT_SCHEMA
60
60
  WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.REFERENCED_TABLE_NAME IS NOT NULL
61
- ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},Ad=new Cn;var Rn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},Dd=new Rn;var On=class{toSql(t){return {sql:`SELECT
61
+ ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},Bd=new On;var Dn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},Qd=new Dn;var xn=class{toSql(t){return {sql:`SELECT
62
62
  CONSTRAINT_NAME AS name,
63
63
  COLUMN_NAME AS column_name
64
64
  FROM information_schema.KEY_COLUMN_USAGE k
65
65
  WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.CONSTRAINT_NAME = 'PRIMARY'
66
- ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},Id=new On;var An=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:[]}}},xd=new An;var Dn=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}\``:""}},Pd=new Dn;var In=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:[]}}},$d=new In;var xn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Ed=new xn;var Pn=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 C?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},vd=new Pn;var $n=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}},Bd=new $n;var En=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}}},Qd=new En;var vn=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}}},kd=new vn;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 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}}},Kd=new Bn;var Qn=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}}},Ld=new Qn;var kn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Fd=new kn;var Kn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},jd=new Kn;var Ln=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Ud=new Ln;var Fn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify "${e.column}" ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`modify "${e.column}" null`:`modify "${e.column}" not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, modify "${e.column}" default null`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"?l="1":l==="FALSE"?l="0":l=`'${l}'`),a+=`, modify "${e.column}" default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},Wd=new Fn;var jn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let m of e.children){let{sql:u,bindings:c}=n.parse([m]);s.push(u.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Vd=new jn;var Un=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Hd=new Un;var Wn=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Jd=new Wn;var Vn=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},zd=new Vn;var Hn=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},Yd=new Hn;var Jn=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Gd=new Jn;var zn=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Zd=new zn;var Yn=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},Xd=new Yn;var Gn=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`modify "${e.column}" default ${r}`,bindings:[]}}},em=new Gn;var Zn=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},tm=new Zn;var Xn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("oracledb",N(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar2(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} clob`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar2(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar2(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} number(19) generated by default as identity`,bindings:[]}:{sql:`${o} number(19)`,bindings:[]};if(n==="tinyint")return {sql:`${o} number(3)`,bindings:[]};if(n==="smallint")return {sql:`${o} number(5)`,bindings:[]};if(n==="mediumint")return {sql:`${o} number(7)`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} binary_float`,bindings:[]};if(n==="double")return {sql:`${o} binary_double`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} number(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} number(4)`,bindings:[]};if(n==="time")return {sql:`${o} varchar2(8)`,bindings:[]};if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":"",a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${a}${s}`.trimEnd(),bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} number(1)`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} clob`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar2(255)`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} number(10) generated by default as identity`,bindings:[]}:{sql:`${o} number(10)`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} sdo_geometry`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},rm=new Xn;var es=class{toSql(t){return {sql:"",bindings:[]}}},om=new es;var ts=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("oracledb",N(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("oracledb",N(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 C?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("oracledb",N(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("oracledb",N(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},nm=new ts;var rs=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let m of e.children){let{sql:u,bindings:c}=n.parse([m]);if(m.folder==="constraint"){let p=s.pop()??"",h=u;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let g=`${p} ${h}`.trim();g=g.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),g=g.replace(/(check\s*\([^)]+\))\s+(default\s+(?:'[^']*'|\S+))/i,"$2 $1"),s.push(g),a.push(...c);continue}s.push(p),s.push(h),a.push(...c);continue}s.push(u),a.push(...c);}for(let m of e.namedConstraints){let{sql:u,bindings:c}=n.parse([m]);s.push(u),a.push(...c);}let l=s.join(", ");return {sql:`${o} (${l})`,bindings:a}}},sm=new rs;var os=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("oracledb",e.fromNode),bindings:[]}}},im=new os;var ns=class{toSql(t){return {sql:"",bindings:[]}}},am=new ns;var ss=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},lm=new ss;var is=class{toSql(t){let e=t;return {sql:`${new y(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},dm=new is;var as=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},mm=new as;var ls=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("oracledb",e.table)} "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("oracledb",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},um=new ls;var ds=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},cm=new ds;var ms=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},pm=new ms;var us=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},fm=new us;var cs=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},ym=new cs;var ps=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("oracledb",c)).join(", "),l=[],d=[],m=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g of p)g instanceof C?h.push(g.rawValue):(l.push(g),h.push(`:${m++}`));d.push(`(${h.join(", ")})`);}let u;if(e.records.length===1)u=`${o} (${a}) values ${d[0]}`;else {e.keyword="insert",m=e.currParamIndex;let c=[];for(let p of e.records){let h=s.map(T=>p[T]),g=[];for(let T of h)T instanceof C?g.push(T.rawValue):g.push(`:${m++}`);c.push(`into ${o} (${a}) values (${g.join(", ")})`);}u=`all ${c.join(" ")} select * from dual`;}return {sql:u,bindings:l}}},hm=new ps;var fs=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("oracledb",o),a=r.formatStringColumn("oracledb",n);return {sql:`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},gm=new fs;var ys=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},bm=new ys;var Rp={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},hs=class{toSql(t){let e=t,r=Rp[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Tm=new hs;var gs=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},wm=new gs;var bs=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("oracledb",a)).join(" AND ");if(e.mode==="ignore")return {sql:`on (${o})`,bindings:[]};let n=e.columnsToUpdate.map(a=>`target.${r.formatStringColumn("oracledb",a)} = source.${r.formatStringColumn("oracledb",a)}`).join(", ");return {sql:`on (${o}) when matched then update set ${n}`,bindings:[]}}},Nm=new bs;var Ts=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("oracledb",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Sm=new Ts;var ws=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},qm=new ws;var Ns=class{toSql(t){return {sql:`SELECT
66
+ ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},Kd=new xn;var In=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:[]}}},kd=new In;var Pn=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}\``:""}},Ld=new Pn;var $n=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("mysql",e.column),o=de.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toMysql();return r==="$"?t:`JSON_EXTRACT(${t}, '${r}')`}buildExtractTextSql(t,e){let r=e.toMysql();return r==="$"?`JSON_UNQUOTE(${t})`:`JSON_UNQUOTE(JSON_EXTRACT(${t}, '${r}'))`}buildArrayLengthSql(t,e){let r=e.toMysql();return r==="$"?`JSON_LENGTH(${t})`:`JSON_LENGTH(${t}, '${r}')`}buildObjectKeysSql(t,e){let r=e.toMysql();return r==="$"?`JSON_KEYS(${t})`:`JSON_KEYS(${t}, '${r}')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as \`${e}\``:t}},jd=new $n;var En=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:[]}}},Fd=new En;var vn=class{toSql(t){let e=t,r=new b(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Ud=new vn;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 C?`${r.formatStringColumn("mysql",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},Wd=new Bn;var Qn=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}},Vd=new Qn;var Kn=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}}},Jd=new Kn;var kn=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}}},Hd=new kn;var Ln=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}}},Yd=new Ln;var jn=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}}},zd=new jn;var Fn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Gd=new Fn;var Un=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Zd=new Un;var Wn=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Xd=new Wn;var Vn=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify "${e.column}" ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`modify "${e.column}" null`:`modify "${e.column}" not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, modify "${e.column}" default null`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"?l="1":l==="FALSE"?l="0":l=`'${l}'`),a+=`, modify "${e.column}" default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},eu=new Vn;var Jn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:c}=n.parse([u]);s.push(m.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},tu=new Jn;var Hn=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},ru=new Hn;var Yn=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},ou=new Yn;var zn=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},nu=new zn;var Gn=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},su=new Gn;var Zn=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},iu=new Zn;var Xn=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},au=new Xn;var es=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},lu=new es;var ts=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`modify "${e.column}" default ${r}`,bindings:[]}}},du=new ts;var rs=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},uu=new rs;var os=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("oracledb",N(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let s=e.length??1;return {sql:`${o} char(${s})`,bindings:[]}}else if(n==="varchar"){let s=e.length??255;return {sql:`${o} varchar2(${s})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} clob`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar2(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar2(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} number(19) generated by default as identity`,bindings:[]}:{sql:`${o} number(19)`,bindings:[]};if(n==="tinyint")return {sql:`${o} number(3)`,bindings:[]};if(n==="smallint")return {sql:`${o} number(5)`,bindings:[]};if(n==="mediumint")return {sql:`${o} number(7)`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} binary_float`,bindings:[]};if(n==="double")return {sql:`${o} binary_double`,bindings:[]};if(n==="decimal"||n==="numeric"){let s=e.precision??10,a=e.scale??0;return {sql:`${o} number(${s}, ${a})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} number(4)`,bindings:[]};if(n==="time")return {sql:`${o} varchar2(8)`,bindings:[]};if(n==="datetime"||n==="timestamp"){let s=e.withTimezone?" with time zone":"",a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} timestamp${a}${s}`.trimEnd(),bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} number(1)`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} clob`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let s=e.enumValues.map(a=>`'${a}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${s}))`,bindings:[]}}return {sql:`${o} varchar2(255)`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} number(10) generated by default as identity`,bindings:[]}:{sql:`${o} number(10)`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} sdo_geometry`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},mu=new os;var ns=class{toSql(t){return {sql:"",bindings:[]}}},cu=new ns;var ss=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("oracledb",N(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("oracledb",N(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 C?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"?{sql:"default 1",bindings:[]}:o==="FALSE"?{sql:"default 0",bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(d=>r.formatStringColumn("oracledb",N(d))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(d=>r.formatStringColumn("oracledb",N(d))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return {sql:"",bindings:[]}}},pu=new ss;var is=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new b(this.model,"oracledb"),s=[],a=[];for(let u of e.children){let{sql:m,bindings:c}=n.parse([u]);if(u.folder==="constraint"){let p=s.pop()??"",h=m;if(/not null/i.test(h)||/null/i.test(h)||/default/i.test(h)){let g=`${p} ${h}`.trim();g=g.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),g=g.replace(/(check\s*\([^)]+\))\s+(default\s+(?:'[^']*'|\S+))/i,"$2 $1"),s.push(g),a.push(...c);continue}s.push(p),s.push(h),a.push(...c);continue}s.push(m),a.push(...c);}for(let u of e.namedConstraints){let{sql:m,bindings:c}=n.parse([u]);s.push(m),a.push(...c);}let l=s.join(", ");return {sql:`${o} (${l})`,bindings:a}}},fu=new is;var as=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("oracledb",e.fromNode),bindings:[]}}},yu=new as;var ls=class{toSql(t){return {sql:"",bindings:[]}}},hu=new ls;var ds=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},gu=new ds;var us=class{toSql(t){let e=t;return {sql:`${new y(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},bu=new us;var ms=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Tu=new ms;var cs=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("oracledb",e.table)} "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("oracledb",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new b(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},wu=new cs;var ps=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},Nu=new ps;var fs=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("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Su=new fs;var ys=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("oracledb",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},qu=new ys;var hs=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},Mu=new hs;var gs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("oracledb",c)).join(", "),l=[],d=[],u=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g of p)g instanceof C?h.push(g.rawValue):(l.push(g),h.push(`:${u++}`));d.push(`(${h.join(", ")})`);}let m;if(e.records.length===1)m=`${o} (${a}) values ${d[0]}`;else {e.keyword="insert",u=e.currParamIndex;let c=[];for(let p of e.records){let h=s.map(w=>p[w]),g=[];for(let w of h)w instanceof C?g.push(w.rawValue):g.push(`:${u++}`);c.push(`into ${o} (${a}) values (${g.join(", ")})`);}m=`all ${c.join(" ")} select * from dual`;}return {sql:m,bindings:l}}},_u=new gs;var bs=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("oracledb",o),a=r.formatStringColumn("oracledb",n);return {sql:`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,bindings:[]}}},Cu=new bs;var Ts=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},Ru=new Ts;var Kp={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},ws=class{toSql(t){let e=t,r=Kp[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Au=new ws;var Ns=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},Ou=new Ns;var Ss=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("oracledb",a)).join(" AND ");if(e.mode==="ignore")return {sql:`on (${o})`,bindings:[]};let n=e.columnsToUpdate.map(a=>`target.${r.formatStringColumn("oracledb",a)} = source.${r.formatStringColumn("oracledb",a)}`).join(", ");return {sql:`on (${o}) when matched then update set ${n}`,bindings:[]}}},Du=new Ss;var qs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("oracledb",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},xu=new qs;var Ms=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Iu=new Ms;var _s=class{toSql(t){return {sql:`SELECT
67
67
  c.constraint_name as name,
68
68
  cc.column_name as column_name,
69
69
  rc.table_name as referenced_table,
@@ -75,7 +75,7 @@ JOIN user_constraints rc ON c.r_constraint_name = rc.constraint_name
75
75
  JOIN user_cons_columns rcc ON rc.constraint_name = rcc.constraint_name AND cc.position = rcc.position
76
76
  WHERE c.constraint_type = 'R'
77
77
  AND c.table_name = '${t.table.toUpperCase()}'
78
- ORDER BY cc.position`,bindings:[]}}},Mm=new Ns;var Ss=class{toSql(t){return {sql:`SELECT
78
+ ORDER BY cc.position`,bindings:[]}}},Pu=new _s;var Cs=class{toSql(t){return {sql:`SELECT
79
79
  i.index_name as index_name,
80
80
  ic.column_name as column_name,
81
81
  CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END as is_unique
@@ -88,14 +88,14 @@ WHERE i.table_name = '${t.table.toUpperCase()}'
88
88
  WHERE c.constraint_type = 'P'
89
89
  AND c.index_name = i.index_name
90
90
  )
91
- ORDER BY i.index_name, ic.column_position`,bindings:[]}}},_m=new Ss;var qs=class{toSql(t){return {sql:`SELECT
91
+ ORDER BY i.index_name, ic.column_position`,bindings:[]}}},$u=new Cs;var Rs=class{toSql(t){return {sql:`SELECT
92
92
  c.constraint_name as name,
93
93
  cc.column_name as column_name
94
94
  FROM user_constraints c
95
95
  JOIN user_cons_columns cc ON c.constraint_name = cc.constraint_name
96
96
  WHERE c.constraint_type = 'P'
97
97
  AND c.table_name = '${t.table.toUpperCase()}'
98
- ORDER BY cc.position`,bindings:[]}}},Cm=new qs;var Ms=class{toSql(t){return {sql:`SELECT
98
+ ORDER BY cc.position`,bindings:[]}}},Eu=new Rs;var As=class{toSql(t){return {sql:`SELECT
99
99
  column_name,
100
100
  data_type,
101
101
  CASE WHEN nullable = 'Y' THEN 'YES' ELSE 'NO' END as is_nullable,
@@ -105,7 +105,7 @@ ORDER BY cc.position`,bindings:[]}}},Cm=new qs;var Ms=class{toSql(t){return {sql
105
105
  data_scale as numeric_scale
106
106
  FROM user_tab_columns
107
107
  WHERE table_name = '${t.table.toUpperCase()}'
108
- ORDER BY column_id`,bindings:[]}}},Rm=new Ms;var _s=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("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},Om=new _s;var Cs=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},Am=new Cs;var Rs=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Dm=new Rs;var Os=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("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,d)=>{let m=e.values[d];return m instanceof C?`${r.formatStringColumn("oracledb",l)} = ${m.rawValue}`:(s.push(m),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Im=new Os;var As=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("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new y(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("oracledb",t):t}},xm=new As;var Ds=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Pm=new Ds;var Is=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new y(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},$m=new Is;var xs=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Em=new xs;var Ps=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},vm=new Ps;var $s=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:[]}}},Bm=new $s;var Es=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Qm=new Es;var vs=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},km=new vs;var Bs=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:[]}}},Km=new Bs;var Qs=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 u of e.children){let{sql:c,bindings:p}=n.parse([u]);s.push(c.trim()),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},Lm=new Qs;var ks=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Fm=new ks;var Ks=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},jm=new Ks;var Ls=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Um=new Ls;var Fs=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Wm=new Fs;var js=class{toSql(t){return {sql:"",bindings:[]}}},Vm=new js;var Us=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Hm=new Us;var Ws=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Jm=new Ws;var Vs=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},zm=new Vs;var Hs=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Ym=new Hs;var Js=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("postgres",N(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:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Gm=new Js;var zs=class{toSql(t){return {sql:"",bindings:[]}}},Zm=new zs;var Ys=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",N(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",N(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 C?{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",N(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",N(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:[]}}},Xm=new Ys;var Gs=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 u of e.children){let{sql:c,bindings:p}=n.parse([u]);if(u.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let T=`${h} ${g}`.trim();T=T.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(T),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let u of e.namedConstraints){let{sql:c,bindings:p}=n.parse([u]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},eu=new Gs;var Zs=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:[]}}},tu=new Zs;var Xs=class{toSql(t){return {sql:"",bindings:[]}}},ru=new Xs;var ei=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},ou=new ei;var ti=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},nu=new ti;var ri=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},su=new ri;var oi=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}}},iu=new oi;var ni=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},au=new ni;var si=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new 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}}},lu=new si;var ii=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:[]}}},du=new ii;var ai=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},mu=new ai;var li=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(c=>r.formatStringColumn("postgres",c)).join(", "),l=[],d=[],m=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g=0;g<s.length;g++){let T=p[g];T instanceof C?h.push(T.rawValue):(l.push(T),h.push(`$${m++}${this.formatTypeCast(T)}`));}d.push(`(${h.join(", ")})`);}let u=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>r.formatStringColumn("postgres",p)).join(", ");u+=` returning ${c}`;}else u+=" returning *";return {sql:u,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}},uu=new li;var di=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:[]}}},cu=new di;var mi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},pu=new mi;var Op={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},ui=class{toSql(t){let e=t,r=Op[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},fu=new ui;var ci=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},yu=new ci;var pi=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:[]}}},hu=new pi;var fi=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:[]}}},gu=new fi;var yi=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},bu=new yi;var hi=class{toSql(t){return {sql:`SELECT
108
+ ORDER BY column_id`,bindings:[]}}},vu=new As;var Os=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("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},Bu=new Os;var Ds=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("oracledb",e.column),o=de.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Qu=new Ds;var xs=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},Ku=new xs;var Is=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},ku=new Is;var Ps=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("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,d)=>{let u=e.values[d];return u instanceof C?`${r.formatStringColumn("oracledb",l)} = ${u.rawValue}`:(s.push(u),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Lu=new Ps;var $s=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("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new y(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new y(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("oracledb",t):t}},ju=new $s;var Es=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new b(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Fu=new Es;var vs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new y(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},Uu=new vs;var Bs=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Wu=new Bs;var Qs=class{toSql(t){let e=t,r=new b(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},Vu=new Qs;var Ks=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:[]}}},Ju=new Ks;var ks=class{toSql(t){let e=t,r=new b(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Hu=new ks;var Ls=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Yu=new Ls;var js=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:[]}}},zu=new js;var Fs=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:c,bindings:p}=n.parse([m]);s.push(c.trim()),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},Gu=new Fs;var Us=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Zu=new Us;var Ws=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Xu=new Ws;var Vs=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},em=new Vs;var Js=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},tm=new Js;var Hs=class{toSql(t){return {sql:"",bindings:[]}}},rm=new Hs;var Ys=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},om=new Ys;var zs=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},nm=new zs;var Gs=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},sm=new Gs;var Zs=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},im=new Zs;var Xs=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("postgres",N(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:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}return {sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},am=new Xs;var ei=class{toSql(t){return {sql:"",bindings:[]}}},lm=new ei;var ti=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",N(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",N(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 C?{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",N(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",N(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:[]}}},dm=new ti;var ri=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:c,bindings:p}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)){let w=`${h} ${g}`.trim();w=w.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(w),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let m of e.namedConstraints){let{sql:c,bindings:p}=n.parse([m]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},um=new ri;var oi=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:[]}}},mm=new oi;var ni=class{toSql(t){return {sql:"",bindings:[]}}},cm=new ni;var si=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},pm=new si;var ii=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},fm=new ii;var ai=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},ym=new ai;var li=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}}},hm=new li;var di=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},gm=new di;var ui=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}}},bm=new ui;var mi=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:[]}}},Tm=new mi;var ci=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},wm=new ci;var pi=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(c=>r.formatStringColumn("postgres",c)).join(", "),l=[],d=[],u=e.currParamIndex;for(let c of e.records){let p=s.map(g=>c[g]),h=[];for(let g=0;g<s.length;g++){let w=p[g];w instanceof C?h.push(w.rawValue):(l.push(w),h.push(`$${u++}${this.formatTypeCast(w)}`));}d.push(`(${h.join(", ")})`);}let m=`${o} (${a}) values ${d.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>r.formatStringColumn("postgres",p)).join(", ");m+=` returning ${c}`;}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}},Nm=new pi;var fi=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:[]}}},Sm=new fi;var yi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},qm=new yi;var kp={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},hi=class{toSql(t){let e=t,r=kp[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Mm=new hi;var gi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},_m=new gi;var bi=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:[]}}},Cm=new bi;var Ti=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:[]}}},Rm=new Ti;var wi=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Am=new wi;var Ni=class{toSql(t){return {sql:`SELECT
109
109
  tc.constraint_name as name,
110
110
  kcu.column_name as column_name,
111
111
  ccu.table_name as referenced_table,
@@ -120,7 +120,7 @@ ORDER BY column_id`,bindings:[]}}},Rm=new Ms;var _s=class{toSql(t){let e=t;if(e.
120
120
  JOIN information_schema.referential_constraints rc
121
121
  ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema
122
122
  WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
123
- ORDER BY kcu.ordinal_position`,bindings:[]}}},Tu=new hi;var gi=class{toSql(t){return {sql:`SELECT
123
+ ORDER BY kcu.ordinal_position`,bindings:[]}}},Om=new Ni;var Si=class{toSql(t){return {sql:`SELECT
124
124
  i.relname as index_name,
125
125
  a.attname as column_name,
126
126
  ix.indisunique as is_unique
@@ -139,14 +139,14 @@ ORDER BY column_id`,bindings:[]}}},Rm=new Ms;var _s=class{toSql(t){let e=t;if(e.
139
139
  AND t.relname = '${t.table}'
140
140
  AND t.relnamespace = n.oid
141
141
  AND n.nspname = current_schema()
142
- AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},wu=new gi;var bi=class{toSql(t){return {sql:`SELECT
142
+ AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},Dm=new Si;var qi=class{toSql(t){return {sql:`SELECT
143
143
  tc.constraint_name as name,
144
144
  kcu.column_name as column_name
145
145
  FROM information_schema.table_constraints tc
146
146
  JOIN information_schema.key_column_usage kcu
147
147
  ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
148
148
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
149
- ORDER BY kcu.ordinal_position`,bindings:[]}}},Nu=new bi;var Ti=class{toSql(t){return {sql:`SELECT column_name,
149
+ ORDER BY kcu.ordinal_position`,bindings:[]}}},xm=new qi;var Mi=class{toSql(t){return {sql:`SELECT column_name,
150
150
  data_type,
151
151
  is_nullable,
152
152
  column_default,
@@ -156,12 +156,12 @@ ORDER BY column_id`,bindings:[]}}},Rm=new Ms;var _s=class{toSql(t){let e=t;if(e.
156
156
  FROM information_schema.columns
157
157
  WHERE table_schema = current_schema()
158
158
  AND table_name = '${t.table}'
159
- ORDER BY ordinal_position`,bindings:[]}}},Su=new Ti;var wi=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}"`:""}},qu=new wi;var Ni=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:[]}}},Mu=new Ni;var Si=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}}},_u=new Si;var qi=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 m=e.currParamIndex+d-n,u=e.values[d];return u instanceof C?(n++,`${r.formatStringColumn("postgres",l)} = ${u.rawValue}`):(s.push(u),`${r.formatStringColumn("postgres",l)} = $${m}${this.formatTypeCast(u)}`)}).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}},Cu=new qi;var Mi=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}},Ru=new Mi;var _i=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}}},Ou=new _i;var Ci=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}}},Au=new Ci;var Ri=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"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}}},Du=new Ri;var Oi=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}}},Iu=new Oi;var Ai=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:[]}}},xu=new Ai;var Di=class{toSql(t){return {sql:"",bindings:[]}}},Pu=new Di;var Ii=class{toSql(t){return {sql:"",bindings:[]}}},$u=new Ii;var xi=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 c of e.children){let{sql:p,bindings:h}=n.parse([c]);if(!(!p||!p.trim())){if(c.file==="add_column")s.push(p),l=true;else if(c.file==="add_constraint"&&l){let g=s.pop()??"",T=p.replace(/^\s*add\s+/i,"").trimStart();s.push(`${g} ${T}`);}else {if(c.file==="set_not_null"||c.file==="drop_not_null")continue;if(c.file==="set_default"||c.file==="drop_default")continue;s.push(p),l=false;}a.push(...h);}}let d=s.join(", "),m=e.ifExists?"if exists ":"";return d.trim()?{sql:`${m}${o} ${d}`,bindings:a}:{sql:"",bindings:[]}}},Eu=new xi;var Pi=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},vu=new Pi;var $i=class{toSql(t){return {sql:"",bindings:[]}}},Bu=new $i;var Ei=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Qu=new Ei;var vi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},ku=new vi;var Bi=class{toSql(t){return {sql:"",bindings:[]}}},Ku=new Bi;var Qi=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Lu=new Qi;var ki=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Fu=new ki;var Ki=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?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:[]}}},ju=new Ki;var Li=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Uu=new Li;var Fi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("sqlite",N(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:[]}:n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint"?{sql:`${o} ${n}`,bindings:[]}:{sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},Wu=new Fi;var ji=class{toSql(t){return {sql:"",bindings:[]}}},Vu=new ji;var Ui=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",N(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 C?{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",N(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",N(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:[]}}},Hu=new Ui;var Wi=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 u of e.children){let{sql:c,bindings:p}=n.parse([u]);if(u.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)||/primary key/i.test(g)){let T=`${h} ${g}`.trim();T=T.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(T),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let u of e.namedConstraints){let{sql:c,bindings:p}=n.parse([u]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},Ju=new Wi;var Vi=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:[]}}},zu=new Vi;var Hi=class{toSql(t){return {sql:"distinct",bindings:[]}}},Yu=new Hi;var Ji=class{toSql(t){return S.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Gu=new Ji;var zi=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Zu=new zi;var Yi=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},Xu=new Yi;var Gi=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}}},ec=new Gi;var Zi=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},tc=new Zi;var Xi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new 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}}},rc=new Xi;var ea=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:[]}}},oc=new ea;var ta=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},nc=new ta;var ra=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(u=>r.formatStringColumn("sqlite",u)).join(", "),l=[],d=[];for(let u of e.records){let c=s.map(h=>u[h]),p=[];for(let h of c)h instanceof C?p.push(h.rawValue):(l.push(h),p.push("?"));d.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},sc=new ra;var oa=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:[]}}},ic=new oa;var na=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},ac=new na;var sa=class{toSql(t){return {sql:"",bindings:[]}}},lc=new sa;var ia=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},dc=new ia;var aa=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:[]}}},mc=new aa;var la=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:[]}}},uc=new la;var da=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},cc=new da;var ma=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},pc=new ma;var ua=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},fc=new ua;var ca=class{toSql(t){return {sql:`SELECT
159
+ ORDER BY ordinal_position`,bindings:[]}}},Im=new Mi;var _i=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}"`:""}},Pm=new _i;var Ci=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("postgres",e.column),o=de.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},$m=new Ci;var Ri=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:[]}}},Em=new Ri;var Ai=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}}},vm=new Ai;var Oi=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 C?(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}},Bm=new Oi;var Di=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}},Qm=new Di;var xi=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}}},Km=new xi;var Ii=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}}},km=new Ii;var Pi=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}}},Lm=new Pi;var $i=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}}},jm=new $i;var Ei=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:[]}}},Fm=new Ei;var vi=class{toSql(t){return {sql:"",bindings:[]}}},Um=new vi;var Bi=class{toSql(t){return {sql:"",bindings:[]}}},Wm=new Bi;var Qi=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 c of e.children){let{sql:p,bindings:h}=n.parse([c]);if(!(!p||!p.trim())){if(c.file==="add_column")s.push(p),l=true;else if(c.file==="add_constraint"&&l){let g=s.pop()??"",w=p.replace(/^\s*add\s+/i,"").trimStart();s.push(`${g} ${w}`);}else {if(c.file==="set_not_null"||c.file==="drop_not_null")continue;if(c.file==="set_default"||c.file==="drop_default")continue;s.push(p),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:[]}}},Vm=new Qi;var Ki=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Jm=new Ki;var ki=class{toSql(t){return {sql:"",bindings:[]}}},Hm=new ki;var Li=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},Ym=new Li;var ji=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},zm=new ji;var Fi=class{toSql(t){return {sql:"",bindings:[]}}},Gm=new Fi;var Ui=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Zm=new Ui;var Wi=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Xm=new Wi;var Vi=class{toSql(t){let e=t,r;return e.defaultValue instanceof C?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},ec=new Vi;var Ji=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},tc=new Ji;var Hi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("sqlite",N(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:[]}:n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint"?{sql:`${o} ${n}`,bindings:[]}:{sql:`${o} ${n} ${e.length?`(${e.length})`:""}`,bindings:[]}}},rc=new Hi;var Yi=class{toSql(t){return {sql:"",bindings:[]}}},oc=new Yi;var zi=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",N(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 C?{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",N(d))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(d=>r.formatStringColumn("sqlite",N(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:[]}}},nc=new zi;var Gi=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:c,bindings:p}=n.parse([m]);if(m.folder==="constraint"){let h=s.pop()??"",g=c;if(/not null/i.test(g)||/null/i.test(g)||/default/i.test(g)||/primary key/i.test(g)){let w=`${h} ${g}`.trim();w=w.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(w),a.push(...p);continue}s.push(h),s.push(g),a.push(...p);continue}s.push(c),a.push(...p);}for(let m of e.namedConstraints){let{sql:c,bindings:p}=n.parse([m]);s.push(c),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifNotExists?"if not exists ":""}${o} (${l})`,bindings:a}}},sc=new Gi;var Zi=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:[]}}},ic=new Zi;var Xi=class{toSql(t){return {sql:"distinct",bindings:[]}}},ac=new Xi;var ea=class{toSql(t){return S.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},lc=new ea;var ta=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},dc=new ta;var ra=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},uc=new ra;var oa=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}}},mc=new oa;var na=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},cc=new na;var sa=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}}},pc=new sa;var ia=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:[]}}},fc=new ia;var aa=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},yc=new aa;var la=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 c=s.map(h=>m[h]),p=[];for(let h of c)h instanceof C?p.push(h.rawValue):(l.push(h),p.push("?"));d.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${d.join(", ")}`,bindings:l}}},hc=new la;var da=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:[]}}},gc=new da;var ua=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},bc=new ua;var ma=class{toSql(t){return {sql:"",bindings:[]}}},Tc=new ma;var ca=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},wc=new ca;var pa=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:[]}}},Nc=new pa;var fa=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:[]}}},Sc=new fa;var ya=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},qc=new ya;var ha=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},Mc=new ha;var ga=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},_c=new ga;var ba=class{toSql(t){return {sql:`SELECT
160
160
  'PRIMARY' as name,
161
161
  name as column_name
162
162
  FROM pragma_table_info('${t.table}')
163
163
  WHERE pk > 0
164
- ORDER BY pk`,bindings:[]}}},yc=new ca;var pa=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},hc=new pa;var fa=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}"`:""}},gc=new fa;var ya=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:[]}}},bc=new ya;var ha=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}}},Tc=new ha;var ga=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 C?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},wc=new ga;var ba=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}},Nc=new ba;var Ta=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}}},Sc=new Ta;var wa=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}}},qc=new wa;var Na=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}}},Mc=new Na;var Sa=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}}},_c=new Sa;var Cc={mssql:{alter_table:{add_column:Za,add_constraint:Xa,add_primary_key:el,alter_column_type:tl,alter_table:rl,drop_column:ol,drop_constraint:nl,drop_default:sl,drop_not_null:il,drop_primary_key:al,rename_column:ll,rename_table:dl,set_default:ml,set_not_null:ul},column:{column_type:cl},constraint:{after:pl,constraint:fl},create_table:{create_table:yl},delete:{delete:hl},distinct:{distinct:gl,distinct_on:bl},drop_table:{drop_table:Tl},extension:{create_extension:wl},from:{from:Nl},group_by:{group_by:Sl},having:{having:ql},index_op:{create_index:Ml,drop_index:_l},insert:{insert:Cl},join:{join:Rl},limit:{limit:Ol},lock:{lock:Al},offset:{offset:Dl},on_duplicate:{on_duplicate:Il},order_by:{order_by:xl},raw:{raw:Pl},schema:{foreign_key_info:$l,index_info:El,primary_key_info:vl,table_info:Bl},select:{select:Ql},truncate:{truncate:kl},union:{union:Kl},update:{update:Ll},where:{where:Fl,where_group:jl,where_json:Ul,where_subquery:Wl},with:{with:Vl}},mysql:{alter_table:{add_column:Hl,add_constraint:Jl,add_primary_key:zl,alter_column_type:Yl,alter_table:Gl,drop_column:Zl,drop_constraint:Xl,drop_default:ed,drop_not_null:td,drop_primary_key:rd,rename_column:od,rename_table:nd,set_default:sd,set_not_null:id},column:{column_type:ad},constraint:{after:ld,constraint:dd},create_table:{create_table:md},delete:{delete:ud},distinct:{distinct:cd,distinct_on:pd},drop_table:{drop_table:fd},extension:{create_extension:yd},from:{from:hd},group_by:{group_by:gd},having:{having:bd},index_op:{create_index:Td,drop_index:wd},insert:{insert:Nd},join:{join:Sd},limit:{limit:qd},lock:{lock:Md},offset:{offset:_d},on_duplicate:{on_duplicate:Cd},order_by:{order_by:Rd},raw:{raw:Od},schema:{foreign_key_info:Ad,index_info:Dd,primary_key_info:Id,table_info:xd},select:{select:Pd},truncate:{truncate:$d},union:{union:Ed},update:{update:vd},where:{where:Bd,where_group:Qd,where_json:kd,where_subquery:Kd},with:{with:Ld}},oracledb:{alter_table:{add_column:Fd,add_constraint:jd,add_primary_key:Ud,alter_column_type:Wd,alter_table:Vd,drop_column:Hd,drop_constraint:Jd,drop_default:zd,drop_not_null:Yd,drop_primary_key:Gd,rename_column:Zd,rename_table:Xd,set_default:em,set_not_null:tm},column:{column_type:rm},constraint:{after:om,constraint:nm},create_table:{create_table:sm},delete:{delete:im},distinct:{distinct:am,distinct_on:lm},drop_table:{drop_table:dm},extension:{create_extension:mm},from:{from:um},group_by:{group_by:cm},having:{having:pm},index_op:{create_index:fm,drop_index:ym},insert:{insert:hm},join:{join:gm},limit:{limit:bm},lock:{lock:Tm},offset:{offset:wm},on_duplicate:{on_duplicate:Nm},order_by:{order_by:Sm},raw:{raw:qm},schema:{foreign_key_info:Mm,index_info:_m,primary_key_info:Cm,table_info:Rm},select:{select:Om},truncate:{truncate:Am},union:{union:Dm},update:{update:Im},where:{where:xm,where_group:Pm,where_json:$m,where_subquery:Em},with:{with:vm}},postgres:{alter_table:{add_column:Bm,add_constraint:Qm,add_primary_key:km,alter_column_type:Km,alter_table:Lm,drop_column:Fm,drop_constraint:jm,drop_default:Um,drop_not_null:Wm,drop_primary_key:Vm,rename_column:Hm,rename_table:Jm,set_default:zm,set_not_null:Ym},column:{column_type:Gm},constraint:{after:Zm,constraint:Xm},create_table:{create_table:eu},delete:{delete:tu},distinct:{distinct:ru,distinct_on:ou},drop_table:{drop_table:nu},extension:{create_extension:su},from:{from:iu},group_by:{group_by:au},having:{having:lu},index_op:{create_index:du,drop_index:mu},insert:{insert:uu},join:{join:cu},limit:{limit:pu},lock:{lock:fu},offset:{offset:yu},on_duplicate:{on_duplicate:hu},order_by:{order_by:gu},raw:{raw:bu},schema:{foreign_key_info:Tu,index_info:wu,primary_key_info:Nu,table_info:Su},select:{select:qu},truncate:{truncate:Mu},union:{union:_u},update:{update:Cu},where:{where:Ru,where_group:Ou,where_json:Au,where_subquery:Du},with:{with:Iu}},sqlite:{alter_table:{add_column:xu,add_constraint:Pu,alter_column_type:$u,alter_table:Eu,drop_column:vu,drop_constraint:Bu,drop_default:Qu,drop_not_null:ku,drop_primary_key:Ku,rename_column:Lu,rename_table:Fu,set_default:ju,set_not_null:Uu},column:{column_type:Wu},constraint:{after:Vu,constraint:Hu},create_table:{create_table:Ju},delete:{delete:zu},distinct:{distinct:Yu,distinct_on:Gu},drop_table:{drop_table:Zu},extension:{create_extension:Xu},from:{from:ec},group_by:{group_by:tc},having:{having:rc},index_op:{create_index:oc,drop_index:nc},insert:{insert:sc},join:{join:ic},limit:{limit:ac},lock:{lock:lc},offset:{offset:dc},on_duplicate:{on_duplicate:mc},order_by:{order_by:uc},raw:{raw:cc},schema:{foreign_key_info:pc,index_info:fc,primary_key_info:yc,table_info:hc},select:{select:gc},truncate:{truncate:bc},union:{union:Tc},update:{update:wc},where:{where:Nc,where_group:Sc,where_json:qc,where_subquery:Mc},with:{with:_c}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(R=>!!R&&R.folder==="distinctOn"),n=!o&&t.find(R=>!!R&&R.folder==="distinct"),s=this.dbType==="mssql"?t.find(R=>!!R&&R.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(R=>R!==null&&R.folder!=="distinct"&&R.folder!=="distinctOn"),d=l.some(R=>R.folder==="offset"),m=l.some(R=>R.folder==="order_by"),u=l.find(R=>R.folder==="limit"),c=l.find(R=>R.folder==="offset"),p=this.dbType==="mssql"&&u&&!d&&!m,h=this.dbType==="mssql"&&!p&&(u||c),g=this.dbType==="oracledb"&&(u||c),T=[],_=[],$=null;p&&u&&_.push(u.limit);for(let R=0;R<l.length;R++){let x=l[R];if(p&&x.folder==="limit"||h&&(x.folder==="limit"||x.folder==="offset")||g&&(x.folder==="limit"||x.folder==="offset"))continue;x.currParamIndex=e+_.length;let A=Cc[this.mapCommonDbType(this.dbType)][x.folder][x.file];if(!A)throw new Error(`Interpreter not found for ${this.dbType} ${x.keyword}`);A.model=this.model;let q=A.toSql(x);if(!q.sql||!q.sql.trim().length)continue;let Q=l[R+1],D=!Q||Q.keyword!==x.keyword?"":Q.chainsWith;if(x.folder==="lock"||x.folder==="on_duplicate"||x.folder==="schema"){T.push(`${q.sql}${D}`),_.push(...q.bindings),$=x.keyword;continue}if($!==x.keyword||x.canKeywordBeSeenMultipleTimes){if(r)T.push(`${q.sql}${D}`);else {let Y=x.keyword;if(x.folder==="with"&&this.dbType!=="mssql"){let le=R,We=false;for(;le<l.length&&l[le].keyword===x.keyword;){let Ae=l[le];if(Ae.folder==="with"&&Ae.clause==="recursive"){We=true;break}le++;}We&&(Y=`${Y} recursive`);}if(Y==="select"){let le=p?`top (@${e}) `:"";if(o){let We=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${le}distinct on (${We}) ${q.sql}${D}`);}else n?T.push(`select ${le}distinct ${q.sql}${D}`):T.push(`select ${le}${q.sql}${D}`);}else Y==="from"&&a?T.push(`${Y} ${q.sql}${a}${D}`):T.push(`${Y} ${q.sql}${D}`);}$=x.keyword;}else T.push(`${q.sql}${D}`);_.push(...q.bindings);}if(h){m||T.push("order by (select null)");let R=c?.offset??0;_.push(R);let A=`offset @${e+_.length-1} rows`;if(u){_.push(u.limit);let q=e+_.length-1;A+=` fetch next @${q} rows only`;}T.push(A);}if(g){m||T.push("order by null");let R=c?.offset??0;_.push(R);let A=`offset :${e+_.length-1} rows`;if(u){_.push(u.limit);let q=e+_.length-1;A+=` fetch next :${q} rows only`;}T.push(A);}return {sql:T.join(" "),bindings:_}}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 It=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var xt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Pt=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var $t=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Et=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ge=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var Ge=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var vt=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var _e=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var Bt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var it=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Qt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var Ze=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var kt=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Kt=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Lt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var J=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var Ft=class extends w{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 jt=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var Ut=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var Wt=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var Vt=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var Te=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Ht=Symbol("columns"),Jt=Symbol("primaryKey"),me=Symbol("relations"),zt=Symbol("indexes"),Yt=Symbol("uniques"),xe=i=>`${Ap__default.default.singular(i)}_id`,Gt=(i,t)=>`idx_${i}_${t}`,de=(i,t)=>`uq_${i}_${t}`,z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,Pe=(i,t)=>`pk_${i}_${t}`;var P=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.isRawValue=o.isRawValue??false;}};var at=class extends w{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var Le=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var Xe=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var $e=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Zt=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Xt=class extends $e{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=Pe(this.tableName,N(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new J("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new J("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??z(this.tableName??"",N(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new J("foreign_key",{columns:[N(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new J("foreign_key",{columns:[N(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}notNullable(){return this.nodes.push(new J("not_null",{columns:[N(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new J("null",{columns:[N(this.columnNode.column)]})),this}default(t){let e;return t instanceof C?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new J("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new J("unique",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName??de(this.tableName??"",N(this.columnNode.column))})),this):(this.namedConstraints.push(new J("unique",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName||de(this.tableName??"",N(this.columnNode.column))})),this)}after(t){return this.nodes.push(new Zt(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new J("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Fe=class extends $e{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 Xt(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new C(e)}char(e,r=1){let o=new P(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new P(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new P(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 P(e,"uuid");return this.build(r)}ulid(e){let r=new P(e,"ulid");return this.build(r)}integer(e,r=255){let o=new P(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new P(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new P(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new P(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new P(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new P(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new P(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new P(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new P(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new P(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 P(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new P(e,"time",{precision:r});return this.build(o)}year(e){let r=new P(e,"year");return this.build(r)}datetime(e,r){let o=new P(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new P(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new P(e,"boolean");return this.build(r)}binary(e){let r=new P(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new P(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new P(e,"blob");return this.build(r)}tinyblob(e){let r=new P(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new P(e,"mediumblob");return this.build(r)}longblob(e){let r=new P(e,"longblob");return this.build(r)}json(e){let r=new P(e,"json");return this.build(r)}jsonb(e){let r=new P(e,"jsonb");return this.build(r)}enum(e,r){let o=new P(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new P(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new P(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new P(e,"geometry");return this.build(r)}point(e){let r=new P(e,"point");return this.build(r)}linestring(e){let r=new P(e,"linestring");return this.build(r)}polygon(e){let r=new P(e,"polygon");return this.build(r)}multiPoint(e){let r=new P(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var er=class extends $e{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new C(t)}addColumn(t){let e=[],r=new Fe(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(u=>u.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(u=>{let c=u;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new Et(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(u=>{let c=u;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(u=>{this.nodes.push(new ge(u));});}alterColumn(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Fe(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(c=>c.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=N(s.column),l=o.getNodes().find(c=>c.constraintType==="null"),m=o.getNodes().find(c=>c.constraintType==="not_null")||l,u=o.getNodes().find(c=>c.constraintType==="default");this.nodes.push(new vt(N(a),s,{})),m&&(m.constraintType==="not_null"?this.nodes.push(new Lt(N(a))):m.constraintType==="null"&&this.nodes.push(new Qt(N(a)))),u&&(u.defaultValue===void 0||u.defaultValue===null?this.nodes.push(new it(N(a))):this.nodes.push(new Kt(N(a),u.defaultValue))),o.getNodes().forEach(c=>{let p=c;switch(p.constraintType){case "primary_key":this.addPrimaryKey(N(a));break;case "unique":this.unique(N(a),{constraintName:p.constraintName});break;case "foreign_key":this.foreignKey(N(a),p.references?.table??"",N(p.references?.columns?.[0]??""),{constraintName:p.constraintName,onDelete:p.onDelete,onUpdate:p.onUpdate});break}});}dropColumn(t){this.nodes.push(new Bt(t));}renameColumn(t,e){this.nodes.push(new kt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new it(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Ge([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new J(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new J("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??z(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new J("unique",{columns:[t],constraintName:e?.constraintName??de(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=z(this.table,t,e);this.nodes.push(new be(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new f("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??de(this.table,t);this.nodes.push(new be(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new f("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new Ze(t));}};var ue=class{constructor(t){if(this.sqlType=t||M.DB_TYPE,!this.sqlType)throw new f("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new C(t)}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!Rc__default.default.existsSync(t))throw new f("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=_t__default.default.basename(t),r=_t__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new f("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=Rc__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 Fe(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new Ft(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 er(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 _e(t,s),d=n.parse([l]).sql;if(!d||!d.trim())return;let m=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(m),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 jt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new _e(t,[new Ye(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new Te(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r){Array.isArray(e)||(e=[e]);let o=r.constraintName||Gt(t,e.join("_")),n=new Wt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Vt(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new Ge(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??de(t,o.join("_")),s=new J("unique",{columns:o,constraintName:n}),a=new _e(t,[new ge(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=z(t,e,r),n=new be(o),s=new _e(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?de(t,e.join("_")):de(t,e),n=r?.constraintName??o,s=new be(n),a=new _e(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new Ze,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new J(...e),o=new _e(t,[new ge(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new be(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}createExtension(t,e=true){let r=new Ut(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new b(t,this.sqlType)}};var tr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let m of d)m.type==="belongsTo"&&m.model().table===n.table&&a.push(`fk.${l.table}.${m.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(m=>m.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let m=l.getRelations();for(let u of m)u.columnName===d.columnName&&a.push(`fk.${n.table}.${u.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(m=>m.table===a&&m.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 rr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new tr(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 ue(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||Pe(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let m=a||Pe(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:m});});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(m=>m.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=N(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=N(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=N(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||Pe(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 ue(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=N(t.relation.manyToManyOptions.throughModel),r=N(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=N(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),p=c.primaryKey,g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=k(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),h=p.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",T=p.find(_=>_.columnName===g);if(T)n=T.databaseName;else {let _=c?.databaseCaseConvention||"preserve";n=k(n||g,_);}}}else {let p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p);if(g)n=g.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=k(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=k(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=k(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=N(c),h=a.find(g=>g.columnName===p);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=k(p,g);}}let m=t.relation.onDelete?.toLowerCase(),u=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,c=>{let p=o||z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:m,onUpdate:u});})}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 xp(i){return i.replace(/\s+/g," ").trim()}function Pp(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ee(i,t){let e=xp(t.toLowerCase()),r=Pp(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}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var or=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(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 m of n.indexes)o.indexes.map(u=>u.name).includes(m.name)||e.data.indexesToAdd.push({table:r.table,index:m.name});let d=r.getUniques?.()||[];for(let m of d)e.data.uniquesToAdd.push({table:r.table,name:m.name||"mandatory",columns:m.columns});for(let m of n.relations){if(m.type!=="belongsTo")continue;let u=N(m.constraintName);o.foreignKeys.find(p=>p.name===u)||e.data.relationsToAdd.push({table:r.table,relation:m,onDelete:m.onDelete,onUpdate:m.onUpdate});}return}for(let d of n.columns)o.columns.some(u=>u.name===d.databaseName||u.name===d.columnName)||e.data.columnsToAdd.push({table:r.table,column:d});for(let d of o.columns)n.columns.some(u=>u.databaseName===d.name||u.columnName===d.name)||e.data.columnsToDrop.push({table:r.table,column:d.name});for(let d of n.indexes)o.indexes.map(m=>m.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(u=>u.name===d.name&&u.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(u=>u.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(u=>u.name).includes(d.name)||e.data.uniquesToDrop.push({table:r.table,name:d.name});}for(let d of n.columns){let m=o.columns.find(p=>p.name===d.databaseName||p.name===d.columnName);if(!m)continue;let u=!e.areColumnsEqual(m,d,o.indexes),c=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:d});(u||c)&&e.data.columnsToModify.push({table:r.table,dbColumns:m,modelColumn:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;if(d.type==="manyToMany"&&d.manyToManyOptions){let c=N(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:c,relation:{type:"belongsTo",model:()=>r,columnName:N(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?N(d.constraintName):z(c,N(d.manyToManyOptions.leftForeignKey||xe(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let m=N(d.constraintName);if(m&&o.foreignKeys.some(c=>c.name===m))continue;o.foreignKeys.find(c=>e.relationMatchesDbRelation(r,d,c))||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 m=N(d.foreignKey)||d.columnName,c=r.getColumns().find(p=>p.columnName===m)?.databaseName||m;return N(d.constraintName)||z(r.table,c,d.model().table)}));for(let d of o.foreignKeys){if(d.name&&a.has(d.name))continue;n.relations.find(u=>u.type!=="belongsTo"&&u.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,u,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 m=o.foreignKeys.find(u=>e.relationMatchesDbRelation(r,d,u));m&&!e.areRelationsEqual(m,d)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,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(m=>m.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 rr(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=Ee(n,t.dataType),a=typeof e.type=="string"?Ee(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,m=t.isNullable;o=o&&d===m;}return o}areRelationsEqual(t,e){let r=N(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),m=d.primaryKey||"id",u=d.getColumns().find(h=>h.columnName===m),c=d.table,p=u?.databaseName||m;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=N(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?N(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=N(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),m=(n.type||"belongsTo")==="belongsTo"?N(n.foreignKey):n.columnName,u=l.find(g=>g.columnName===m);u&&(m=u.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===m&&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=Ee(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ee(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),m=this.normalizeDefaultValue(e,o||r,l);return d!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);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=N(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(D=>D.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",m=s.getColumns().find(D=>D.columnName===l),u=a.getColumns().find(D=>D.columnName===d);if(!m||!u)continue;let c=N(o.manyToManyOptions.leftForeignKey)||l,p=N(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(m,c),this.clonePkAsColumn(u,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(m,c),T=this.clonePkAsColumn(u,p),_=h.columns.find(D=>D.name===c),$=h.columns.find(D=>D.name===p),V=_?this.areColumnsEqual(_,g,h.indexes):false,R=$?this.areColumnsEqual($,T,h.indexes):false;for(let D of h.foreignKeys){let Y=D.referencedTable===s.table,le=D.referencedTable===a.table;if(!Y&&!le)continue;let We=Y?c:p,Ae=D.columns[0];Ae&&Ae!==We&&(this.data.relationsToDrop.push({table:n,relation:D}),Ae!==c&&Ae!==p&&this.data.columnsToDrop.push({table:n,column:Ae}));}let x={};V||(x[g.databaseName]=g),R||(x[T.databaseName]=x[T.databaseName]||T);for(let D of Object.keys(x))this.data.columnsToAdd.push({table:n,column:x[D]});let A=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),q=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),Q=h.foreignKeys.find(D=>D.referencedTable===s.table&&D.columns.length===1&&D.columns[0]===c),qe=h.foreignKeys.find(D=>D.referencedTable===a.table&&D.columns.length===1&&D.columns[0]===p);if(!Q){let D=h.foreignKeys.find(Y=>Y.referencedTable===s.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(A);}if(!qe){let D=h.foreignKeys.find(Y=>Y.referencedTable===a.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(q);}}}}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,m=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,u=N(a.constraintName)||z(o.table,m,a.model().table);s.add(u);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(g=>g.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let d=o.table,m=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let T=g.primaryKey||"id";m=g.getColumns().find($=>$.columnName===T)?.databaseName||T;}let u=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let T=u.has(g.columns[0]),_=g.referencedTable===d,$=g.referencedColumns[0]===m;return T&&_&&$}),p=N(o.relation.constraintName)||z(o.table,l,d),h=e.get(o.table)||new Set;if(c||p&&h.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=N(o.relation.manyToManyOptions.throughModel),T=N(o.relation.manyToManyOptions.leftForeignKey),_=N(o.relation.manyToManyOptions.rightForeignKey),$=o.table===g&&o.relation.columnName===T&&o.relation.model().table===s?.table,V=o.table===g&&o.relation.columnName===_&&o.relation.model().table!==s?.table,R=await this.sql.getTableSchema(g),x=R.foreignKeys.some(q=>q.columns.length===1&&q.columns[0]===T&&q.referencedTable===(s?.table||"")),A=R.foreignKeys.some(q=>q.columns.length===1&&q.columns[0]===_&&q.referencedTable===o.relation.model().table);if($&&x||V&&A)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 u=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),p=c.primaryKey||"id",g=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===u&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){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?N(n):z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var we=class extends w{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var F=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var U=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ce=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var oe=class extends w{constructor(e,r=[],o=[],n=false){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o;}};var B=class extends w{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var lt=class extends w{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var ne=class extends B{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 Re=class extends w{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var nr=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);});}},Dc=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,m)=>{n.run(i,t,function(u){u&&m(u),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,m)=>{n.all(i,t,(u,c)=>{u&&m(u),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,m)=>{n.run(i,t,function(u){u?m(new Error(u.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((u,c)=>{n.run(i,t,function(p){if(p)return c(p);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){u([h]);return}let g=h?.[a]||this.lastID;if(!g)return c(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[g],(_,$)=>{if(_)return c(_);u([$]);});});});if(!Array.isArray(r.models))throw new f("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((u,c)=>{n.run(i,t,function(p){if(p)return c(p);u(d);});});let m=[];return new Promise(async(u,c)=>{try{let p=d.map(async h=>{let g=new y(s),{columns:T,values:_}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),$=Object.fromEntries(T.map((A,q)=>[A,_[q]])),V=new b(s,e.getDbType()),{sql:R,bindings:x}=V.parse([new U(new F(s.table),[$])]);return new Promise((A,q)=>{n.run(R,x,function(Q){if(Q)return q(Q);let qe=h[a]||this.lastID;if(!qe)return q(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let D=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(D,[qe],(Y,le)=>{if(Y)return q(Y);A(le);});});})});m=await Promise.all(p),u(m);}catch(p){c(p);}})}return new Promise((d,m)=>{n.run(i,t,function(u){u?m(new Error(u.message)):d(this.changes);});})};var Ep=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,vp=/^\d{4}-\d{2}-\d{2}$/,qa=i=>typeof i!="string"?i:Ep.test(i)?new Date(i.replace(" ","T")+"Z"):vp.test(i)?new Date(i+"T00:00:00Z"):i,Bp=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),Ic=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Bp(r):t[e]=r;}return t};var W=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||X(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await dt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=await dt(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?d.rows:o==="raw"?d:d.rowCount;case "sqlite":let m=await dt(()=>Dc(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(m)?m:[m]:m;case "mssql":let u=e.getPool(),c=e.sqlConnection?e.sqlConnection.request():u.request();t.forEach((V,R)=>{c.input(`p${R}`,V);});let p=0,h=i.replace(/\?|@(\d+)/g,()=>`@p${p++}`),g=await dt(()=>c.query(h),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?g.rowsAffected[0]:o==="raw"?g:g.recordset;case "oracledb":let T=4002,_=null,$=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let V=t.map(qa),R=await dt(()=>_.execute(i,V,{outFormat:T,autoCommit:!$}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?R.rowsAffected:o==="raw"?R:await Promise.all(R.rows?.map(async A=>{let q=await Ic(A),Q={};for(let qe in q)Q[qe.toLowerCase()]=q[qe];return Q})??[])}finally{_&&!$&&await _.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},ir=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),m=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),u=0,c=false,p=false,h=()=>{try{a.release();}catch{}};return m.on("data",g=>{if(o.onData){u++,Promise.resolve(o.onData(l,g)).then(()=>{u--,c&&u===0&&!p&&(h(),l.end());}).catch(T=>{p=true,h(),l.destroy(T);});return}l.write(g);}),m.on("end",()=>{c=true,u===0&&!p&&(h(),l.end());}),m.on("error",g=>{p=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new v("pg-query-stream")}),d=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),m=new l.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),u=a.query(m),c=0,p=false,h=false,g=T=>{try{a.release(T);}catch{}};return u.on("data",T=>{if(o.onData){c++,Promise.resolve(o.onData(d,T)).then(()=>{c--,p&&c===0&&!h&&(g(),d.end());}).catch(_=>{h=true,g(_),d.destroy(_);});return}d.write(T);}),u.on("end",()=>{p=true,c===0&&!h&&(g(),d.end());}),u.on("error",T=>{h=true,g(T),d.destroy(T);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new nr(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((h,g)=>{l.input(`p${g}`,h);});let d=0,m=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),u=0,c=false,p=false;return l.on("row",h=>{if(!p){if(o.onData){u++,Promise.resolve(o.onData(a,h)).then(()=>{u--,c&&u===0&&!p&&a.end();}).catch(g=>{p=true,a.destroy(g);});return}a.write(h);}}),l.on("error",h=>{p=true,a.destroy(h);}),l.on("done",()=>{c=true,u===0&&!p&&a.end();}),l.query(m),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,m=t.map(qa),u=a.queryStream(i,m,{outFormat:d}),c=0,p=false,h=false,g=async()=>{try{await a.close();}catch{}};return u.on("data",T=>{if(h)return;let _={};for(let $ in T)_[$.toLowerCase()]=T[$];if(o.onData){c++,Promise.resolve(o.onData(l,_)).then(()=>{c--,p&&c===0&&!h&&(g(),l.end());}).catch($=>{h=true,g(),l.destroy($);});return}l.write(_);}),u.on("end",()=>{p=true,c===0&&!h&&(g(),l.end());}),u.on("error",T=>{h=true,g(),l.destroy(T);}),l}default:throw new f("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function dt(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++,za(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var L=(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 ee=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var mt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=ar(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new f("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function lr(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 xc(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var et=i=>typeof i=="number"?i:parseFloat(i);var je=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var dr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var mr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var se=class extends w{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 ut=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var ur=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var cr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var ct=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var pr=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 ut(e));}),this}groupByRaw(t){return this.groupByNodes.push(new ut(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new ct(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new ct(t,"asc",true)),this}limit(t){return typeof t!="number"&&S.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new ur(t),this}offset(t){return typeof t!="number"&&S.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new cr(t),this}};var fr=class extends pr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new f("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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var yr=class extends fr{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=>k(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new ee(o));}),this}selectRaw(e){return this.selectNodes.push(new ee(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 ee(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 dr,this}distinctOn(...e){return this.distinctOnNode=new mr(e),this}};var hr=class extends yr{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 E&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||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 E&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 B(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new B(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 B(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new B(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 B(e,"and",false,"in",r)),this):(this.whereNodes.push(new B("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new B(e,"or",false,"in",r)),this):(this.whereNodes.push(new B("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 B(e,"and",true,"in",r)),this):(this.whereNodes.push(new B("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new B(e,"or",true,"in",r)),this):(this.whereNodes.push(new B("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new B(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new B(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new B(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new B(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 B(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 B(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new B(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new B(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 je(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 je(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new je(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new je(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof E)return e;let r=new E(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Re(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Re(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new E(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new lt(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new E(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new lt(r.whereNodes,"or");return this.whereNodes.push(o),this}};var gr=class extends hr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"or",false,"raw",e)),this}};var E=class i extends gr{constructor(e,r=pe.instance){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.replicationMode=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);}setReplicationMode(e){return this.replicationMode=e,this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>W(e,r,o,this.dbType,"rows",{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 f("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await ir(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let s=await this.many(),a=await n.getCount(),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:xc(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 ee(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new ee(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new at("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new at("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Le(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Le(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(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?et(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?et(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?et(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?et(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?et(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&S.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:lr(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new f("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new F(n,r),this}return this.fromNode=new F(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new Xe("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 Xe("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new f("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new Xe("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,c)=>[u,n[c]]));this.insertNode=new U(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),m=await W(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(m)&&m.length?m[0]:m}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async l=>{let{columns:d,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(l),Object.values(l),"insert");return Object.fromEntries(d.map((u,c)=>[u,m[c]]))}));this.insertNode=new U(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]),a=await this.getSqlDataSource("write");return W(n,s,a,this.dbType,"rows",{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((h,g)=>[h,l[g]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:m,bindings:u}=this.astParser.parse([new U(new F(this.model.table),[d],void 0,true),new ce(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),p=await W(m,u,c,this.dbType,"rows",{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:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(u),Object.values(u),"insert"),h=Object.fromEntries(c.map((g,T)=>[g,p[T]]));s.push(h);})),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 ce(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),m=await W(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),d=Q=>this.interpreterUtils.formatStringColumn("mssql",Q),m=[],u=e.map(Q=>`select ${a.map(D=>(m.push(Q[D]),`@${m.length}`)).join(", ")}`),c=a.map(d).join(", "),p=u.join(" union all "),h=r.map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(" and "),g=o.filter(Q=>!r.includes(Q)).map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(", "),T=a.map(d).join(", "),_=a.map(Q=>`source.${d(Q)}`).join(", "),$=n.returning&&n.returning.length?n.returning.map(Q=>`inserted.${d(Q)}`).join(", "):a.map(Q=>`inserted.${d(Q)}`).join(", "),R=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",x=`merge into ${l} as target using (${p}) as source (${c}) on ${h} ${R} when not matched then insert (${T}) values (${_}) output ${$};`,A=await this.getSqlDataSource("write"),q=await W(x,m,A,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(q)?q:[q]}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 oe(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return W(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new Te(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await W(e,r,o,this.dbType,"rows");}async delete(){this.deleteNode=new we(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return W(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=ye()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new oe(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return W(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ga(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new ee("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=At(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 ee("*")]),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 L(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await L(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 L(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await L(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await L(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await L(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await L(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var tt=class i extends E{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 mt(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 f(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 he(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(),n=await this.getSqlDataSource("read");return await ir(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),m=await he([d],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);m&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([m]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([m]),a.write(m));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new f(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}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:lr(e,r,d),data:l}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new ee(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 ee(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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereNotExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereNotExists(m),this}clone(){let e=super.clone();return e.relationQueryBuilders=j(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let h=n.get(String(p));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let h=s.get(String(p));c[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=a.get(String(p))||[];c[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,m=l.leftForeignKey,u=this.modelColumnsMap.get(m)||this.modelColumnsDatabaseNames.get(m)||k(m,this.model.modelCaseConvention);o.forEach(c=>{let p=c.$annotations||{},h=p[u];if(h==null)return;let g=String(h);d.has(g)||d.set(g,[]),this.modelAnnotatedColumns.includes(u)||(delete p[u],Object.keys(p).length||delete c.$annotations),d.get(g).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=d.get(String(p))||[];c[e.columnName]=h;});break;default:throw new f(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=Me__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,m=e.orderByNodes.map(q=>q.isRawValue?q.column:`${this.interpreterUtils.formatStringColumn(this.dbType,q.column)} ${q.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let u=e.with(d,q=>q.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${m}) as rn_${l}`).whereIn(r.foreignKey,n));s&&u.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&u.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(q=>Lr(q,d,e.model.table));return u.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(q=>q.includes(".")?q:`${r.model.table}.${q}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...T).annotate(`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let _=Me__default.default.randomBytes(6).toString("hex"),$=`${r.model.table}_cte_${_}`,V=e.orderByNodes.map(q=>{if(q.isRawValue)return q.column;let Q=q.column.includes(".")?q.column:`${r.model.table}.${q.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,Q)} ${q.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Me__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,x=e.with($,q=>q.select(...T).annotate(`${p.throughModel}.${p.leftForeignKey}`,R).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${V}) as rn_${_}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));h&&x.whereRaw(`rn_${_} <= ${h+(g||0)}`),g&&x.whereRaw(`rn_${_} > ${g}`);let A=T.map(q=>Lr(q,$,e.model.table));return x.select(...A).annotate(`${$}.${R}`,p.leftForeignKey).from($);default:throw new f(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new y(r.model),a=new y(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),m=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let u=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new f(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[k(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await L(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await L(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await L(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 L(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 L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await L(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var br=class extends tt{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 oe(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new we(this.fromNode),this}truncate(){return this.truncateNode=new Te(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=ye()}=e||{};return this.updateNode=new oe(this.fromNode,[r],[o]),this}};function Pc(i){let t=i.name,e=k(t,"snake");return Ap__default.default(e)}function $c(){return {}}var pt=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=$c(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&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 f(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new f(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}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((u,c)=>{let p=o[c];n[u]=p,t[u]??(t[u]=p);});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,this.sqlType,"rows",{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 he([d],this.model)):t}async insertMany(t,e={}){if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let d=this.model.primaryKey,m=Object.keys(t[0]||{});if(d&&!m.includes(d))return this.handleOracleIdentityInsert(t,e)}let r=[];for(let d of t){let{columns:m,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c={};m.forEach((p,h)=>{let g=u[h];c[p]=g,d[p]??(d[p]=g);}),r.push(c);}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,this.sqlType,"rows",{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 he(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:m,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c=Object.fromEntries(m.map((p,h)=>[p,u[h]]));n.push(c);})),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 ce(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await W(s,a,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=A=>this.interpreterUtils.formatStringColumn("mssql",A),d=[],m=t.map(A=>`select ${s.map(Q=>(d.push(A[Q]),`@${d.length}`)).join(", ")}`),u=s.map(l).join(", "),c=m.join(" union all "),p=e.map(A=>`target.${l(A)} = source.${l(A)}`).join(" and "),h=r.filter(A=>!e.includes(A)).map(A=>`target.${l(A)} = source.${l(A)}`).join(", "),g=s.map(l).join(", "),T=s.map(A=>`source.${l(A)}`).join(", "),_=o.returning&&o.returning.length?o.returning.map(A=>`inserted.${l(A)}`).join(", "):s.map(A=>`inserted.${l(A)}`).join(", "),V=(o.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${c}) as source (${u}) on ${p} ${V} when not matched then insert (${g}) values (${T}) output ${_};`;return await W(R,d,this.sqlDataSource,this.sqlType,"rows",{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 f(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let s=r.indexOf(n);s!==-1&&(r.splice(s,1),o.splice(s,1));let{sql:a,bindings:l}=this.astParser.parse([new oe(new F(this.model.table),r,o),new B(n,"and",false,"=",t[n])]);await W(a,l,this.sqlDataSource,this.sqlType,"affectedRows");let d=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!d)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return d}async deleteRecord(t){if(!this.model.primaryKey)throw new f(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new B(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new we(new F(this.model.table)),e]);await W(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new tt(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}dryQuery(){return new br(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 he([a],this.model):null}return await he(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(m=>m[this.model.primaryKey]),l=a.map(m=>`'${m}'`).join(","),d=await this.query().select(...o??"*").whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||"*").whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,h)=>{let g=a[h];l[p]=g,n[p]??(n[p]=g);});let{sql:d,bindings:m}=this.astParser.parse([new U(new F(this.model.table),[l],e.returning)]);await W(d,m,this.sqlDataSource,this.sqlType,"rows");let u=this.query().select(...e.returning||["*"]);for(let[p,h]of Object.entries(l))h!=null&&p!==o&&u.where(p,"=",h);o&&u.orderBy(o,"desc");let c=await u.one({ignoreHooks:["beforeFetch"]});c?(o&&c[o]&&(n[o]=c[o]),r.push(c)):r.push(n);}return await this.model.afterFetch?.(r),r}};var Tr=class extends E{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 ce(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 ce(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new oe(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new we(this.fromNode),this}truncate(){return this.truncateNode=new Te(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=ye()}=t||{};return this.updateNode=new oe(this.fromNode,[e],[r]),this}};var _a=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??ye()});var te=class{constructor(t){this.options=t;}static async createDriver(t){throw new f("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var ft=class ft extends te{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new ft(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new v("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new v("mongodb");return new ft(this.mongoClient)}};ft.mongoClient=null;var wr=ft;var yt=class yt extends te{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new yt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new v("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new v("mssql");return new yt(this.mssqlClient)}};yt.mssqlClient=null;var Nr=yt;var ht=class ht extends te{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new ht(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new v("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new v("mysql2");return new ht(this.mysqlClient)}};ht.mysqlClient=null;var Sr=ht;var gt=class gt extends te{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new gt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new v("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new v("oracledb");return new gt(this.oracledbClient)}};gt.oracledbClient=null;var qr=gt;var bt=class bt extends te{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new bt(this.pgClient);let e=await import('pg').catch(()=>{throw new v("pg")});if(this.pgClient=e.default??e,!this.pgClient)throw new v("pg");return new bt(this.pgClient)}};bt.pgClient=null;var Mr=bt;var Tt=class Tt extends te{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Tt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new v("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new v("sqlite3");return new Tt(this.sqlite3Client)}};Tt.sqlite3Client=null;var _r=Tt;var ie=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Sr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Mr.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await _r.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await wr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Nr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await qr.createDriver(),this.oracledbDriver;default:throw new f(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};ie.mysqlDriver=null,ie.pgDriver=null,ie.sqliteDriver=null,ie.mssqlDriver=null,ie.oracledbDriver=null,ie.mongodbDriver=null;var kp=async i=>(await ie.getDriver(i)).client,wt=async(i,t)=>{let e=await kp(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,m=t,u=m?.database;return new d.Database(u,m?.driverOptions?.mode??void 0,A=>{if(A)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,h=t,{options:g,...T}=h.driverOptions??{};return await p.connect({server:h.host??"localhost",port:h.port,database:h.database,user:h.username,password:h.password,...T,options:{trustServerCertificate:M.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});case "oracledb":let $=e,V=t,R=`${V.host}/${V.database}`;return await $.createPool({user:V.username,password:V.password,connectString:R,...V.driverOptions});default:throw new f("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var Nt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Me__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":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),X("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;X("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");S.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":X("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;X("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":X("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw S.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");S.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":X("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;X("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":X("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw S.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new f("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){S.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 f("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new f("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw S.error(e),new v("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new f("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var fe,Oe=class Oe extends He{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new Rt;this.migrationConfig={path:M.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:Vr(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Oe(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!ke(this,fe))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return ke(this,fe)}static async connectToSecondarySource(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.closeConnection();}catch(s){throw o.isConnected&&await o.closeConnection(),s}}static async closeConnection(){if(!ke(this,fe)){S.warn("Connection already closed");return}await ke(this,fe).closeConnection(),Er(this,fe,null);}static async disconnect(){return this.closeConnection()}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!ke(this,fe)?.globalTransaction}async connect(){if(ke(Oe,fe))throw new f("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await wt(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await wt(e.sqlType,e.inputDetails),e.ownsPool=true;})),Er(Oe,fe,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new f("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new f("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let m=Ur(JSON.stringify(d)),u=m?`${e}:${m}`:e,c=await this.cacheAdapter.get(u);if(c!==void 0)return c;let p=await n(...d);return await this.cacheAdapter.set(u,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new f("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Ur(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Oe(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await wt(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new E(_a(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new Tr(_a(e,r),this)}alterTable(...e){let r=new ue(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new ue(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 Nt(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new f("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){S.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 Nt(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 f("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new pt(e,this.globalTransaction.sql):new pt(e,this)}getPool(){if(!this.sqlPool)throw new f("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new f("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new f("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){X("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{S.warn("SqlDataSource::closeConnection - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.closeConnection();}catch(r){S.warn(`SqlDataSource::closeConnection - Error while closing slave connection: ${r.message}`);}})),X("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new f("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async disconnect(){return this.closeConnection()}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){S.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await or.makeDiff(this)).getSqlStatements();if(!o.length){S.info("No new changes detected between database schema and models metadata");return}if(S.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);S.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),S.info(`Synced schema with ${o.length} SQL statements`);}async rawQuery(e,r=[],o){if(!this.isConnected)throw new f("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=At(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>W(n,r,a,this.getDbType(),"raw")):W(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new C(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 Ja(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Fr(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await Ha(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 $t(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(st(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=Ee(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(),m=Ee(s,d),u=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof u=="string"?u.toLowerCase()!=="no":typeof u=="boolean"?u:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,T=a.numeric_scale!=null?Number(a.numeric_scale):null,_=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:m,isNullable:c,defaultValue:p,length:h,precision:g,scale:T,withTimezone:_}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new xt(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(st(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let m=d.Key_name,u=d.Non_unique===0,c=l.get(m)||{name:m,columns:[],isUnique:u};c.columns.push(d.Column_name),l.set(m,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let m=d.index_name,u=!!d.is_unique,c=l.get(m)||{name:m,columns:[],isUnique:u};c.columns.push(d.column_name),l.set(m,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,m=!!l.unique,c=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(p=>p.name);a.push({name:d,columns:c,isUnique:m});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new It(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(st(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let m=Number(d.id),u=l.get(m)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};u.columns.push(String(d.from)),u.referencedColumns.push(String(d.to)),l.set(m,u);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),m=d||`${l.referenced_table}_${l.column_name}`,u=a.get(m)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};u.columns.push(String(l.column_name)),u.referencedColumns.push(String(l.referenced_column)),a.set(m,u);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Pt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(st(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
164
+ ORDER BY pk`,bindings:[]}}},Cc=new ba;var Ta=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Rc=new Ta;var wa=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}"`:""}},Ac=new wa;var Na=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("sqlite",e.column),o=de.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Oc=new Na;var Sa=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:[]}}},Dc=new Sa;var qa=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},xc=new qa;var Ma=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 C?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},Ic=new Ma;var _a=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}},Pc=new _a;var Ca=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}}},$c=new Ca;var Ra=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}}},Ec=new Ra;var Aa=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}}},vc=new Aa;var Oa=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}}},Bc=new Oa;var Qc={mssql:{alter_table:{add_column:sl,add_constraint:il,add_primary_key:al,alter_column_type:ll,alter_table:dl,drop_column:ul,drop_constraint:ml,drop_default:cl,drop_not_null:pl,drop_primary_key:fl,rename_column:yl,rename_table:hl,set_default:gl,set_not_null:bl},column:{column_type:Tl},constraint:{after:wl,constraint:Nl},create_table:{create_table:Sl},delete:{delete:ql},distinct:{distinct:Ml,distinct_on:_l},drop_table:{drop_table:Cl},extension:{create_extension:Rl},from:{from:Al},group_by:{group_by:Ol},having:{having:Dl},index_op:{create_index:xl,drop_index:Il},insert:{insert:Pl},join:{join:$l},limit:{limit:El},lock:{lock:vl},offset:{offset:Bl},on_duplicate:{on_duplicate:Ql},order_by:{order_by:Kl},raw:{raw:kl},schema:{foreign_key_info:Ll,index_info:jl,primary_key_info:Fl,table_info:Ul},select:{select:Wl,select_json:Vl},truncate:{truncate:Jl},union:{union:Hl},update:{update:Yl},where:{where:zl,where_group:Gl,where_json:Zl,where_subquery:Xl},with:{with:ed}},mysql:{alter_table:{add_column:td,add_constraint:rd,add_primary_key:od,alter_column_type:nd,alter_table:sd,drop_column:id,drop_constraint:ad,drop_default:ld,drop_not_null:dd,drop_primary_key:ud,rename_column:md,rename_table:cd,set_default:pd,set_not_null:fd},column:{column_type:yd},constraint:{after:hd,constraint:gd},create_table:{create_table:bd},delete:{delete:Td},distinct:{distinct:wd,distinct_on:Nd},drop_table:{drop_table:Sd},extension:{create_extension:qd},from:{from:Md},group_by:{group_by:_d},having:{having:Cd},index_op:{create_index:Rd,drop_index:Ad},insert:{insert:Od},join:{join:Dd},limit:{limit:xd},lock:{lock:Id},offset:{offset:Pd},on_duplicate:{on_duplicate:$d},order_by:{order_by:Ed},raw:{raw:vd},schema:{foreign_key_info:Bd,index_info:Qd,primary_key_info:Kd,table_info:kd},select:{select:Ld,select_json:jd},truncate:{truncate:Fd},union:{union:Ud},update:{update:Wd},where:{where:Vd,where_group:Jd,where_json:Hd,where_subquery:Yd},with:{with:zd}},oracledb:{alter_table:{add_column:Gd,add_constraint:Zd,add_primary_key:Xd,alter_column_type:eu,alter_table:tu,drop_column:ru,drop_constraint:ou,drop_default:nu,drop_not_null:su,drop_primary_key:iu,rename_column:au,rename_table:lu,set_default:du,set_not_null:uu},column:{column_type:mu},constraint:{after:cu,constraint:pu},create_table:{create_table:fu},delete:{delete:yu},distinct:{distinct:hu,distinct_on:gu},drop_table:{drop_table:bu},extension:{create_extension:Tu},from:{from:wu},group_by:{group_by:Nu},having:{having:Su},index_op:{create_index:qu,drop_index:Mu},insert:{insert:_u},join:{join:Cu},limit:{limit:Ru},lock:{lock:Au},offset:{offset:Ou},on_duplicate:{on_duplicate:Du},order_by:{order_by:xu},raw:{raw:Iu},schema:{foreign_key_info:Pu,index_info:$u,primary_key_info:Eu,table_info:vu},select:{select:Bu,select_json:Qu},truncate:{truncate:Ku},union:{union:ku},update:{update:Lu},where:{where:ju,where_group:Fu,where_json:Uu,where_subquery:Wu},with:{with:Vu}},postgres:{alter_table:{add_column:Ju,add_constraint:Hu,add_primary_key:Yu,alter_column_type:zu,alter_table:Gu,drop_column:Zu,drop_constraint:Xu,drop_default:em,drop_not_null:tm,drop_primary_key:rm,rename_column:om,rename_table:nm,set_default:sm,set_not_null:im},column:{column_type:am},constraint:{after:lm,constraint:dm},create_table:{create_table:um},delete:{delete:mm},distinct:{distinct:cm,distinct_on:pm},drop_table:{drop_table:fm},extension:{create_extension:ym},from:{from:hm},group_by:{group_by:gm},having:{having:bm},index_op:{create_index:Tm,drop_index:wm},insert:{insert:Nm},join:{join:Sm},limit:{limit:qm},lock:{lock:Mm},offset:{offset:_m},on_duplicate:{on_duplicate:Cm},order_by:{order_by:Rm},raw:{raw:Am},schema:{foreign_key_info:Om,index_info:Dm,primary_key_info:xm,table_info:Im},select:{select:Pm,select_json:$m},truncate:{truncate:Em},union:{union:vm},update:{update:Bm},where:{where:Qm,where_group:Km,where_json:km,where_subquery:Lm},with:{with:jm}},sqlite:{alter_table:{add_column:Fm,add_constraint:Um,alter_column_type:Wm,alter_table:Vm,drop_column:Jm,drop_constraint:Hm,drop_default:Ym,drop_not_null:zm,drop_primary_key:Gm,rename_column:Zm,rename_table:Xm,set_default:ec,set_not_null:tc},column:{column_type:rc},constraint:{after:oc,constraint:nc},create_table:{create_table:sc},delete:{delete:ic},distinct:{distinct:ac,distinct_on:lc},drop_table:{drop_table:dc},extension:{create_extension:uc},from:{from:mc},group_by:{group_by:cc},having:{having:pc},index_op:{create_index:fc,drop_index:yc},insert:{insert:hc},join:{join:gc},limit:{limit:bc},lock:{lock:Tc},offset:{offset:wc},on_duplicate:{on_duplicate:Nc},order_by:{order_by:Sc},raw:{raw:qc},schema:{foreign_key_info:Mc,index_info:_c,primary_key_info:Cc,table_info:Rc},select:{select:Ac,select_json:Oc},truncate:{truncate:Dc},union:{union:xc},update:{update:Ic},where:{where:Pc,where_group:$c,where_json:Ec,where_subquery:vc},with:{with:Bc}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(R=>!!R&&R.folder==="distinctOn"),n=!o&&t.find(R=>!!R&&R.folder==="distinct"),s=this.dbType==="mssql"?t.find(R=>!!R&&R.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(R=>R!==null&&R.folder!=="distinct"&&R.folder!=="distinctOn"),d=l.some(R=>R.folder==="offset"),u=l.some(R=>R.folder==="order_by"),m=l.find(R=>R.folder==="limit"),c=l.find(R=>R.folder==="offset"),p=this.dbType==="mssql"&&m&&!d&&!u,h=this.dbType==="mssql"&&!p&&(m||c),g=this.dbType==="oracledb"&&(m||c),w=[],_=[],$=null;p&&m&&_.push(m.limit);for(let R=0;R<l.length;R++){let I=l[R];if(p&&I.folder==="limit"||h&&(I.folder==="limit"||I.folder==="offset")||g&&(I.folder==="limit"||I.folder==="offset"))continue;I.currParamIndex=e+_.length;let O=Qc[this.mapCommonDbType(this.dbType)][I.folder][I.file];if(!O)throw new Error(`Interpreter not found for ${this.dbType} ${I.keyword}`);O.model=this.model;let q=O.toSql(I);if(!q.sql||!q.sql.trim().length)continue;let Q=l[R+1],D=!Q||Q.keyword!==I.keyword?"":Q.chainsWith;if(I.folder==="lock"||I.folder==="on_duplicate"||I.folder==="schema"){w.push(`${q.sql}${D}`),_.push(...q.bindings),$=I.keyword;continue}if($!==I.keyword||I.canKeywordBeSeenMultipleTimes){if(r)w.push(`${q.sql}${D}`);else {let z=I.keyword;if(I.folder==="with"&&this.dbType!=="mssql"){let le=R,Je=false;for(;le<l.length&&l[le].keyword===I.keyword;){let De=l[le];if(De.folder==="with"&&De.clause==="recursive"){Je=true;break}le++;}Je&&(z=`${z} recursive`);}if(z==="select"){let le=p?`top (@${e}) `:"";if(o){let Je=Array.isArray(o.columns)?o.columns.join(", "):"";w.push(`select ${le}distinct on (${Je}) ${q.sql}${D}`);}else n?w.push(`select ${le}distinct ${q.sql}${D}`):w.push(`select ${le}${q.sql}${D}`);}else z==="from"&&a?w.push(`${z} ${q.sql}${a}${D}`):w.push(`${z} ${q.sql}${D}`);}$=I.keyword;}else w.push(`${q.sql}${D}`);_.push(...q.bindings);}if(h){u||w.push("order by (select null)");let R=c?.offset??0;_.push(R);let O=`offset @${e+_.length-1} rows`;if(m){_.push(m.limit);let q=e+_.length-1;O+=` fetch next @${q} rows only`;}w.push(O);}if(g){u||w.push("order by null");let R=c?.offset??0;_.push(R);let O=`offset :${e+_.length-1} rows`;if(m){_.push(m.limit);let q=e+_.length-1;O+=` fetch next :${q} rows only`;}w.push(O);}return {sql:w.join(" "),bindings:_}}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 Pt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var $t=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Et=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var vt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Bt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var be=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var Xe=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Qt=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 Ce=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 Kt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var Te=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var lt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var kt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var et=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Lt=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 jt=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 Ft=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 Ut=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 Wt=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 Vt=class extends T{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var Jt=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 Ht=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 we=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 Yt=Symbol("columns"),zt=Symbol("primaryKey"),me=Symbol("relations"),Gt=Symbol("indexes"),Zt=Symbol("uniques"),Pe=i=>`${Lp__default.default.singular(i)}_id`,Xt=(i,t)=>`idx_${i}_${t}`,ue=(i,t)=>`uq_${i}_${t}`,Y=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,$e=(i,t)=>`pk_${i}_${t}`;var P=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 dt=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 Fe=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 tt=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 Ee=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var er=class extends T{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var tr=class extends Ee{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=$e(this.tableName,N(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new H("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new H("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??Y(this.tableName??"",N(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new H("foreign_key",{columns:[N(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:[N(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:[N(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new H("null",{columns:[N(this.columnNode.column)]})),this}default(t){let e;return t instanceof C?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:[N(this.columnNode.column)],constraintName:t?.constraintName??ue(this.tableName??"",N(this.columnNode.column))})),this):(this.namedConstraints.push(new H("unique",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName||ue(this.tableName??"",N(this.columnNode.column))})),this)}after(t){return this.nodes.push(new er(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new H("primary_key",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ue=class extends Ee{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}build(e){return this.nodes.push(e),new tr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new C(e)}char(e,r=1){let o=new P(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new P(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new P(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 P(e,"uuid");return this.build(r)}ulid(e){let r=new P(e,"ulid");return this.build(r)}integer(e,r=255){let o=new P(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new P(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new P(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new P(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new P(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new P(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new P(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new P(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new P(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new P(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 P(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new P(e,"time",{precision:r});return this.build(o)}year(e){let r=new P(e,"year");return this.build(r)}datetime(e,r){let o=new P(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new P(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new P(e,"boolean");return this.build(r)}binary(e){let r=new P(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new P(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new P(e,"blob");return this.build(r)}tinyblob(e){let r=new P(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new P(e,"mediumblob");return this.build(r)}longblob(e){let r=new P(e,"longblob");return this.build(r)}json(e){let r=new P(e,"json");return this.build(r)}jsonb(e){let r=new P(e,"jsonb");return this.build(r)}enum(e,r){let o=new P(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new P(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new P(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new P(e,"geometry");return this.build(r)}point(e){let r=new P(e,"point");return this.build(r)}linestring(e){let r=new P(e,"linestring");return this.build(r)}polygon(e){let r=new P(e,"polygon");return this.build(r)}multiPoint(e){let r=new P(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var rr=class extends Ee{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new C(t)}addColumn(t){let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(m=>m.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(m=>{let c=m;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new Bt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(m=>{let c=m;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new be(m));});}alterColumn(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(c=>c.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=N(s.column),l=o.getNodes().find(c=>c.constraintType==="null"),u=o.getNodes().find(c=>c.constraintType==="not_null")||l,m=o.getNodes().find(c=>c.constraintType==="default");this.nodes.push(new Qt(N(a),s,{})),u&&(u.constraintType==="not_null"?this.nodes.push(new Ft(N(a))):u.constraintType==="null"&&this.nodes.push(new kt(N(a)))),m&&(m.defaultValue===void 0||m.defaultValue===null?this.nodes.push(new lt(N(a))):this.nodes.push(new jt(N(a),m.defaultValue))),o.getNodes().forEach(c=>{let p=c;switch(p.constraintType){case "primary_key":this.addPrimaryKey(N(a));break;case "unique":this.unique(N(a),{constraintName:p.constraintName});break;case "foreign_key":this.foreignKey(N(a),p.references?.table??"",N(p.references?.columns?.[0]??""),{constraintName:p.constraintName,onDelete:p.onDelete,onUpdate:p.onUpdate});break}});}dropColumn(t){this.nodes.push(new Kt(t));}renameColumn(t,e){this.nodes.push(new Lt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new lt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Xe([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(new H(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(new H("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??Y(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(new H("unique",{columns:[t],constraintName:e?.constraintName??ue(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=Y(this.table,t,e);this.nodes.push(new Te(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new f("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ue(this.table,t);this.nodes.push(new Te(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Te(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new f("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new f("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new et(t));}};var ce=class{constructor(t){if(this.sqlType=t||M.DB_TYPE,!this.sqlType)throw new f("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new C(t)}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!Kc__default.default.existsSync(t))throw new f("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=Rt__default.default.basename(t),r=Rt__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new f("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=Kc__default.default.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Ue(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new Ut(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 rr(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 Ce(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 Wt(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new Ce(t,[new Ze(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new we(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r){Array.isArray(e)||(e=[e]);let o=r.constraintName||Xt(t,e.join("_")),n=new Jt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Ht(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new Xe(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??ue(t,o.join("_")),s=new H("unique",{columns:o,constraintName:n}),a=new Ce(t,[new be(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=Y(t,e,r),n=new Te(o),s=new Ce(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)?ue(t,e.join("_")):ue(t,e),n=r?.constraintName??o,s=new Te(n),a=new Ce(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new et,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 Ce(t,[new be(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new Te(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}createExtension(t,e=true){let r=new Vt(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new b(t,this.sqlType)}};var or=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let u of d)u.type==="belongsTo"&&u.model().table===n.table&&a.push(`fk.${l.table}.${u.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(d=>d.table===n.table);if(l){let d=l.getColumns().find(u=>u.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let u=l.getRelations();for(let m of u)m.columnName===d.columnName&&a.push(`fk.${n.table}.${m.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let d of l)s(d);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),d=t.relationsToDrop?.find(u=>u.table===a&&u.relation.name===l);d&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:d,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(d)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let d of l)d.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):d.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(d=>d.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){return this.sql.getDbType()==="sqlite"?[]:t.relation.name?this.sql.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 nr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new or(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 ce(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(d=>d.table===o.table)?.getColumns().find(d=>d.columnName===o.columns[0])?.primaryKeyConstraintName||$e(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let u=a||$e(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=N(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=N(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,Y(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=N(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s=e[r.type](...o);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||$e(t,r.columnName)}),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.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 ce(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=N(t.relation.manyToManyOptions.throughModel),r=N(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=N(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),p=c.primaryKey,g=c.getColumns().find(w=>w.columnName===p);if(g)n=g.databaseName;else {let w=c?.databaseCaseConvention||"preserve";n=K(p,w);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),h=p.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",w=p.find(_=>_.columnName===g);if(w)n=w.databaseName;else {let _=c?.databaseCaseConvention||"preserve";n=K(n||g,_);}}}else {let p=c.primaryKey||"id",g=c.getColumns().find(w=>w.columnName===p);if(g)n=g.databaseName;else {let w=c?.databaseCaseConvention||"preserve";n=K(p,w);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=K(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=K(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=N(c),h=a.find(g=>g.columnName===p);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=K(p,g);}}let u=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,c=>{let p=o||Y(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,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 Up(i){return i.replace(/\s+/g," ").trim()}function Wp(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function ve(i,t){let e=Up(t.toLowerCase()),r=Wp(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}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var sr=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(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=N(u.constraintName);o.foreignKeys.find(p=>p.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(p=>p.name===d.databaseName||p.name===d.columnName);if(!u)continue;let m=!e.areColumnsEqual(u,d,o.indexes),c=e.getDefaultChange({table:r.table,dbColumns:u,modelColumn:d});(m||c)&&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 c=N(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:c,relation:{type:"belongsTo",model:()=>r,columnName:N(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?N(d.constraintName):Y(c,N(d.manyToManyOptions.leftForeignKey||Pe(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let u=N(d.constraintName);if(u&&o.foreignKeys.some(c=>c.name===u))continue;o.foreignKeys.find(c=>e.relationMatchesDbRelation(r,d,c))||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=N(d.foreignKey)||d.columnName,c=r.getColumns().find(p=>p.columnName===u)?.databaseName||u;return N(d.constraintName)||Y(r.table,c,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 nr(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=ve(n,t.dataType),a=typeof e.type=="string"?ve(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=N(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",m=d.getColumns().find(h=>h.columnName===u),c=d.table,p=m?.databaseName||u;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=N(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?N(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=N(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),u=(n.type||"belongsTo")==="belongsTo"?N(n.foreignKey):n.columnName,m=l.find(g=>g.columnName===u);m&&(u=m.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&n}getDefaultChange(t){let e=this.sql.getDbType(),r=ve(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?ve(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=N(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(D=>D.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",u=s.getColumns().find(D=>D.columnName===l),m=a.getColumns().find(D=>D.columnName===d);if(!u||!m)continue;let c=N(o.manyToManyOptions.leftForeignKey)||l,p=N(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(u,c),w=this.clonePkAsColumn(m,p),_=h.columns.find(D=>D.name===c),$=h.columns.find(D=>D.name===p),V=_?this.areColumnsEqual(_,g,h.indexes):false,R=$?this.areColumnsEqual($,w,h.indexes):false;for(let D of h.foreignKeys){let z=D.referencedTable===s.table,le=D.referencedTable===a.table;if(!z&&!le)continue;let Je=z?c:p,De=D.columns[0];De&&De!==Je&&(this.data.relationsToDrop.push({table:n,relation:D}),De!==c&&De!==p&&this.data.columnsToDrop.push({table:n,column:De}));}let I={};V||(I[g.databaseName]=g),R||(I[w.databaseName]=I[w.databaseName]||w);for(let D of Object.keys(I))this.data.columnsToAdd.push({table:n,column:I[D]});let O=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),q=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),Q=h.foreignKeys.find(D=>D.referencedTable===s.table&&D.columns.length===1&&D.columns[0]===c),Me=h.foreignKeys.find(D=>D.referencedTable===a.table&&D.columns.length===1&&D.columns[0]===p);if(!Q){let D=h.foreignKeys.find(z=>z.referencedTable===s.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(O);}if(!Me){let D=h.foreignKeys.find(z=>z.referencedTable===a.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(q);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,u=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=N(a.constraintName)||Y(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(w=>w.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(w=>w.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 w=g.primaryKey||"id";u=g.getColumns().find($=>$.columnName===w)?.databaseName||w;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let w=m.has(g.columns[0]),_=g.referencedTable===d,$=g.referencedColumns[0]===u;return w&&_&&$}),p=N(o.relation.constraintName)||Y(o.table,l,d),h=e.get(o.table)||new Set;if(c||p&&h.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=N(o.relation.manyToManyOptions.throughModel),w=N(o.relation.manyToManyOptions.leftForeignKey),_=N(o.relation.manyToManyOptions.rightForeignKey),$=o.table===g&&o.relation.columnName===w&&o.relation.model().table===s?.table,V=o.table===g&&o.relation.columnName===_&&o.relation.model().table!==s?.table,R=await this.sql.getTableSchema(g),I=R.foreignKeys.some(q=>q.columns.length===1&&q.columns[0]===w&&q.referencedTable===(s?.table||"")),O=R.foreignKeys.some(q=>q.columns.length===1&&q.columns[0]===_&&q.referencedTable===o.relation.model().table);if($&&I||V&&O)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(w=>w.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),p=c.primaryKey||"id",g=c.getColumns().find(w=>w.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){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?N(n):Y(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 Ne=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 j=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 pe=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 oe=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 B=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 ut=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 ne=class extends B{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 Ae=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 ir=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);});}},jc=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,u)=>{n.run(i,t,function(m){m&&u(m),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,u)=>{n.all(i,t,(m,c)=>{m&&u(m),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.message)):d(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([h]);return}let g=h?.[a]||this.lastID;if(!g)return c(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let w=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(w,[g],(_,$)=>{if(_)return c(_);m([$]);});});});if(!Array.isArray(r.models))throw new f("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(d);});});let u=[];return new Promise(async(m,c)=>{try{let p=d.map(async h=>{let g=new y(s),{columns:w,values:_}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),$=Object.fromEntries(w.map((O,q)=>[O,_[q]])),V=new b(s,e.getDbType()),{sql:R,bindings:I}=V.parse([new U(new j(s.table),[$])]);return new Promise((O,q)=>{n.run(R,I,function(Q){if(Q)return q(Q);let Me=h[a]||this.lastID;if(!Me)return q(new f("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let D=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(D,[Me],(z,le)=>{if(z)return q(z);O(le);});});})});u=await Promise.all(p),m(u);}catch(p){c(p);}})}return new Promise((d,u)=>{n.run(i,t,function(m){m?u(new Error(m.message)):d(this.changes);});})};var Jp=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Hp=/^\d{4}-\d{2}-\d{2}$/,Da=i=>typeof i!="string"?i:Jp.test(i)?new Date(i.replace(" ","T")+"Z"):Hp.test(i)?new Date(i+"T00:00:00Z"):i,Yp=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),Fc=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Yp(r):t[e]=r;}return t};var W=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||X(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await mt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=await mt(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?d.rows:o==="raw"?d:d.rowCount;case "sqlite":let u=await mt(()=>jc(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(u)?u:[u]:u;case "mssql":let m=e.getPool(),c=e.sqlConnection?e.sqlConnection.request():m.request();t.forEach((V,R)=>{c.input(`p${R}`,V);});let p=0,h=i.replace(/\?|@(\d+)/g,()=>`@p${p++}`),g=await mt(()=>c.query(h),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?g.rowsAffected[0]:o==="raw"?g:g.recordset;case "oracledb":let w=4002,_=null,$=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let V=t.map(Da),R=await mt(()=>_.execute(i,V,{outFormat:w,autoCommit:!$}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?R.rowsAffected:o==="raw"?R:await Promise.all(R.rows?.map(async O=>{let q=await Fc(O),Q={};for(let Me in q)Q[Me.toLowerCase()]=q[Me];return Q})??[])}finally{_&&!$&&await _.close();}default:throw new f("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},lr=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,h=()=>{try{a.release();}catch{}};return u.on("data",g=>{if(o.onData){m++,Promise.resolve(o.onData(l,g)).then(()=>{m--,c&&m===0&&!p&&(h(),l.end());}).catch(w=>{p=true,h(),l.destroy(w);});return}l.write(g);}),u.on("end",()=>{c=true,m===0&&!p&&(h(),l.end());}),u.on("error",g=>{p=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new v("pg-query-stream")}),d=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),u=new l.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=a.query(u),c=0,p=false,h=false,g=w=>{try{a.release(w);}catch{}};return m.on("data",w=>{if(o.onData){c++,Promise.resolve(o.onData(d,w)).then(()=>{c--,p&&c===0&&!h&&(g(),d.end());}).catch(_=>{h=true,g(_),d.destroy(_);});return}d.write(w);}),m.on("end",()=>{p=true,c===0&&!h&&(g(),d.end());}),m.on("error",w=>{h=true,g(w),d.destroy(w);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new ir(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((h,g)=>{l.input(`p${g}`,h);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),m=0,c=false,p=false;return l.on("row",h=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,h)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(g=>{p=true,a.destroy(g);});return}a.write(h);}}),l.on("error",h=>{p=true,a.destroy(h);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(u),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,u=t.map(Da),m=a.queryStream(i,u,{outFormat:d}),c=0,p=false,h=false,g=async()=>{try{await a.close();}catch{}};return m.on("data",w=>{if(h)return;let _={};for(let $ in w)_[$.toLowerCase()]=w[$];if(o.onData){c++,Promise.resolve(o.onData(l,_)).then(()=>{c--,p&&c===0&&!h&&(g(),l.end());}).catch($=>{h=true,g(),l.destroy($);});return}l.write(_);}),m.on("end",()=>{p=true,c===0&&!h&&(g(),l.end());}),m.on("error",w=>{h=true,g(),l.destroy(w);}),l}default:throw new f("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function mt(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,rl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var L=(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 ee=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 ct=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=dr(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new f("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function ur(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 Uc(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var rt=i=>typeof i=="number"?i:parseFloat(i);var We=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 mr=class extends T{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var cr=class extends T{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Be=class extends T{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var se=class extends 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 pt=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 pr=class extends T{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var fr=class extends T{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var ft=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 yr=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 pt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new pt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new ft(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new ft(t,"asc",true)),this}limit(t){return typeof t!="number"&&S.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new pr(t),this}offset(t){return typeof t!="number"&&S.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new fr(t),this}};var hr=class extends yr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new f("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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(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 f("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var gr=class extends hr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.modelAnnotatedColumns=[];this.dbType=r.getDbType(),this.fromNode=new j(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],e.map(o=>K(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new ee(o));}),this}selectRaw(e){return this.selectNodes.push(new ee(e,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new j(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 ee(s,a,n)),this.modelAnnotatedColumns.push(a),this}from(e){return this.fromNode=new j(e),this}table(e){return this.fromNode=new j(e),this}distinct(){return this.distinctNode=new mr,this}distinctOn(...e){return this.distinctOnNode=new cr(e),this}selectJson(e,r,o){return this.selectNodes.push(new Be(e,r,o,"extract")),this.modelAnnotatedColumns.push(o),this}selectJsonText(e,r,o){return this.selectNodes.push(new Be(e,r,o,"extract_text")),this.modelAnnotatedColumns.push(o),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Be(e,r,o,"array_length")),this.modelAnnotatedColumns.push(o),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Be(e,r,o,"object_keys")),this.modelAnnotatedColumns.push(o),this}selectJsonRaw(e,r){return this.selectNodes.push(new Be(e,"",r,"raw",true)),this.modelAnnotatedColumns.push(r),this}};var br=class extends gr{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 E&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||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 E&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 E&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof E||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof E)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new B(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 B(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new B(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 B(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new B(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 B(e,"and",false,"in",r)),this):(this.whereNodes.push(new B("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new B(e,"or",false,"in",r)),this):(this.whereNodes.push(new B("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 B(e,"and",true,"in",r)),this):(this.whereNodes.push(new B("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new B(e,"or",true,"in",r)),this):(this.whereNodes.push(new B("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new B(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new B(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new B(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new B(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 B(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 B(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new B(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ae("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ae("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ae("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof E?e:new E(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Ae("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new B(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new B(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 We(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 We(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new We(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new We(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof E)return e;let r=new E(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Ae(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Ae(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new E(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new ut(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new E(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new ut(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Tr=class extends br{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ne(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ne(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ne(t,"or",false,"raw",e)),this}};var E=class i extends Tr{constructor(e,r=fe.instance){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.replicationMode=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);}setReplicationMode(e){return this.replicationMode=e,this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>W(e,r,o,this.dbType,"rows",{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 f("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await lr(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let s=await this.many(),a=await n.getCount(),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:Uc(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 ee(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new ee(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new dt("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new dt("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Fe(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Fe(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Fe(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Fe(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?rt(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?rt(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?rt(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?rt(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?rt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&S.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:ur(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new f("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new j(n,r),this}return this.fromNode=new j(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 tt("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 tt("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new f("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new tt("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((m,c)=>[m,n[c]]));this.insertNode=new U(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),u=await W(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(u)&&u.length?u[0]:u}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async l=>{let{columns:d,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(l),Object.values(l),"insert");return Object.fromEntries(d.map((m,c)=>[m,u[c]]))}));this.insertNode=new U(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]),a=await this.getSqlDataSource("write");return W(n,s,a,this.dbType,"rows",{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((h,g)=>[h,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 j(this.model.table),[d],void 0,true),new pe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),p=await W(u,m,c,this.dbType,"rows",{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 m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert"),h=Object.fromEntries(c.map((g,w)=>[g,p[w]]));s.push(h);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(s,e,r,n,o);let{sql:a,bindings:l}=this.astParser.parse([new U(new j(this.model.table),s,void 0,true),new pe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),u=await W(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(u)?u:[u]}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=Q=>this.interpreterUtils.formatStringColumn("mssql",Q),u=[],m=e.map(Q=>`select ${a.map(D=>(u.push(Q[D]),`@${u.length}`)).join(", ")}`),c=a.map(d).join(", "),p=m.join(" union all "),h=r.map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(" and "),g=o.filter(Q=>!r.includes(Q)).map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(", "),w=a.map(d).join(", "),_=a.map(Q=>`source.${d(Q)}`).join(", "),$=n.returning&&n.returning.length?n.returning.map(Q=>`inserted.${d(Q)}`).join(", "):a.map(Q=>`inserted.${d(Q)}`).join(", "),R=(n.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",I=`merge into ${l} as target using (${p}) as source (${c}) on ${h} ${R} when not matched then insert (${w}) values (${_}) output ${$};`,O=await this.getSqlDataSource("write"),q=await W(I,u,O,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(q)?q:[q]}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 oe(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return W(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new we(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await W(e,r,o,this.dbType,"rows");}async delete(){this.deleteNode=new Ne(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return W(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=he()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new oe(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return W(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return nl(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new ee("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=xt(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=F(this.modelSelectedColumns),e.modelAnnotatedColumns=F(this.modelAnnotatedColumns),e.distinctNode=F(this.distinctNode),e.distinctOnNode=F(this.distinctOnNode),e.selectNodes=F(this.selectNodes),e.withQuery=F(this.withQuery),e.joinNodes=F(this.joinNodes),e.whereNodes=F(this.whereNodes),e.groupByNodes=F(this.groupByNodes),e.havingNodes=F(this.havingNodes),e.orderByNodes=F(this.orderByNodes),e.lockQueryNodes=F(this.lockQueryNodes),e.unionNodes=F(this.unionNodes),e.withNodes=F(this.withNodes),e.fromNode=F(this.fromNode),e.limitNode=F(this.limitNode),e.offsetNode=F(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 ee("*")]),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 L(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await L(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 L(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await L(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await L(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await L(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await L(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var ot=class i extends E{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 ct(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 f(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 ge(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(),n=await this.getSqlDataSource("read");return await lr(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),u=await ge([d],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);u&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([u]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new f(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}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:ur(e,r,d),data:l}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new ee(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 ee(s,a,n)),this.modelAnnotatedColumns.push(a),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}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=F(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let h=n.get(String(p));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let h=s.get(String(p));c[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=a.get(String(p))||[];c[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new f(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,u=l.leftForeignKey,m=this.modelColumnsMap.get(u)||this.modelColumnsDatabaseNames.get(u)||K(u,this.model.modelCaseConvention);o.forEach(c=>{let p=c.$annotations||{},h=p[m];if(h==null)return;let g=String(h);d.has(g)||d.set(g,[]),this.modelAnnotatedColumns.includes(m)||(delete p[m],Object.keys(p).length||delete c.$annotations),d.get(g).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let h=d.get(String(p))||[];c[e.columnName]=h;});break;default:throw new f(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=_e__default.default.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,u=e.orderByNodes.map(q=>q.isRawValue?q.column:`${this.interpreterUtils.formatStringColumn(this.dbType,q.column)} ${q.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(d,q=>q.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${u}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(q=>Fr(q,d,e.model.table));return m.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,w=e.modelSelectedColumns.length?e.modelSelectedColumns.map(q=>q.includes(".")?q:`${r.model.table}.${q}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...w).annotate(`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let _=_e__default.default.randomBytes(6).toString("hex"),$=`${r.model.table}_cte_${_}`,V=e.orderByNodes.map(q=>{if(q.isRawValue)return q.column;let Q=q.column.includes(".")?q.column:`${r.model.table}.${q.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,Q)} ${q.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${_e__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,I=e.with($,q=>q.select(...w).annotate(`${p.throughModel}.${p.leftForeignKey}`,R).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${V}) as rn_${_}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));h&&I.whereRaw(`rn_${_} <= ${h+(g||0)}`),g&&I.whereRaw(`rn_${_} > ${g}`);let O=w.map(q=>Fr(q,$,e.model.table));return I.select(...O).annotate(`${$}.${R}`,p.leftForeignKey).from($);default:throw new f(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new f(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new y(r.model),a=new y(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new f(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),u=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new f(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let m=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new f(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={},n={};return Object.entries(e).forEach(([s,a])=>{if(s==="$annotations"||this.modelColumnsDatabaseNames.get(s)){o[s]=a;return}n[K(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await L(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await L(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await L(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 L(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 L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await L(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var wr=class extends ot{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 oe(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new Ne(this.fromNode),this}truncate(){return this.truncateNode=new we(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=he()}=e||{};return this.updateNode=new oe(this.fromNode,[r],[o]),this}};function Wc(i){let t=i.name,e=K(t,"snake");return Lp__default.default(e)}function Vc(){return {}}var yt=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Vc(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&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 f(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new f(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}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,c)=>{let p=o[c];n[m]=p,t[m]??(t[m]=p);});let{sql:s,bindings:a}=this.astParser.parse([new U(new j(this.model.table),[n],e.returning)]),l=await W(s,a,this.sqlDataSource,this.sqlType,"rows",{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 ge([d],this.model)):t}async insertMany(t,e={}){if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let d=this.model.primaryKey,u=Object.keys(t[0]||{});if(d&&!u.includes(d))return this.handleOracleIdentityInsert(t,e)}let r=[];for(let d of t){let{columns:u,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c={};u.forEach((p,h)=>{let g=m[h];c[p]=g,d[p]??(d[p]=g);}),r.push(c);}let{sql:o,bindings:n}=this.astParser.parse([new U(new j(this.model.table),r,e.returning)]),s=await W(o,n,this.sqlDataSource,this.sqlType,"rows",{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 ge(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"),c=Object.fromEntries(u.map((p,h)=>[p,m[h]]));n.push(c);})),this.sqlType==="mssql")return this.executeMssqlMerge(n,t,e,o,r);let{sql:s,bindings:a}=this.astParser.parse([new U(new j(this.model.table),n,void 0,true),new pe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await W(s,a,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=O=>this.interpreterUtils.formatStringColumn("mssql",O),d=[],u=t.map(O=>`select ${s.map(Q=>(d.push(O[Q]),`@${d.length}`)).join(", ")}`),m=s.map(l).join(", "),c=u.join(" union all "),p=e.map(O=>`target.${l(O)} = source.${l(O)}`).join(" and "),h=r.filter(O=>!e.includes(O)).map(O=>`target.${l(O)} = source.${l(O)}`).join(", "),g=s.map(l).join(", "),w=s.map(O=>`source.${l(O)}`).join(", "),_=o.returning&&o.returning.length?o.returning.map(O=>`inserted.${l(O)}`).join(", "):s.map(O=>`inserted.${l(O)}`).join(", "),V=(o.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${V} when not matched then insert (${g}) values (${w}) output ${_};`;return await W(R,d,this.sqlDataSource,this.sqlType,"rows",{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 f(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let s=r.indexOf(n);s!==-1&&(r.splice(s,1),o.splice(s,1));let{sql:a,bindings:l}=this.astParser.parse([new oe(new j(this.model.table),r,o),new B(n,"and",false,"=",t[n])]);await W(a,l,this.sqlDataSource,this.sqlType,"affectedRows");let d=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!d)throw new f(this.model.name+"::updateRecord","ROW_NOT_FOUND");return d}async deleteRecord(t){if(!this.model.primaryKey)throw new f(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new B(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new Ne(new j(this.model.table)),e]);await W(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ot(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}dryQuery(){return new wr(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 ge([a],this.model):null}return await ge(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(u=>u[this.model.primaryKey]),l=a.map(u=>`'${u}'`).join(","),d=await this.query().select(...o??"*").whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||"*").whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,h)=>{let g=a[h];l[p]=g,n[p]??(n[p]=g);});let{sql:d,bindings:u}=this.astParser.parse([new U(new j(this.model.table),[l],e.returning)]);await W(d,u,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,h]of Object.entries(l))h!=null&&p!==o&&m.where(p,"=",h);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});c?(o&&c[o]&&(n[o]=c[o]),r.push(c)):r.push(n);}return await this.model.afterFetch?.(r),r}};var Nr=class extends E{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 j(this.model.table),[e],void 0,true),this.onDuplicateNode=new pe(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 j(this.model.table),s,void 0,true),this.onDuplicateNode=new pe(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new oe(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new Ne(this.fromNode),this}truncate(){return this.truncateNode=new we(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=he()}=t||{};return this.updateNode=new oe(this.fromNode,[e],[r]),this}};var Ia=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??he()});var te=class{constructor(t){this.options=t;}static async createDriver(t){throw new f("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var ht=class ht extends te{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new ht(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new v("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new v("mongodb");return new ht(this.mongoClient)}};ht.mongoClient=null;var Sr=ht;var gt=class gt extends te{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new gt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new v("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new v("mssql");return new gt(this.mssqlClient)}};gt.mssqlClient=null;var qr=gt;var bt=class bt extends te{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new bt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new v("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new v("mysql2");return new bt(this.mysqlClient)}};bt.mysqlClient=null;var Mr=bt;var Tt=class Tt extends te{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new Tt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new v("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new v("oracledb");return new Tt(this.oracledbClient)}};Tt.oracledbClient=null;var _r=Tt;var wt=class wt extends te{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new wt(this.pgClient);let e=await import('pg').catch(()=>{throw new v("pg")});if(this.pgClient=e.default??e,!this.pgClient)throw new v("pg");return new wt(this.pgClient)}};wt.pgClient=null;var Cr=wt;var Nt=class Nt extends te{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Nt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new v("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new v("sqlite3");return new Nt(this.sqlite3Client)}};Nt.sqlite3Client=null;var Rr=Nt;var ie=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Mr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Cr.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Rr.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await Sr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await qr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await _r.createDriver(),this.oracledbDriver;default:throw new f(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};ie.mysqlDriver=null,ie.pgDriver=null,ie.sqliteDriver=null,ie.mssqlDriver=null,ie.oracledbDriver=null,ie.mongodbDriver=null;var Gp=async i=>(await ie.getDriver(i)).client,St=async(i,t)=>{let e=await Gp(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,O=>{if(O)throw new f("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,h=t,{options:g,...w}=h.driverOptions??{};return await p.connect({server:h.host??"localhost",port:h.port,database:h.database,user:h.username,password:h.password,...w,options:{trustServerCertificate:M.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...g,abortTransactionOnError:false,enableImplicitTransactions:false}});case "oracledb":let $=e,V=t,R=`${V.host}/${V.database}`;return await $.createPool({user:V.username,password:V.password,connectString:R,...V.driverOptions});default:throw new f("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var qt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=_e__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":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),X("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;X("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");S.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":X("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;X("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":X("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw S.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new f("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");S.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":X("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;X("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":X("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new f("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw S.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new f("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){S.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 f("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new f("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw S.error(e),new v("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new f("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var ye,Oe=class Oe extends Ye{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new Ot;this.migrationConfig={path:M.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:Hr(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Oe(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!Le(this,ye))throw new f("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Le(this,ye)}static async connectToSecondarySource(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Oe(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.closeConnection();}catch(s){throw o.isConnected&&await o.closeConnection(),s}}static async closeConnection(){if(!Le(this,ye)){S.warn("Connection already closed");return}await Le(this,ye).closeConnection(),Br(this,ye,null);}static async disconnect(){return this.closeConnection()}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!Le(this,ye)?.globalTransaction}async connect(){if(Le(Oe,ye))throw new f("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await St(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await St(e.sqlType,e.inputDetails),e.ownsPool=true;})),Br(Oe,ye,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new f("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new f("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let u=Vr(JSON.stringify(d)),m=u?`${e}:${u}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...d);return await this.cacheAdapter.set(m,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new f("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Vr(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new f("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Oe(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await St(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new E(Ia(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new Nr(Ia(e,r),this)}alterTable(...e){let r=new ce(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new ce(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 qt(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new f("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){S.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 qt(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 f("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new yt(e,this.globalTransaction.sql):new yt(e,this)}getPool(){if(!this.sqlPool)throw new f("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new f("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new f("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){X("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{S.warn("SqlDataSource::closeConnection - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.closeConnection();}catch(r){S.warn(`SqlDataSource::closeConnection - Error while closing slave connection: ${r.message}`);}})),X("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new f("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async disconnect(){return this.closeConnection()}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){S.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await sr.makeDiff(this)).getSqlStatements();if(!o.length){S.info("No new changes detected between database schema and models metadata");return}if(S.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);S.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),S.info(`Synced schema with ${o.length} SQL statements`);}async rawQuery(e,r=[],o){if(!this.isConnected)throw new f("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=xt(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>W(n,r,a,this.getDbType(),"raw")):W(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new C(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 tl(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Ur(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new f("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await el(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 vt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(at(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=ve(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=ve(s,d),m=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof m=="string"?m.toLowerCase()!=="no":typeof m=="boolean"?m:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,w=a.numeric_scale!=null?Number(a.numeric_scale):null,_=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:c,defaultValue:p,length:h,precision:g,scale:w,withTimezone:_}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new $t(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(at(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let u=d.Key_name,m=d.Non_unique===0,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.Column_name),l.set(u,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let u=d.index_name,m=!!d.is_unique,c=l.get(u)||{name:u,columns:[],isUnique:m};c.columns.push(d.column_name),l.set(u,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,c=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(p=>p.name);a.push({name:d,columns:c,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Pt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(at(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 Et(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(at(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
165
165
  v_result NUMBER;
166
166
  BEGIN
167
167
  v_result := DBMS_LOCK.REQUEST(
@@ -184,7 +184,7 @@ ORDER BY ordinal_position`,bindings:[]}}},Su=new Ti;var wi=class{toSql(t){let e=
184
184
  ELSE
185
185
  :result := 0;
186
186
  END IF;
187
- END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return S.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return S.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return S.error(`Failed to release lock: ${n.message||JSON.stringify(o)} (dbType: ${r}, lockKey: ${e}). Full error: ${JSON.stringify(o)}`),false}}hashStringToLockId(e){let r=0;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);r=(r<<5)-r+n,r=r&r;}return Math.abs(r)}async executeOnSlave(e){let r=this.getSlave();if(!r)return e(this);try{return await e(r)}catch(o){let n=o instanceof Error?o:new Error(String(o));if(this.onSlaveServerFailure)return await this.onSlaveServerFailure(n,{host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,type:r.sqlType}),e(this);throw n}}async connectWithoutSettingPrimary(){this.sqlPool=await wt(this.sqlType,this.inputDetails),this.ownsPool=true;}};fe=new WeakMap,Qa(Oe,fe,null);var pe=Oe;var Ec=["postgres","cockroachdb"];var St=class St extends De{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:Pc(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Lc(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=ar(s).find(h=>h.columnName===t);if(!l)throw new f(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new f(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=k(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),m=k(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),u=r.map((h,g)=>({[d]:e[s.primaryKey],[m]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends St{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(u);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof f&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new f(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e);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(u=>{let c=new Set(Object.keys(u));return t.every(p=>c.has(p))}))throw new f("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(Ec.includes(l))return await he(a,o,r.returning);let d=n.query();r.returning?.length&&d.select(...r.returning);let m=new Map;return t.forEach(u=>{e.forEach(c=>{m.set(u,[...m.get(u)||[],c[u]]);});}),d.where(u=>{t.forEach(c=>{u.orWhereIn(c,m.get(c)||[]);});}),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 Dt(this)}static getRelations(){return Kc(this)}static getIndexes(){return Fc(this)}static getUniques(){return jc(this)}static column(t,...e){O(...e)(this.prototype,t);}static hasOne(t,...e){Bc(...e)(this.prototype,t);}static hasMany(t,...e){Qc(...e)(this.prototype,t);}static belongsTo(t,...e){vc(...e)(this.prototype,t);}static manyToMany(t,...e){kc(...e)(this.prototype,t);}static establishConnection(){let t=pe.instance;if(!t)throw new f("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){let e;if(t?.connection)e=t.connection.getModelManager(this);else if(t?.trx)e=t.trx.sql.getModelManager(this);else {let r=this;r.establishConnection(),e=r.sqlInstance.getModelManager(r);}return t?.replicationMode&&e.setReplicationMode(t.replicationMode),e}mergeProps(t){this.constructor.combineProps(this,t);}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new f(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 f(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new f(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 f(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new f(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 f(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new f(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 f(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new f(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};St.softDeleteColumn="deletedAt",St.softDeleteValue=ye();var ae=St;var Ne=class{constructor(t,e){this.model=ae;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Cr=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Rr=class extends Ne{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Or=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Ar=class extends Ne{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function Pv(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(zt,e.prototype)||[];o.push({columns:r,name:t??Gt(e.table,r.join("_"))}),K.defineMetadata(zt,o,e.prototype);}}function $v(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(Yt,e.prototype)||[];o.push({columns:r,name:t??de(e.table,r.join("_"))}),K.defineMetadata(Yt,o,e.prototype);}}function Ev(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 O(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(K.getMetadata(Jt,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");K.defineMetadata(Jt,r,e);}let n=i.databaseName??k(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??Pe(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(Ht,e)||[];a.push(s),K.defineMetadata(Ht,a,e);}}O.primary=Fp;O.date=Zp;O.datetime=Xp;O.timestamp=ef;O.time=tf;O.boolean=Gp;O.json=rf;O.uuid=Hp;O.ulid=Jp;O.integer=Up;O.float=jp;O.increment=Wp;O.bigIncrement=Vp;O.encryption={symmetric:zp,asymmetric:Yp};function Fp(i={}){return O({...i,primaryKey:true})}function jp(i={}){return O({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 Up(i={}){return O({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 Wp(i={}){return O({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 Vp(i={}){return O({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 Hp(i={}){return O({type:"uuid",...i,prepare:t=>t||Me__default.default.randomUUID()})}function Jp(i={}){return O({type:"ulid",...i,prepare:t=>t||Ua()})}function zp(i){return O({...i,prepare:t=>t&&Ka(i.key,t),serialize:t=>t&&La(i.key,t)})}function Yp(i){return O({...i,prepare:t=>t&&Fa(i.publicKey,t),serialize:t=>t&&ja(i.privateKey,t)})}function Gp(i={}){return O({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function Zp(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"DATE_ONLY",t):typeof d=="string"?d:re(d,"DATE_ONLY",t):r?re(new Date,"DATE_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:ot(d,void 0,t)};return O({type:"date",...s,autoUpdate:e,prepare:d=>{let m=a(d);return o?o(m):m},serialize:d=>{let m=l(d);return n?n(m):m}})}function Xp(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"ISO",t):typeof d=="string"?d:re(d,"ISO",t):r?re(new Date,"ISO",t):null,l=d=>{if(d!==void 0)return d===null?null:ot(d,void 0,t)};return O({type:"datetime",...s,autoUpdate:e,prepare:d=>{let m=a(d);return o?o(m):m},serialize:d=>{let m=l(d);return n?n(m):m}})}function ef(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"TIMESTAMP",t):typeof d=="string"?d:re(d,"TIMESTAMP",t):r?re(new Date,"TIMESTAMP",t):null,l=d=>{if(d!==void 0)return d===null?null:ot(d,void 0,t)};return O({type:"timestamp",...s,autoUpdate:e,prepare:d=>{let m=a(d);return o?o(m):m},serialize:d=>{let m=l(d);return n?n(m):m}})}function tf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"TIME_ONLY",t):typeof d=="string"?d:re(d,"TIME_ONLY",t):r?re(new Date,"TIME_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:ot(d,void 0,t)};return O({type:"time",...s,autoUpdate:e,prepare:d=>{let m=a(d);return o?o(m):m},serialize:d=>{let m=l(d);return n?n(m):m}})}function rf(i={}){return O({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function Dt(i){try{return K.getMetadata(Ht,i.prototype)||[]}catch{return []}}function vc(i,t,e){return (r,o)=>{let n=()=>xe(i().table),s=()=>{let d=r.constructor.table,m=t||n();return z(d,m,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(me,r)||[];l.push(a),K.defineMetadata(me,l,r);}}function Bc(i,t){return (e,r)=>{let o=()=>xe(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=K.getMetadata(me,e)||[];s.push(n),K.defineMetadata(me,s,e);}}function Qc(i,t){return (e,r)=>{let o=()=>xe(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=K.getMetadata(me,e)||[];s.push(n),K.defineMetadata(me,s,e);}}function kc(i,t,e,r){return (o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,m=o.constructor.table,u=()=>xe(m),c=()=>xe(i().table),p=()=>z(N(d),s?String(s):u()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??p,foreignKey:s?String(s):u,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:m,throughModel:d,leftForeignKey:s?String(s):u,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=K.getMetadata(me,o)||[];g.push(h),K.defineMetadata(me,g,o);}}function Kc(i){return K.getMetadata(me,i.prototype)||[]}function ar(i){return (K.getMetadata(me,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=N(s),l=o();switch(r){case "belongsTo":return new Cr(l,n,a);case "hasOne":return new Or(l,n,a);case "hasMany":return new Rr(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new f("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new Ar(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:N(e.manyToManyOptions.throughModel),leftForeignKey:N(e.manyToManyOptions.leftForeignKey),rightForeignKey:N(e.manyToManyOptions.rightForeignKey)});default:throw new f("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Lc(i){return K.getMetadata(Jt,i.prototype)}function Fc(i){return K.getMetadata(zt,i.prototype)||[]}function jc(i){return K.getMetadata(Yt,i.prototype)||[]}var Ca=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})))}},of=(i,t)=>new Ca(i,t);var qt=class extends ae{};G([O.datetime({autoCreate:true,openApi:{type:"string",format:"date-time",required:true}})],qt.prototype,"createdAt"),G([O.datetime({autoCreate:true,autoUpdate:true,openApi:{type:"string",format:"date-time",required:true}})],qt.prototype,"updatedAt"),G([O.datetime({openApi:{type:"string",format:"date-time",required:true}})],qt.prototype,"deletedAt");var Ra=class extends ae{};G([O.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],Ra.prototype,"id");var Oa=class extends ae{};G([O.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Oa.prototype,"id");var Ue=class extends ae{};G([O.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Ue.prototype,"id"),G([O({type:"varchar",length:255,openApi:{type:"string",required:true}})],Ue.prototype,"email"),G([O.datetime({autoCreate:true,openApi:{type:"string",format:"date-time",required:true}})],Ue.prototype,"createdAt"),G([O.datetime({autoCreate:true,autoUpdate:true,openApi:{type:"string",format:"date-time",required:true}})],Ue.prototype,"updatedAt"),G([O.datetime({openApi:{type:"string",format:"date-time",required:true}})],Ue.prototype,"deletedAt");var Uc=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw S.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new v("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw S.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:sf}=Ap__default.default;function Wc(i){let t=i.name,e=k(t,"snake");return sf(e)}function Vc(){return {$annotations:{}}}var rt=class extends De{static get collection(){return this._collection||Wc(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=Mt.getInstance();if(!t)throw new f("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){Br()(this.prototype,t);}static async afterFetch(t){return t}};G([Br()],rt.prototype,"id");async function ve(i,t,e){if(!t)return null;let r=Vc(),o=ka(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=k(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=k(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=k(n,i.modelCaseConvention);r[s]=null;}})),r}async function Dr(i,t,e){return (await Promise.all(t.map(async o=>await ve(i,o,e)))).filter(o=>o!==null)}var Ir=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,session:this.session}),o=await ve(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new f("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await Dr(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await ve(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await Dr(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 Dr(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 S.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 S.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 S.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 S.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 S.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 S.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 xr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=rt,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new f("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Ir(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await ve(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await ve(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await ve(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var Be=class Be extends He{constructor(e){super({type:"mongo",url:e?.url,logs:e?.logs});this.mongoClient=null;this.isConnected=false,this.mongoOptions=e?.options,this.url||(this.url=M.MONGO_URL);}async connect(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,Be.instance=this;}async connectWithoutSettingPrimary(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true;}getCurrentConnection(){if(!this.mongoClient)throw new f("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}static async connectToSecondarySource(e){let r=new Be(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!Be.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Be.instance}startSession(){if(!this.mongoClient)throw new f("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}static async disconnect(){if(!this.instance)throw new f("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(e,r){let o=new Be(e);await o.connectWithoutSettingPrimary();try{await r(o);}finally{await o.disconnect();}}static query(e){return this.getInstance().query(e)}query(e){if(!this.isConnected)throw new f("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:e},this).query()}getModelManager(e,r,o){return new xr(e,r,o,this.logs)}};Be.instance=null;var Mt=Be;var H=class H{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||+M.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new v("ioredis")});this.redisDataSourceInstance=new H(new r.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:e,password:t?.password||M.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new f("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new v("ioredis")}),r=new e.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:t?.port||+M.REDIS_PORT||6379,password:t?.password||M.REDIS_PASSWORD,...t}),o=new H(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new f("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return H.getValue(e)}catch{throw new f("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),H.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED");S.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return H.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return H.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>H.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return H.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=H.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>H.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>H.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>H.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>H.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>H.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=H.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=>H.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=H.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=>H.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};H.OK="OK";var Aa=H;var Da=class{constructor(t){this.dbType=t,this.migrationName=_t__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 ue(this.dbType);}};async function Jc(i,t){let{bundleRequire:e}=await import('bundle-require').catch(()=>{throw new v("bundle-require")}),r=_t__default.default.isAbsolute(i)?i:_t__default.default.resolve(process.cwd(),i),{mod:o}=await e({filepath:r,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:t??"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","dayjs","commander"]});return o}var Ia=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(n=>n.table_name);case "mssql":return r.recordset.map(n=>n.TABLE_NAME);case "oracledb":return (r.rows||[]).map(n=>Array.isArray(n)?n[0]:n?.TABLE_NAME).filter(n=>typeof n=="string"&&n.length>0);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
187
+ END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return S.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return S.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return S.error(`Failed to release lock: ${n.message||JSON.stringify(o)} (dbType: ${r}, lockKey: ${e}). Full error: ${JSON.stringify(o)}`),false}}hashStringToLockId(e){let r=0;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);r=(r<<5)-r+n,r=r&r;}return Math.abs(r)}async executeOnSlave(e){let r=this.getSlave();if(!r)return e(this);try{return await e(r)}catch(o){let n=o instanceof Error?o:new Error(String(o));if(this.onSlaveServerFailure)return await this.onSlaveServerFailure(n,{host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,type:r.sqlType}),e(this);throw n}}async connectWithoutSettingPrimary(){this.sqlPool=await St(this.sqlType,this.inputDetails),this.ownsPool=true;}};ye=new WeakMap,Wa(Oe,ye,null);var fe=Oe;var Jc=["postgres","cockroachdb"];var Mt=class Mt extends xe{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:Wc(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Xc(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=dr(s).find(h=>h.columnName===t);if(!l)throw new f(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new f(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=K(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),u=K(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),m=r.map((h,g)=>({[d]:e[s.primaryKey],[u]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends Mt{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(m);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof f&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new f(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e);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 c=new Set(Object.keys(m));return t.every(p=>c.has(p))}))throw new f("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(Jc.includes(l))return await ge(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(c=>{u.set(m,[...u.get(m)||[],c[m]]);});}),d.where(m=>{t.forEach(c=>{m.orWhereIn(c,u.get(c)||[]);});}),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 It(this)}static getRelations(){return Zc(this)}static getIndexes(){return ep(this)}static getUniques(){return tp(this)}static column(t,...e){A(...e)(this.prototype,t);}static hasOne(t,...e){Yc(...e)(this.prototype,t);}static hasMany(t,...e){zc(...e)(this.prototype,t);}static belongsTo(t,...e){Hc(...e)(this.prototype,t);}static manyToMany(t,...e){Gc(...e)(this.prototype,t);}static establishConnection(){let t=fe.instance;if(!t)throw new f("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){let e;if(t?.connection)e=t.connection.getModelManager(this);else if(t?.trx)e=t.trx.sql.getModelManager(this);else {let r=this;r.establishConnection(),e=r.sqlInstance.getModelManager(r);}return t?.replicationMode&&e.setReplicationMode(t.replicationMode),e}mergeProps(t){this.constructor.combineProps(this,t);}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new f(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 f(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new f(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 f(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new f(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 f(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new f(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 f(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new f(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};Mt.softDeleteColumn="deletedAt",Mt.softDeleteValue=he();var ae=Mt;var Se=class{constructor(t,e){this.model=ae;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Ar=class extends Se{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Or=class extends Se{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Dr=class extends Se{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var xr=class extends Se{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 yB(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(Gt,e.prototype)||[];o.push({columns:r,name:t??Xt(e.table,r.join("_"))}),k.defineMetadata(Gt,o,e.prototype);}}function hB(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=k.getMetadata(Zt,e.prototype)||[];o.push({columns:r,name:t??ue(e.table,r.join("_"))}),k.defineMetadata(Zt,o,e.prototype);}}function gB(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 A(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(k.getMetadata(zt,e))throw new f("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");k.defineMetadata(zt,r,e);}let n=i.databaseName??K(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??$e(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=k.getMetadata(Yt,e)||[];a.push(s),k.defineMetadata(Yt,a,e);}}A.primary=ef;A.date=mf;A.datetime=cf;A.timestamp=pf;A.time=ff;A.boolean=uf;A.json=yf;A.uuid=sf;A.ulid=af;A.integer=rf;A.float=tf;A.increment=of;A.bigIncrement=nf;A.encryption={symmetric:lf,asymmetric:df};function ef(i={}){return A({...i,primaryKey:true})}function tf(i={}){return A({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 rf(i={}){return A({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 of(i={}){return A({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 nf(i={}){return A({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 sf(i={}){return A({type:"uuid",...i,prepare:t=>t||_e__default.default.randomUUID()})}function af(i={}){return A({type:"ulid",...i,prepare:t=>t||Ga()})}function lf(i){return A({...i,prepare:t=>t&&Ja(i.key,t),serialize:t=>t&&Ha(i.key,t)})}function df(i){return A({...i,prepare:t=>t&&Ya(i.publicKey,t),serialize:t=>t&&za(i.privateKey,t)})}function uf(i={}){return A({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function mf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"DATE_ONLY",t):typeof d=="string"?d:re(d,"DATE_ONLY",t):r?re(new Date,"DATE_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:st(d,void 0,t)};return A({type:"date",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u}})}function cf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"ISO",t):typeof d=="string"?d:re(d,"ISO",t):r?re(new Date,"ISO",t):null,l=d=>{if(d!==void 0)return d===null?null:st(d,void 0,t)};return A({type:"datetime",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u}})}function pf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"TIMESTAMP",t):typeof d=="string"?d:re(d,"TIMESTAMP",t):r?re(new Date,"TIMESTAMP",t):null,l=d=>{if(d!==void 0)return d===null?null:st(d,void 0,t)};return A({type:"timestamp",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u}})}function ff(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=d=>d?e?re(new Date,"TIME_ONLY",t):typeof d=="string"?d:re(d,"TIME_ONLY",t):r?re(new Date,"TIME_ONLY",t):null,l=d=>{if(d!==void 0)return d===null?null:st(d,void 0,t)};return A({type:"time",...s,autoUpdate:e,prepare:d=>{let u=a(d);return o?o(u):u},serialize:d=>{let u=l(d);return n?n(u):u}})}function yf(i={}){return A({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function It(i){try{return k.getMetadata(Yt,i.prototype)||[]}catch{return []}}function Hc(i,t,e){return (r,o)=>{let n=()=>Pe(i().table),s=()=>{let d=r.constructor.table,u=t||n();return Y(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(me,r)||[];l.push(a),k.defineMetadata(me,l,r);}}function Yc(i,t){return (e,r)=>{let o=()=>Pe(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(me,e)||[];s.push(n),k.defineMetadata(me,s,e);}}function zc(i,t){return (e,r)=>{let o=()=>Pe(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=k.getMetadata(me,e)||[];s.push(n),k.defineMetadata(me,s,e);}}function Gc(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=()=>Pe(u),c=()=>Pe(i().table),p=()=>Y(N(d),s?String(s):m()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??p,foreignKey:s?String(s):m,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:u,throughModel:d,leftForeignKey:s?String(s):m,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=k.getMetadata(me,o)||[];g.push(h),k.defineMetadata(me,g,o);}}function Zc(i){return k.getMetadata(me,i.prototype)||[]}function dr(i){return (k.getMetadata(me,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=N(s),l=o();switch(r){case "belongsTo":return new Ar(l,n,a);case "hasOne":return new Dr(l,n,a);case "hasMany":return new Or(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new f("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new xr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:N(e.manyToManyOptions.throughModel),leftForeignKey:N(e.manyToManyOptions.leftForeignKey),rightForeignKey:N(e.manyToManyOptions.rightForeignKey)});default:throw new f("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Xc(i){return k.getMetadata(zt,i.prototype)}function ep(i){return k.getMetadata(Gt,i.prototype)||[]}function tp(i){return k.getMetadata(Zt,i.prototype)||[]}var Pa=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})))}},hf=(i,t)=>new Pa(i,t);var _t=class extends ae{};G([A.datetime({autoCreate:true,openApi:{type:"string",format:"date-time",required:true}})],_t.prototype,"createdAt"),G([A.datetime({autoCreate:true,autoUpdate:true,openApi:{type:"string",format:"date-time",required:true}})],_t.prototype,"updatedAt"),G([A.datetime({openApi:{type:"string",format:"date-time",required:true}})],_t.prototype,"deletedAt");var $a=class extends ae{};G([A.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],$a.prototype,"id");var Ea=class extends ae{};G([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Ea.prototype,"id");var Ve=class extends ae{};G([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Ve.prototype,"id"),G([A({type:"varchar",length:255,openApi:{type:"string",required:true}})],Ve.prototype,"email"),G([A.datetime({autoCreate:true,openApi:{type:"string",format:"date-time",required:true}})],Ve.prototype,"createdAt"),G([A.datetime({autoCreate:true,autoUpdate:true,openApi:{type:"string",format:"date-time",required:true}})],Ve.prototype,"updatedAt"),G([A.datetime({openApi:{type:"string",format:"date-time",required:true}})],Ve.prototype,"deletedAt");var rp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw S.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new v("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw S.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:bf}=Lp__default.default;function op(i){let t=i.name,e=K(t,"snake");return bf(e)}function np(){return {$annotations:{}}}var nt=class extends xe{static get collection(){return this._collection||op(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 f("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){Kr()(this.prototype,t);}static async afterFetch(t){return t}};G([Kr()],nt.prototype,"id");async function Qe(i,t,e){if(!t)return null;let r=np(),o=Va(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=K(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=K(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=K(n,i.modelCaseConvention);r[s]=null;}})),r}async function Ir(i,t,e){return (await Promise.all(t.map(async o=>await Qe(i,o,e)))).filter(o=>o!==null)}var Pr=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,session:this.session}),o=await Qe(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new f("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await Ir(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await Qe(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await Ir(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 Ir(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 S.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 S.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 S.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 S.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 S.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 S.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 $r=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=nt,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new f("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Pr(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await Qe(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await Qe(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new f("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Qe(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new f("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var Ke=class Ke extends Ye{constructor(e){super({type:"mongo",url:e?.url,logs:e?.logs});this.mongoClient=null;this.isConnected=false,this.mongoOptions=e?.options,this.url||(this.url=M.MONGO_URL);}async connect(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true,Ke.instance=this;}async connectWithoutSettingPrimary(){if(!this.url)throw new f("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let e=(await ie.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true;}getCurrentConnection(){if(!this.mongoClient)throw new f("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}static async connectToSecondarySource(e){let r=new Ke(e);return await r.connectWithoutSettingPrimary(),r}static getInstance(){if(!Ke.instance)throw new f("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Ke.instance}startSession(){if(!this.mongoClient)throw new f("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}static async disconnect(){if(!this.instance)throw new f("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(e,r){let o=new Ke(e);await o.connectWithoutSettingPrimary();try{await r(o);}finally{await o.disconnect();}}static query(e){return this.getInstance().query(e)}query(e){if(!this.isConnected)throw new f("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:e},this).query()}getModelManager(e,r,o){return new $r(e,r,o,this.logs)}};Ke.instance=null;var Ct=Ke;var J=class J{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||+M.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new v("ioredis")});this.redisDataSourceInstance=new J(new r.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:e,password:t?.password||M.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new f("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new v("ioredis")}),r=new e.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:t?.port||+M.REDIS_PORT||6379,password:t?.password||M.REDIS_PASSWORD,...t}),o=new J(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new f("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new f("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return J.getValue(e)}catch{throw new f("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new f("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),J.getValue(e)}catch{throw new f("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new f("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new f("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new f("RedisDataSource::disconnect","DISCONNECT_FAILED");S.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new f("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new f("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return J.getValue(e)}catch{throw new f("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return J.getValue(e)}catch{throw new f("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>J.getValue(n)).filter(n=>n!==null)}catch{throw new f("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new f("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new f("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new f("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return J.getValue(r)}catch{throw new f("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=J.getValue(n);return r}catch{throw new f("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>J.getValue(o))}catch{throw new f("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new f("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new f("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new f("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new f("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new f("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>J.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new f("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new f("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new f("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>J.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>J.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>J.getValue(r)).filter(r=>r!==null)}catch{throw new f("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new f("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=J.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=>J.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=J.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=>J.getValue(s)).filter(s=>s!==null)}catch{throw new f("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new f("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new f("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new f("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new f("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new f("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new f("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new f("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new f("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new f("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new f("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new f("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new f("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new f("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new f("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new f("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new f("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new f("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new f("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};J.OK="OK";var va=J;var Ba=class{constructor(t){this.dbType=t,this.migrationName=Rt__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 ce(this.dbType);}};async function ip(i,t){let{bundleRequire:e}=await import('bundle-require').catch(()=>{throw new v("bundle-require")}),r=Rt__default.default.isAbsolute(i)?i:Rt__default.default.resolve(process.cwd(),i),{mod:o}=await e({filepath:r,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:t??"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","dayjs","commander"]});return o}var Qa=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(n=>n.table_name);case "mssql":return r.recordset.map(n=>n.TABLE_NAME);case "oracledb":return (r.rows||[]).map(n=>Array.isArray(n)?n[0]:n?.TABLE_NAME).filter(n=>typeof n=="string"&&n.length>0);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
188
188
  FROM information_schema.tables
189
189
  WHERE table_catalog = '${e}'
190
190
  AND table_schema = 'public'
@@ -298,5 +298,5 @@ CREATE TABLE [migrations] (
298
298
  "id" NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
299
299
  "name" VARCHAR2(255) NOT NULL,
300
300
  "timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
301
- )`}},Se=new Ia;var cf=async(i,t)=>{if(i.endsWith(".ts"))return await import('typescript').catch(()=>{throw new f("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 f("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 f("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")}),Jc(i,t);try{return import(url.pathToFileURL(i).href)}catch{let o=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));try{let n=o(i);return {default:n.default||n,...n}}catch{throw new f(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function Pr(i,t){switch(i){case "mariadb":case "mysql":let e=t;return await e.query(Se.migrationTableTemplateMysql()),(await e.query(Se.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":let o=t;return await o.query(Se.migrationTableTemplatePg()),(await o.query(Se.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await Yc(Se.migrationTableTemplateSQLite(),[],t),await Yc(Se.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(Se.migrationTableTemplateMssql()),(await s.request().query(Se.selectAllFromMigrationsTemplate())).recordset;case "oracledb":let d=await t.getConnection();try{try{await d.execute(Se.migrationTableTemplateOracle());}catch(u){if(u.errorNum!==955)throw u}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(u=>({id:u[0],name:u[1],timestamp:u[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function $r(i,t,e){let r=yf(t),o=[];for(let n of r){let s=await ff(n,t,e),a=new s(i||M.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function pf(i,t){let e=await cf(i,t);if(!e.default)throw new f("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}async function ff(i,t=M.MIGRATION_PATH||"database/migrations",e){t=_t.join(t,i);let r=_t__default.default.resolve(process.cwd(),t),o=await pf(r,e);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function yf(i){let t=process.cwd(),e=_t__default.default.resolve(i||M.MIGRATION_PATH||"database/migrations"),r=_t__default.default.resolve(t,e);try{let o=Rc__default.default.readdirSync(r).filter(n=>{let s=_t__default.default.extname(n),a=_t__default.default.join(r,n);return Rc__default.default.statSync(a).isFile()&&(s===".ts"||s===".js")});if(o.length)return o;throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}catch{throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}}async function Yc(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function xa(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;S.info("Rolling back migrations for database type: "+n);try{let l=await Pr(n,i.getPool()),d=await $r(n,e,r),m=l.map(p=>p.name),u=d.filter(p=>m.includes(p.migrationName));if(u.length===0){S.info("No pending migrations.");return}if(t);let c=new Qe(i);s&&(a=await i.startTransaction(),i=a.sql),await c.downMigrations(u),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}S.info("Migrations rolled back successfully");}async function Pa(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;S.info("Running migrations for database type: "+n);try{let l=await Pr(n,i.getPool()),m=(await $r(n,e,r)).filter(c=>!l.map(p=>p.name).includes(c.migrationName));if(!m.length){S.info("No pending migrations.");return}if(t);let u=new Qe(i);s&&(a=await i.startTransaction(),i=a.sql),await u.upMigrations(m),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}S.info("Migrations ran successfully");}var Qe=class{constructor(t){this.migrationTable="migrations";this.sql=t||pe.instance;}async upMigrations(t){for(let e of t){S.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){S.info(`Rolling back migration ${e.migrationName}`),await e.down();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.deleteMigrationFromMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async addMigrationToMigrationTable(t){let e=new Date,r=this.sql.getDbType()==="oracledb"?e:e.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"");await this.sql.query(this.migrationTable).insert({name:t.migrationName,timestamp:r});}async deleteMigrationFromMigrationTable(t){await this.sql.query(this.migrationTable).where("name",t.migrationName).delete();}},$a=class{constructor(t=M.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){M.MIGRATION_PATH=this.migrationPath;let e;if(this.sqlDataSourceInput instanceof pe)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new pe(r),await e.connect();}return t==="up"?Pa(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):xa(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},hf=(i,t)=>new $a(i,t);var Ea=class{constructor(t){this.logger=S;this.sqlDataSource=t;}};exports.AutogeneratedModel=Oa;exports.BaseSeeder=Ea;exports.Collection=rt;exports.HysteriaError=f;exports.InMemoryAdapter=Rt;exports.Migration=Da;exports.Model=ae;exports.ModelQueryBuilder=tt;exports.MongoDataSource=Mt;exports.RawNode=C;exports.RedisCacheAdapter=Uc;exports.SqlDataSource=pe;exports.TimestampedModel=qt;exports.UserMixin=Ue;exports.UuidModel=Ra;exports.belongsTo=vc;exports.column=O;exports.createModelFactory=of;exports.defineMigrator=hf;exports.generateOpenApiModel=Zf;exports.generateOpenApiModelSchema=Xf;exports.generateOpenApiModelWithMetadata=Ja;exports.getCollectionProperties=ka;exports.getIndexes=Fc;exports.getModelColumns=Dt;exports.getPrimaryKey=Lc;exports.getRelations=ar;exports.getRelationsMetadata=Kc;exports.getUniques=jc;exports.hasMany=Qc;exports.hasOne=Bc;exports.index=Pv;exports.logger=S;exports.manyToMany=kc;exports.property=Br;exports.redis=Aa;exports.unique=$v;exports.view=Ev;exports.withPerformance=L;//# sourceMappingURL=index.cjs.map
301
+ )`}},qe=new Qa;var Mf=async(i,t)=>{if(i.endsWith(".ts"))return await import('typescript').catch(()=>{throw new f("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 f("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 f("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")}),ip(i,t);try{return import(url.pathToFileURL(i).href)}catch{let o=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));try{let n=o(i);return {default:n.default||n,...n}}catch{throw new f(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function Er(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 lp(qe.migrationTableTemplateSQLite(),[],t),await lp(qe.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(qe.migrationTableTemplateMssql()),(await s.request().query(qe.selectAllFromMigrationsTemplate())).recordset;case "oracledb":let d=await t.getConnection();try{try{await d.execute(qe.migrationTableTemplateOracle());}catch(m){if(m.errorNum!==955)throw m}return ((await d.execute('SELECT * FROM "migrations"')).rows||[]).map(m=>({id:m[0],name:m[1],timestamp:m[2]}))}finally{await d.close();}default:throw new f("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function vr(i,t,e){let r=Rf(t),o=[];for(let n of r){let s=await Cf(n,t,e),a=new s(i||M.DB_TYPE);a.migrationName=n,o.push(a);}return o}async function _f(i,t){let e=await Mf(i,t);if(!e.default)throw new f("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}async function Cf(i,t=M.MIGRATION_PATH||"database/migrations",e){t=Rt.join(t,i);let r=Rt__default.default.resolve(process.cwd(),t),o=await _f(r,e);if(!o)throw new f("MigrationUtils::findMigrationModule migrations module not found for migration: "+i,"MIGRATION_MODULE_NOT_FOUND");return o}function Rf(i){let t=process.cwd(),e=Rt__default.default.resolve(i||M.MIGRATION_PATH||"database/migrations"),r=Rt__default.default.resolve(t,e);try{let o=Kc__default.default.readdirSync(r).filter(n=>{let s=Rt__default.default.extname(n),a=Rt__default.default.join(r,n);return Kc__default.default.statSync(a).isFile()&&(s===".ts"||s===".js")});if(o.length)return o;throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}catch{throw new f("MigrationUtils::findMigrationNames No database migration files found on path: "+r,"MIGRATION_MODULE_NOT_FOUND")}}async function lp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function Ka(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;S.info("Rolling back migrations for database type: "+n);try{let l=await Er(n,i.getPool()),d=await vr(n,e,r),u=l.map(p=>p.name),m=d.filter(p=>u.includes(p.migrationName));if(m.length===0){S.info("No pending migrations.");return}if(t);let c=new ke(i);s&&(a=await i.startTransaction(),i=a.sql),await c.downMigrations(m),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}S.info("Migrations rolled back successfully");}async function ka(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;S.info("Running migrations for database type: "+n);try{let l=await Er(n,i.getPool()),u=(await vr(n,e,r)).filter(c=>!l.map(p=>p.name).includes(c.migrationName));if(!u.length){S.info("No pending migrations.");return}if(t);let m=new ke(i);s&&(a=await i.startTransaction(),i=a.sql),await m.upMigrations(u),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}S.info("Migrations ran successfully");}var ke=class{constructor(t){this.migrationTable="migrations";this.sql=t||fe.instance;}async upMigrations(t){for(let e of t){S.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){S.info(`Rolling back migration ${e.migrationName}`),await e.down();let r=e.schema.queryStatements;for(let o of r)o&&await this.sql.rawQuery(o);await this.deleteMigrationFromMigrationTable(e),e.afterMigration&&await e.afterMigration(this.sql);}}async addMigrationToMigrationTable(t){let e=new Date,r=this.sql.getDbType()==="oracledb"?e:e.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"");await this.sql.query(this.migrationTable).insert({name:t.migrationName,timestamp:r});}async deleteMigrationFromMigrationTable(t){await this.sql.query(this.migrationTable).where("name",t.migrationName).delete();}},La=class{constructor(t=M.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){M.MIGRATION_PATH=this.migrationPath;let e;if(this.sqlDataSourceInput instanceof fe)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new fe(r),await e.connect();}return t==="up"?ka(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):Ka(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},Af=(i,t)=>new La(i,t);var ja=class{constructor(t){this.logger=S;this.sqlDataSource=t;}};exports.AutogeneratedModel=Ea;exports.BaseSeeder=ja;exports.Collection=nt;exports.HysteriaError=f;exports.InMemoryAdapter=Ot;exports.Migration=Ba;exports.Model=ae;exports.ModelQueryBuilder=ot;exports.MongoDataSource=Ct;exports.RawNode=C;exports.RedisCacheAdapter=rp;exports.SqlDataSource=fe;exports.TimestampedModel=_t;exports.UserMixin=Ve;exports.UuidModel=$a;exports.belongsTo=Hc;exports.column=A;exports.createModelFactory=hf;exports.defineMigrator=Af;exports.generateOpenApiModel=uy;exports.generateOpenApiModelSchema=my;exports.generateOpenApiModelWithMetadata=tl;exports.getCollectionProperties=Va;exports.getIndexes=ep;exports.getModelColumns=It;exports.getPrimaryKey=Xc;exports.getRelations=dr;exports.getRelationsMetadata=Zc;exports.getUniques=tp;exports.hasMany=zc;exports.hasOne=Yc;exports.index=yB;exports.logger=S;exports.manyToMany=Gc;exports.property=Kr;exports.redis=va;exports.unique=hB;exports.view=gB;exports.withPerformance=L;//# sourceMappingURL=index.cjs.map
302
302
  //# sourceMappingURL=index.cjs.map